Zach Sugano
Zach Sugano

Reputation: 1607

How to check that an uploaded file is a valid Image in Django

I have an ImageField in one of my models so that users can upload an image. When a user submits an upload form, I want to verify that the file in question is a fully valid and displayable image.

I tried using PIL to verify that the image was in fact authentic, but using

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

No matter what file I give it though, it always throws an exception.

Anyone know of an easy way to verify the file?

Upvotes: 14

Views: 12176

Answers (4)

K.A
K.A

Reputation: 1659

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.

Upvotes: 2

Amin Mir
Amin Mir

Reputation: 642

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.

Upvotes: 0

matus moravcik
matus moravcik

Reputation: 151

Also, you should use verify() as follows:

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

Upvotes: 5

e4c5
e4c5

Reputation: 53734

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

Upvotes: 10

Related Questions