Django: MEDIA_URL is not set in the template

I read a lot of questions and articles, but I can not find what I am 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) 

Be that as it may, my media is being served because when I go to http: // localhost: 8000 / media / path / to / image.jpg , I have my image.

But when in the template I go like this:

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

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

So, my MEDIA_URL not set in the template, and as far as I was looking, I do not see what I missed.

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

+7
python django
Aug 10 '15 at 16:48
source share
2 answers

models.ImageField has a url property that gives you a way to view your image.

You should use artist.artist_image.url instead of manually adding MEDIA_URL to the image name:

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

-

Make sure artist_image not None , otherwise the .url call throws an exception.

+11
Aug 10 '15 at 17:03
source share

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

If this processor is enabled, each RequestContext will contain a MEDIA_URL variable that provides the value of the MEDIA_URL parameter.

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

 context_processors = [ ... 'django.template.context_processors.media', # set this explicitly ] 
+11
Aug 10 '15 at 16:52
source share



All Articles