[Solved]-How to check that an uploaded file is a valid Image in Django

10👍

Good news, you don’t need to do this:

class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)

Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.

https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ImageField

👤e4c5

4👍

Also, you should use verify() as follows:

from PIL import Image
im = Image.open(model.file)
im.verify()

2👍

you can use a ‘Pillow’ with ‘try,except ‘block, before insert image/data to a database or use it where you want,

like my following example for submit ticket support form , ‘view.py’ file :

from PIL import Image
    
    if request.method=='POST':
       # check if attachment file is not empty inside try/except to pass django error.
        try:
            ticket_attachmet_image = request.FILES["q_attachment_image"]
        except:
            ticket_attachmet_image = None

       # check if uploaded image is valid (for example not video file ) .
        if not ticket_attachmet_image == None:
            try:
                Image.open(ticket_attachmet_image)
            except:
                messages.warning(request, 'sorry, your image is invalid')
                return redirect('your_url_name')

#done.

👤K.A

0👍

if 'image' in request.FILES['image'].content_type:
    # Some code
else:
    # the file is not image

The ImageField doesn’t work when the form is not created by the form.py

In fact, if we upload a file, that is not an image, and save it in the image field, it wouldn’t raise any error so, the content_type of the file must be checked before saving.

Leave a comment