Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django validating ImageField dimensions etc

Tags:

django

I have a custom clean method below:

def clean_image(self):
    image = self.cleaned_data['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

The problem scenario is this:

An image has been uploaded. I now want to clear it using the checkbox that appears using the ImageField widget. When submitting the form to make this clear take place the clear does not.

If I remove my custom clean method the clear does work. Therefore I guess my method is doing something wrong.

like image 881
user973347 Avatar asked Sep 30 '11 15:09

user973347


1 Answers

There are 3 problems when django realize this validations:

  1. Django need obtain the value of these field, always need return a value
  2. Need put class Meta with the name of the model you used.
  3. In this sentences need put .get this way

    self.cleaned_data.get['image']
    
  4. The code looks like this:

    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
    
like image 129
Gianfranco Lemmo Avatar answered Nov 15 '22 11:11

Gianfranco Lemmo