ModelForms and file uploads
We’ve seen how using form.ImageField
on a form can prevent non-images from being uploaded. We’ve also seen how models.ImageField
makes it easy to store an image for a model. But we need to be aware that Django does not stop you from setting a non-image file to ImageField
. For example, consider a form that has both FileField
and ImageField
:
class ExampleForm(forms.Form): uploaded_file = forms.FileField() uploaded_image = forms.ImageField()
In the following view, the form would not validate if the uploaded_image
field on the form was not an image, so some data validity is ensured for uploaded data. The following is an example of this:
def view(request): form = ExampleForm(request.POST, request.FILES) if form.is_valid(): m = ExampleModel() m.file_field...