我有一个自定义清洁方法如下:
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
问题场景是这样的:
解决方法
当django实现这个验证时有3个问题:
> Django需要获取这些字段的值,总是需要返回一个值
>需要将类Meta与您使用的模型的名称放在一起.
>在这句话中需要把这种方式放进去
self.cleaned_data.get['image']
>代码如下所示:
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,*.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