我有一个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() …Run Code Online (Sandbox Code Playgroud)