Search code examples
pythondjangofile-upload

Is the Basic File Upload example in the Django documentation correct?


I'm using python 3.10.5 with django 4.2.2.

The djangoproject documentation for a Basic File Upload has the following example for uploading a file:

Consider a form containing a FileField:

forms.py

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

This is my upload.html:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h1>File Upload</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="file" required>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

When I run that code, it fails the...

if form.is_valid()

...test in views.py because "title" is empty, but it's defined as required in the forms.py. If I simply comment out the...

title = forms.CharField(max_length=50)

...line from forms.py, then it works fine, so what is that "title = forms.CharField(max_length=50)" line for in forms.py?


Solution

  • As suggested by Willem VO supports mod strike, simply use {{ form }} in place of the...

    <input type="file" name="file" required>
    

    ...line in upload.html.

    NEW upload.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>File Upload</title>
    </head>
    <body>
        <h1>File Upload</h1>
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ form }}
            <button type="submit">Upload</button>
        </form>
    </body>
    </html>