django 'unicode' 对象没有属性 'size'

django 'unicode' object has no attribute 'size'

我想验证我的表单,其中用户不能上传大小大于 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")

在这里,如果我什么都不上传,它应该报错 "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,但是您没有 return 清理数据值,即使它是 None.如果您没有 return 条件语句之外的值,您的表单将 永远不会 有效。

使用所有 Python 词典中的静态 .get() 方法获取 thumbnail 值。如果密钥不存在,return 值将为 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