Django File Uploads with Django Forms


First of all we need to add MEDIA_ROOT and MEDIA_URL to our file

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Also here you will work with ImageField, so remember in such cases install Pillow library (pip install pillow). Otherwise, you will have such error:

ImportError: No module named PIL

Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. Pillow is backwards compatible with PIL.

Django comes with two form fields to upload files to the server, FileField and ImageField, the following is an example of using these two fields in our form

from django import forms

class UploadDocumentForm(forms.Form):
    file = forms.FileField()
    image = forms.ImageField()

from django.shortcuts import render
from .forms import UploadDocumentForm

def upload_doc(request):
    form = UploadDocumentForm()
    if request.method == 'POST':
        form = UploadDocumentForm(request.POST, request.FILES)  # Do not forget to add: request.FILES
        if form.is_valid():
            # Do something with our files or simply save them
            # if saved, our files would be located in media/ folder under the project's base folder
    return render(request, 'upload_doc.html', locals())


    <head>File Uploads</head>
        <form enctype="multipart/form-data" action="" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" -->
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Save">