django的“ unicode”对象没有属性“ 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")

在这里,如果我什么也没有上传,它应该给出错误“无法读取上传的图像”,但是它给出了错误。

这有什么问题吗?

markwalker_

您不仅需要检查清理数据中的图像字段,还需要做更多的事情。我怀疑你可以做类似的事情;

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章