[Django]-The 'photo' attribute has no file associated with it

10👍

I solved this using an answer of Stackoverflow, in the Model:

@property
def photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url

In the template, using default_if_none as for default url:

<img src="{{ person.photo_url|default_if_none:'#' }}" />

This actually provides me correct answers after lots of searching and spending many times.

Hope it will helps other to load images in the django template.

👤ohid

1👍

My dear friend, ohid’s solving is good but not enough because If user hasn’t profile picture you should show default image. 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="{{ person.get_photo_url }}" class="img-responsive thumbnail " alt="img">

0👍

Try returning the “full URL” by not calling the FileField field/property name without the .url part e.g. person.photo and not person.photo.url.

N/B: I have only tested it on a REST API in a DRF(djangorestframework) serializer class am not sure if it’ll work for django template’s but it’s worth a try

👤Mitch

0👍

May be your ImageField is not getting any image at some point, but somewhere else you are trying to use the path of the image(which is non-existent). Others have also pointed the same thing. This can happen in the template {{ post.post_image.url }} or in the views.py or even in the models.py when you are trying to preprocess the image before saving the image. Where ever you are using it be careful and use try-except block.

from PIL import Image     # I was using pillow to pre-process
...
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    try:
        img = Image.open(self.post_image.path)
    except:
        print("Do something.. break or return")
        return  

0👍

Delete all the previous records which have no image attribute or use

<img src="{{ person.photo_url|default_if_none:'#' }}" />

Leave a comment