File uploads with Django forms
In Chapter 6, Forms, we saw how Django makes it easy to define forms and automatically render them to HTML. In the previous example, we defined our form manually and wrote the HTML. We can replace this with a Django form and implement the file input with a FileField
constructor.
Here’s how FileField
is defined on a form:
from django import forms class ExampleForm(forms.Form): file_upload = forms.FileField()
The FileField
constructor can take the following keyword arguments:
Required
: This should beTrue
for required fields andFalse
if the field is optionalmax_length
: This refers to the maximum length of the filename of the file being uploadedallow_empty_file
: A field with this argument is considered to be valid even if the uploaded file is empty (has a size of 0)
Apart from these three keyword arguments, the constructor can also accept the standard Field
arguments, such as widget
. The default...