Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 856
Zach Sugano Avatar asked Jan 17 '17 07:01

Zach Sugano


People also ask

How does Django validate file extensions?

From django 1.11, you can also use FileExtensionValidator. Note this must be used on a FileField and won't work on a CharField (for example), since the validator validates on value.name. Validating just the file name extension is not sufficient.


3 Answers

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.

like image 154
K.A Avatar answered Oct 01 '22 17:10

K.A


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

like image 26
e4c5 Avatar answered Oct 01 '22 16:10

e4c5


Also, you should use verify() as follows:

from PIL import Image
im = Image.open(model.file)
im.verify()
like image 28
matus moravcik Avatar answered Oct 01 '22 18:10

matus moravcik