我在下面有一个自定义清洁方法:
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
问题场景是:
已上传图片。我现在想要使用ImageField小部件显示的复选框清除它。在提交表格时,要明确表示不清楚。
如果我删除自定义清理方法,则清除确实有效。因此我猜我的方法做错了。
答案 0 :(得分:9)
当django意识到这种验证时,有3个问题:
在这句话中需要把这种方式放进去。
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, 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
答案 1 :(得分:0)
我认为它不是从cleaning_data返回图像。您应该检查一下,因为您的编码看起来很好。