我想验证我的表单,其中用户无法上传大小大于 512 Kb 的图像...如果文件大小大于 512 Kb,我的验证效果很好,但是当我不上传任何内容时,它会给出错误,说unicode object has no attribute size
但我已经检查了图像应该是真的
class GeneralUserPictureChangeForm(forms.ModelForm):
class Meta:
model = GeneralUser
fields = ("thumbnail",)
def clean_thumbnail(self):
thumbnail = self.cleaned_data['thumbnail']
if thumbnail:
if thumbnail.size > 512*1024:
raise forms.ValidationError("Image file too large ( > 512Kb )")
return thumbnail
else:
raise forms.ValidationError("Couldn't read uploaded image")
在这里,如果我不上传任何内容,它应该给出错误"无法读取上传的图像",但它会给出错误。
这里面有什么问题?
您必须做的不仅仅是检查清理数据中的图像字段。我怀疑你可以做这样的事情;
if thumbnail is not None:
try:
if thumbnail.size > 512*1024:
raise forms.ValidationError("Image file too large ( > 512Kb )")
except AttributeError:
# no image uploaded as it has no size
self._errors['thumbnail'] = _("Please upload an image")
return thumbnail
如果有人上传了无效的图像,则需要检查AttributeException
,但是即使它是None
,您也不会返回清理后的数据值。如果不返回条件语句之外的值,则表单将永远不会有效。
使用所有 Python 字典中存在的静态.get()
方法来获取thumbnail
值。如果键不存在,则返回值将为 None
。检查字典中不存在的键将引发KeyError
异常。
def clean_thumbnail(self):
# .get() will return `None` if the key is missing
thumbnail = self.cleaned_data.get('thumbnail')
if thumbnail:
try:
if thumbnail.size > 512*1024:
raise forms.ValidationError(
"Image file too large ( > 512Kb )")
except AttributeError:
raise forms.ValidationError("Couldn't read uploaded image")
# always return the cleaned data value, even if it's `None`
return thumbnail