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.
There are 3 problems when django realize this validations:
In this sentences need put .get this way
self.cleaned_data.get['image']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With