JojoL
JojoL

Reputation: 141

Render Default Image, Django

I defined an ImageField in my models.py, with a default image. Each time I create a new user, I can see in the admin that the default image is associated to the user, as I wanted.

The problem is, when I try to render it in my templates, with something like:

{{user.userprofile.profilpic.url}}

it does not work. The image is not displayed.

But if I go into my admin and change it manually, even with the exact same image, it works. It looks like the image is not saved into the db when I create the user.

Here is my models.py:

    class UserProfile(FacebookProfileModel):
       user = models.OneToOneField(User)
       profilpic = models.ImageField(upload_to="profilpics/", default="/my/picture.jpeg")

I wonder how I can fix that. Thank you for your help.

Upvotes: 2

Views: 947

Answers (2)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

You can add a method to your model:

class UserProfile(FacebookProfileModel):
    ... 
    profilepic = ...

    def profilepic_or_default(self, default_path="/images/..."):
        if self.profilepic:
            return self.profilepic
        return default_path

and use it in your tempalte:

{{ myuser.profilepic_or_default }}

Upvotes: 2

jpic
jpic

Reputation: 33410

You could use the default templatefilter:

{% with default_image=STATIC_URL|add:"default_image.jpg" %}
     {{ user.userprofile.profilpic.url|default:default_image }}
{% endwith %}

Upvotes: 3

Related Questions