django {{Media_url}} blank @deprecated
-
04-10-2019 - |
题
在过去的几个小时里,我一直在敲打这个问题。我无法获得{{Media_url}}出现
在设置中
..
MEDIA_URL = 'http://10.10.0.106/ame/'
..
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",
)
..
我认为我有
from django.shortcuts import render_to_response, get_object_or_404
from ame.Question.models import Question
def latest(request):
Question_latest_ten = Question.objects.all().order_by('pub_date')[:10]
p = get_object_or_404(Question_latest_ten)
return render_to_response('Question/latest.html', {'latest': p})
然后我有一个base.html和问题/最新.html
{% extends 'base.html' %}
<img class="hl" src="{{ MEDIA_URL }}/images/avatar.jpg" /></a>
但是Media_url出现空白,我认为这是它应该如何工作的,但也许我错了。
更新最新版本解决了这些问题。
解决方案
添加媒体模板上下文处理器还可以完成工作
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",
"django.core.context_processors.static",
)
其他提示
您需要添加 RequestContext
在你的 render_to_response
为了处理上下文处理器。
在您的情况下:
from django.template.context import RequestContext
context = {'latest': p}
render_to_response('Question/latest.html',
context_instance=RequestContext(request, context))
来自 文档:
context_instance
上下文实例呈现模板。默认情况下,该模板将使用上下文实例渲染(填充了字典中的值)。如果您需要使用上下文处理器,请改用requestContext实例渲染模板。
您也可以使用direct_to_template:
from django.views.generic.simple import direct_to_template
...
return direct_to_template(request, 'Question/latest.html', {'latest': p})
除了上面提供的问题外,还可以建议您看看 光学 应用。它可以帮助您避免模板文件中的直接链接并改用对象。 F.Ex。:
<img src="{{ artist.photo.get_face_photo_url }}" alt="{{ artist.photo.title }}"/>
更新:对于Django 1.10用户,媒体和静态上下文处理器已经在django中移动。 https://docs.djangoproject.com/en/1.10/ref/templates/api/#django-template-context-processors-media
不隶属于 StackOverflow