0

I have a project that gives the user an option to upload an avatar. The upload works fine and, in fact, I can see the avatar in the root / of the project. However, when I navigate /anything_else/, my project can't seem to find the avatar.

Below is the relevant part of the model that handles the upload:

avatar = models.ImageField('profile picture', upload_to='static/media/images/avatars/', null=True, blank=True)

In my user_base.html template, I have the following line that shows the avatar

<img id="profile_pic" src="{{ user.avatar }}" alt="Profile picture" style="width:30px;height:30px;border:0">

So if I upload the picture guitar.jpg and go to mysite.com/static/media/images/avatars/guitar.jpg, it will be found.

However, if I navigate to mysite.com/news/, I still expect to have a viewable avatar, but instead I get a 404. This is because it looks for the image at mysite.com/news/static/media/images/avatars/guitar.jpg

I've heard of template inheritance, but I'm not really sure how to do this. Any ideas?

EDIT

I solved it by changing

<img id="profile_pic" src="{{ user.avatar }}" alt="Profile picture" style="width:30px;height:30px;border:0">

to

<img id="profile_pic" src="/{{ user.avatar }}" alt="Profile picture" style="width:30px;height:30px;border:0">
erip
  • 16,374
  • 11
  • 66
  • 121

1 Answers1

2

The problem is nothing to do with template inheritance, seems like maybe your MEDIA_URL does not start with /

That would mean you have a relative url (see Absolute vs relative URLs)

also I think you need to use <img src="{{ user.avatar.url }}"> in the template

https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.fields.files.FieldFile.url

Community
  • 1
  • 1
Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • `STATIC_URL = '/static/'`. I also tried adding a `/` to the `upload_to` and resulted in a crash. – erip Feb 13 '15 at 17:16
  • sorry I meant `MEDIA_URL`, and no not to the `upload_to` because that's a path on disk not a url – Anentropic Feb 13 '15 at 17:18
  • `MEDIA_URL = ''`. My `media` directory is within my `static`, so I think it should be fine. – erip Feb 13 '15 at 17:21
  • you're doing it wrong, you should set the `MEDIA_URL` properly so you don't have to add random stuff to your templates – Anentropic Feb 14 '15 at 15:58