我有一个Django模型,它有一个图像的上传字段,我试图在存储之前验证图像字段以检查图像大小,并返回优雅的错误消息供用户纠正。
我尝试使用以下代码,但它不起作用
admin.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()
现在第二段代码工作正常,它通过验证过程,但它没有显示简单的错误消息。相反,它会引发异常!如何让它显示错误,以便用户纠正并重试?
P.S使用django 1.4和django-hvad进行翻译,这就是为什么我要继承TranslatableAdmin
此致
答案 0 :(得分:8)
正如 demalexx 所说,您应该使用其他表单来验证您的模型。
class Bonanza(models.Model):
user_profile = models.CharField(max_length = 128)
publish_date = models.DateField()
在您的管理表单中使用任何验证:
class BonanzaAdminForm(forms.ModelForm):
class Meta:
model = Bonanza
def clean(self):
# Validation goes here :)
raise forms.ValidationError("TEST EXCEPTION!")
简单的自动生成管理员:
class BonanzaAdmin(admin.ModelAdmin):
form = BonanzaAdminForm
admin.site.register(Bonanza, BonanzaAdmin)
答案 1 :(得分:1)
您继承了ModelAdmin
,但它没有验证方法。相反,您应该覆盖form
属性以提供自定义表单并向该表单添加验证方法。在admin:https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#adding-custom-validation-to-the-admin