Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Image for Django easy_thumbnails

I have a model with an ImageField that I display using easy_thumbnails (|thumbnail_url).
My question is how do I display a default image if the ImageField is empty?
I would like this logic in the Model/View, NOT in the html/template.

e.g.:

DEFAULT_PICTURE = 'default.jpg'

def get_picture(self):
    if self.picture:
        return self.picture
    else:
        from DEFAULT_PICTURE

What object should get_picture() return that is compatible with easy_thumbnails?
I tried to create a new File object, like here, but it did not work.
Can you kindly provide a working example of returning an existing file to display with easy_thumbnails?

like image 464
nak Avatar asked Mar 22 '23 16:03

nak


1 Answers

Chris (easy_thumbnails) answered here, and also on SO.

His suggestion to create a new ImageFieldFile is good, but easy_thumbnails stilled failed because the newly created ImageFieldFile had an empty instance.
So either set instance = self:

DEFAULT_PICTURE = 'default.jpg'

def get_picture(self):
    if self.picture:
        return self.picture
    else:
        return ImageFieldFile(instance=self, field=FileField(), name=DEFAULT_PICTURE)

or change alias.py line 116:

if not hasattr(target, 'instance'):
    return None

should be...

if not hasattr(target, 'instance') or not target.instance:
    return None
like image 63
nak Avatar answered Apr 02 '23 07:04

nak