Django validating ImageField dimensions etc
I have a custom cl开发者_运维技巧ean 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:
- Django need obtain the value of these field, always need return a value
- Need put class Meta with the name of the model you used.
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
I think it isn't returning image from cleaned_data. You shoudl check that, because your coding looks fine.
精彩评论