[Django]-Django custom validation in model form for imagefield (max file size etc.)

2👍

Just answering here for the record:

The poster didn’t check the form.cleaned_data(), which means that clean_xxx validation didn’t get run.

6👍

The name of method should be clean_<field name>, in this case clean_banner.

For future reference I will place a snippet of code that I used in one recent project (names must be adapted to work with OP code):

from PIL import Image
from django.utils.translation import ugettext as _

def clean_photo(self):
    image = self.cleaned_data.get('photo', False)

    if image:
        img = Image.open(image)
        w, h = img.size

        #validate dimensions
        max_width = max_height = 500
        if w > max_width or h > max_height:
            raise forms.ValidationError(
                _('Please use an image that is smaller or equal to '
                  '%s x %s pixels.' % (max_width, max_height)))

        #validate content type
        main, sub = image.content_type.split('/')
        if not (main == 'image' and sub.lower() in ['jpeg', 'pjpeg', 'png', 'jpg']):
            raise forms.ValidationError(_('Please use a JPEG or PNG image.'))

        #validate file size
        if len(image) > (1 * 1024 * 1024):
            raise forms.ValidationError(_('Image file too large ( maximum 1mb )'))
    else:
        raise forms.ValidationError(_("Couldn't read uploaded image"))
    return image

Leave a comment