Question

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?

Was it helpful?

Solution

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

OTHER TIPS

This is the code that I have used previously. It could probably be optimized a bit (and probably shouldn't have the hard coded media path), but it worked well for my small project.

def get_picture(self):
    if self.picture:
         return '<img src="%s" />' % self.picture['thumbnail'].url
    return '{img src="/media/img/admin/icon-no.gif" alt="No Image"}' 

With this, you just need to ensure that you have icon-no.gif in the appropriate path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top