[Answered ]-Django 'unicode' object has no attribute 'size'

1👍

You’d have to do more than just check the image field us in the cleaned data. I suspect you can do something like;

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👍

In the case where someone uploads an invalid image, you need to check for an AttributeException, however you’re not returning the cleaned data value, even if it’s None. If you don’t return a value outside of the conditional statement(s), your form will never be valid.

Use the static .get() method, present on all Python dictionaries, to get the thumbnail value. If the key isn’t there, the return value will be None. Checking for a key in a dictionary that doesn’t exist will raise a KeyError exception.

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

Leave a comment