views:

372

answers:

3

I'm using an ImageField to store profile pictures on my model.

How do I set it to return a default image if no image is defined?

A: 

you could try this in your view:

{% ifequal object.image None %}
    <img src="DEFAULT_IMAGE" />
{% else %}
    display image
{% endifequal %}
jobscry
{% if obj.image %}display{% else %}<img src="default" />{% endif %} -- burn all {% ifequal %} tags!!
SmileyChris
This is what I'm doing, but that's duplicating code, no?
Yuvi
if you need it in all your views you could use an include, you could call it show_obj_image.html then use {% include "show_obj_image.html" %}
jobscry
+3  A: 

I haven't tried this, but I'm relatively sure you can just set it as a default in your field.

pic = models.ImageField(upload_to='blah', default='path/to/my/default/image.jpg')

EDIT: Stupid StackOverflow won't let me comment on other people's answers, but that old snippet is not what you want. I highly recommend django-imagekit because it does tons of great image resizing and manipulation stuff very easily and cleanly.

ericflo
Thanks for that link - looks like I'll be using that one down the road quite a bit.
Yuvi
@ericflo: Yeah, StackOverflow doesn't let you leave comment until you have 50 reputation, which is kind of annoying.
R. Bemrose
Actually this does work. Although perhaps not ideally... It behaves more like 'initial' than 'default' because it sets it to the default value on creation, but if you delete the image it does not set the value back to your default. So you might want to establish that default value as a constant someplace and set it back manually on delete.
John Mee
+1  A: 

You could theoretically also use a function within your model definition. But I dont know whether this is good practice:

class Image(model.Models):
    image = ....

    def getImage(self):
        if not self.image:
            # depending on your template
            return default_path or default_image_object

and then within a template

   <img src="img.getImage" />

This gives you a great deal of flexibility for the future...

I'm using sorl for thumbnails generation with great success

msmart
Django already provides the url() method for this purpose: <img src="{{my_image.url}}">
shanyu