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?
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.
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.
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
Also, you should use verify() as follows:
from PIL import Image
im = Image.open(model.file)
im.verify()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With