Skip to content

Instantly share code, notes, and snippets.

@azhtom
Created January 4, 2014 21:21
Show Gist options
  • Save azhtom/8260885 to your computer and use it in GitHub Desktop.
Save azhtom/8260885 to your computer and use it in GitHub Desktop.
ImageField Size Validation
class Meta:
model = NameModel
def clean_image(self):
image = self.cleaned_data.get['image']
if image:
from django.core.files.images import get_image_dimensions
w, h = get_image_dimensions(image)
if not image.content_type in settings.VALID_IMAGE_FORMATS:
raise forms.ValidationError(u'Only *.gif, *.jpg and *.png images are allowed.')
if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment