Django {{MEDIA_URL}}空白@DEPRECATED

Ath*_*ion 32 django django-templates media-url

在过去的几个小时里,我一直在争论这个问题.我无法显示{{MEDIA_URL}}

在settings.py中

..
MEDIA_URL = 'http://10.10.0.106/ame/'
..
TEMPLATE_CONTEXT_PROCESSORS = (
  "django.contrib.auth.context_processors.auth",
  "django.core.context_processors.media",
)
..
Run Code Online (Sandbox Code Playgroud)

在我看来,我有

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})
Run Code Online (Sandbox Code Playgroud)

然后我有一个base.html和问题/ latest.html

{% extends 'base.html' %}
<img class="hl" src="{{ MEDIA_URL }}/images/avatar.jpg" /></a>
Run Code Online (Sandbox Code Playgroud)

但MEDIA_URL显示空白,我认为这是它的假设,但也许我错了.

更新 最新版本修复了这些问题.

Sam*_*lan 30

您需要RequestContextrender_to_responsefor中添加要处理的上下文处理器.

在你的情况下:

from django.template.context import RequestContext

context = {'latest': p}
render_to_response('Question/latest.html',
                   context_instance=RequestContext(request, context))
Run Code Online (Sandbox Code Playgroud)

来自文档:

context_instance

用于呈现模板的上下文实例.默认情况下,模板将使用Context实例(使用字典中的值填充)进行渲染.如果需要使用上下文处理器,请使用RequestContext实例呈现模板.

  • Awww谢谢你,我认为他们需要为开始django的人更好地指出这一点.MEDIA_URL对于设计和便携性非常重要. (4认同)

Shr*_*rey 22

添加媒体模板上下文处理器也可以完成工作

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
)
Run Code Online (Sandbox Code Playgroud)

  • 对于讲英语的人来说https://docs.djangoproject.com/en/1.9/ref/settings/#media-url (5认同)
  • /!\不推荐使用,您应该使用TEMPLATE dict和选项context_processors:https://docs.djangoproject.com/fr/1.9/ref/settings/#media-url (4认同)