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

时间:2015-01-31 11:43:45

标签: django forms validation

我想验证我的表单,用户无法上传大小超过512 Kb的图片...如果文件大小超过512 Kb,我的验证工作正常,但是当我上传任何内容时,它会显示错误{{1}但我已经检查过图像应该是真的

unicode object has no attribute size

如果我上传任何内容,它应该给出错误“无法读取上传的图像”,但它会给出错误..

这里有什么问题?

2 个答案:

答案 0 :(得分:1)

您必须做的不仅仅是检查已清理数据中的图像字段。我怀疑你可以做点什么;

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

答案 1 :(得分:1)

如果有人上传了无效图片,您需要检查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