我有一个 Django 模型,其中有一个图像上传字段,我正在尝试验证图像字段以在存储之前检查图像大小并返回优雅的错误消息以供用户更正。
我尝试使用以下代码,但它不起作用
管理员.py
class BonanzaAdmin(TranslatableAdmin):
list_display = ['get_bonanza_name', 'user_profile', 'publish_date', 'created_by', 'created_at', 'all_translations']
def clean_image(self):
image = self.cleaned_data.get('image')
if not image:
raise forms.ValidationError("No image!")
else:
w, h = get_image_dimensions(image)
if w != 1170:
raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 1170px" % w)
if h != 500:
raise forms.ValidationError("The image is %i pixel high. It's supposed to be 500px" % h)
return image
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.save()
整个 clean_image() 没有被调用,我也尝试将名称反转为 image_clean() 但也没有工作。无论如何,我试图将验证移至 save_model
class BonanzaAdmin(TranslatableAdmin):
list_display = ['get_bonanza_name', 'user_profile', 'publish_date', 'created_by', 'created_at', 'all_translations']
def save_model(self, request, obj, form, change):
image = obj.image
if not image:
raise forms.ValidationError("No image!")
else:
w, h = get_image_dimensions(image)
if w != 1170:
raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 1170px" % w)
if h != 500:
raise forms.ValidationError("The image is %i pixel high. It's supposed to be 500px" % h)
if not change:
obj.created_by = request.user
obj.save()
现在第二段代码工作正常,它通过了验证过程,但没有显示简单的错误消息。相反,它会引发异常!我怎样才能让它显示错误,以便用户更正并重试?
PS 我正在使用 django 1.4 和 django-hvad 进行翻译,这就是我从 TranslatableAdmin 继承的原因
问候