简体   繁体   中英

Django MEDIA_URL not working in template

I've read various answers on how to do this, but still can't seem to get it working.

settings.py

MEDIA_ROOT = 'c:/jaskaran/dropbox/edmhunters/hunt/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS = (
  "django.contrib.auth.context_processors.auth",
  "django.core.context_processors.media",
)

I have a 'media/img/' folder in my Django app and a 'static'folder as well.

view.py

def top100(request):
    top_100_list = DJ.objects.exclude(rank__isnull=True).order_by('rank')
    context = {'top_100_list': top_100_list}
    return render_to_response('hunt/top100.html', context_instance=RequestContext(request, context))

urls.py

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is how i'm accessing the image in the Django template <img src="{{ MEDIA_URL }}{{ dj.img }}">

The image url doesn't add the MEDIA_URL to the image link.

What's missing in this code?

Sorry, noob mistake. I was using the <img src="{{ MEDIA_URL }}{{ dj.img }}"> in the wrong HTML file.

Your call to render_to_response looks like the issue, here.

return render_to_response('hunt/top100.html', context_instance=RequestContext(request, context))

should instead be:

return render_to_response('hunt/top100.html', context, context_instance=RequestContext(request))

Writing it the django way in the template by appending url to the model field name ie

<img src="{{ dj.img.url }}">

Also works and even more cleaner code compared to:

<img src="{{ MEDIA_URL }}{{ dj.img }}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM