1

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?

2
  • 1
    If you use {{ form }} it adds a text field for the title, likely the title you want to provide to the file. Commented Jul 3, 2023 at 22:56
  • That did the trick. Now I get it. Thanks so much Willem. Commented Jul 8, 2023 at 4:09

1 Answer 1

1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.