Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: MEDIA_URL not set in template

I've read a lot of question and article but can't find what I'm missing.

Here is my conf :

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(os.path.dirname(__file__),'static').replace('\\', '/'),
)

urls.py

urlpatterns = [
    url(r'^$', include('home.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^artist/', include('artists.urls')),
    url(r'photo/', include('photo.urls'))
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Whatever, my media are served, cause when I go to http://localhost:8000/media/path/to/image.jpg, i have my image.

But when in template I go like this :

<img class="avatar secondary-content" src="{{MEDIA_URL}}{{artist.artist_image}}">

I only have the image path. When I change in html {{MEDIA_URL}} by '/media/', it works.

So it seems my MEDIA_URL is not set in template and as far as I've searched, I can't see what I missed.

I'm on django 1.8.2. If you need any informations, just ask me.

like image 760
Bestasttung Avatar asked Aug 10 '15 16:08

Bestasttung


2 Answers

You need to define the django.template.context_processors.media template context processor in your settings for MEDIA_URL variable to be present in the template context.

If this processor is enabled, every RequestContext will contain a variable MEDIA_URL, providing the value of the MEDIA_URL setting.

Including this in your settings will include MEDIA_URL in the template context. It is not included by default in Django 1.8 settings. We need to set it explicitly.

context_processors = [
    ...
    'django.template.context_processors.media', # set this explicitly
]
like image 174
Rahul Gupta Avatar answered Nov 15 '22 15:11

Rahul Gupta


models.ImageField has a property called url which gives you the browsable path of your image.

You should be using artist.artist_image.url instead of prepending MEDIA_URL to your image name manually:

<img class="avatar secondary-content" src="{{artist.artist_image.url}}" />

--

Make sure artist_image is not None, otherwise calling .url throws an exception.

like image 36
Ozgur Vatansever Avatar answered Nov 15 '22 15:11

Ozgur Vatansever