Merge pull request #252 from kaedroho/image-validation-fix

More robust image file validation
pull/217/head^2
Karl Hobley 2014-05-19 09:59:13 +01:00
commit e00bf58914
2 zmienionych plików z 31 dodań i 7 usunięć

Wyświetl plik

@ -4,7 +4,7 @@ import os.path
from taggit.managers import TaggableManager
from django.core.files import File
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist, ValidationError
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
@ -17,6 +17,8 @@ from unidecode import unidecode
from wagtail.wagtailadmin.taggable import TagSearchable
from wagtail.wagtailimages.backends import get_image_backend
from .utils import validate_image_format
class AbstractImage(models.Model, TagSearchable):
title = models.CharField(max_length=255, verbose_name=_('Title') )
@ -34,12 +36,7 @@ class AbstractImage(models.Model, TagSearchable):
filename = prefix[:-1] + dot + extension
return os.path.join(folder_name, filename)
def file_extension_validator(ffile):
extension = ffile.name.split(".")[-1].lower()
if extension not in ["gif", "jpg", "jpeg", "png"]:
raise ValidationError(_("Not a valid image format. Please use a gif, jpeg or png file instead."))
file = models.ImageField(verbose_name=_('File'), upload_to=get_upload_to, width_field='width', height_field='height', validators=[file_extension_validator])
file = models.ImageField(verbose_name=_('File'), upload_to=get_upload_to, width_field='width', height_field='height', validators=[validate_image_format])
width = models.IntegerField(editable=False)
height = models.IntegerField(editable=False)
created_at = models.DateTimeField(auto_now_add=True)

Wyświetl plik

@ -0,0 +1,27 @@
import os
from PIL import Image
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
def validate_image_format(f):
# Check file extension
extension = os.path.splitext(f.name)[1].lower()[1:]
if extension == 'jpg':
extension = 'jpeg'
if extension not in ['gif', 'jpeg', 'png']:
raise ValidationError(_("Not a valid image. Please use a gif, jpeg or png file with the correct file extension."))
# Open image file
file_position = f.tell()
f.seek(0)
image = Image.open(f)
f.seek(file_position)
# Check that the internal format matches the extension
if image.format.upper() != extension.upper():
raise ValidationError(_("Not a valid %s image. Please use a gif, jpeg or png file with the correct file extension.") % (extension.upper()))