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...