简体   繁体   English

Django MEDIA_URL无法使用模板

[英]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 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. 我的Django应用程序中有一个'media / img /'文件夹,还有一个'static'文件夹。

view.py 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 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 }}"> 这就是我在Django模板中访问图像的方式<img src="{{ MEDIA_URL }}{{ dj.img }}">

The image url doesn't add the MEDIA_URL to the image link. 图像网址不会将MEDIA_URL添加到图像链接。

What's missing in this code? 这段代码中缺少什么?

Sorry, noob mistake. 对不起,noob错误。 I was using the <img src="{{ MEDIA_URL }}{{ dj.img }}"> in the wrong HTML file. 我在错误的HTML文件中使用了<img src="{{ MEDIA_URL }}{{ dj.img }}">

Your call to render_to_response looks like the issue, here. 您对render_to_response的调用看起来就像问题一样。

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 通过将url附加到模型字段名称即将其写入模板中的django方式

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

Also works and even more cleaner code compared to: 与以下相比,还可以工作,甚至更清晰的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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