Django checking ImageField sizes, etc.

I have a custom clean method:

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 as follows:

Uploaded image. Now I want to clear it using the checkbox that appears with the ImageField widget. When submitting a form to make it clear, clear does not.

If I remove my own clean method, clarity will work. Therefore, I assume that my method is doing something wrong.

+6
source share
2 answers

There are three problems when django implements these checks:

  • Django needs to get the value of this field, you always need to return the value
  • You need to put the Meta class with the name of the model used.
  • In these sentences you need to put .get in this way

     self.cleaned_data.get['image'] 
  • The code is as follows:

     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 
+9
source

I think it does not return an image from cleaned_data. You shoudl check this out because your coding looks good.

0
source

Source: https://habr.com/ru/post/898385/


All Articles