Django The 'image' attribute has no file associated with it

bob and person are the same object,

person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)

So you can use just person for it.

In your template, check image exist or not first,

{% if person.image %}
    <img src="{{ person.image.url }}">
{% endif %}

The better approach which would not violate DRY is to add a helper method to the model class like:

@property
def image_url(self):
    if self.image and hasattr(self.image, 'url'):
        return self.image.url

and use default_if_none template filter to provide default url:

<img src="{{ object.image_url|default_if_none:'#' }}" />

My dear friend, others solvings are good but not enough because If user hasn't profile picture you should show default image easily (not need migration). So you can follow below steps:

Add this method to your person model:

@property
def get_photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url
    else:
        return "/static/images/user.jpg"

You can use any path (/media, /static etc.) but don't forget putting default user photo as user.jpg to your path.

And change your code in template like below:

<img src="{{ profile.get_photo_url }}" class="img-responsive thumbnail " alt="img">

Tags:

Django