【问题标题】:Django {{ MEDIA_URL }} blank @DEPRECATEDDjango {{ MEDIA_URL }} 空白 @DEPRECATED
【发布时间】:2011-04-14 23:38:17
【问题描述】:

在过去的几个小时里,我一直在努力解决这个问题。 我无法显示 {{ 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",
)
..

在我看来我有

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 和 Question/latest.html

{% extends 'base.html' %}
<img class="hl" src="{{ MEDIA_URL }}/images/avatar.jpg" /></a>

但是 MEDIA_URL 显示为空白,我认为这就是它的工作方式,但也许我错了。

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

【问题讨论】:

    标签: django django-templates media-url


    【解决方案1】:

    更新:对于 Django 1.10 用户,媒体和静态上下文处理器已经从 django.core 移到 django.template 中,请阅读以下文章了解更多信息:https://docs.djangoproject.com/en/1.10/ref/templates/api/#django-template-context-processors-media

    【讨论】:

      【解决方案2】:

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

      TEMPLATE_CONTEXT_PROCESSORS = (
          "django.core.context_processors.request",
          "django.contrib.auth.context_processors.auth",
          "django.core.context_processors.media",
          "django.core.context_processors.static",
      )
      

      【讨论】:

      【解决方案3】:

      您需要在render_to_response 中添加RequestContext,以便处理上下文处理器。

      在你的情况下:

      from django.template.context import RequestContext
      
      context = {'latest': p}
      render_to_response('Question/latest.html',
                         context_instance=RequestContext(request, context))
      

      来自docs

      context_instance

      上下文实例 渲染模板。经过 默认情况下,将呈现模板 带有 Context 实例(填充 字典中的值)。如果你需要 要使用上下文处理器,渲染 带有 RequestContext 的模板 而是实例。

      【讨论】:

      • Awww 谢谢,我认为他们需要为刚开始使用 django 的人指出这一点。 MEDIA_URL 对于设计和可移植性都相当重要。
      【解决方案4】:

      除了上面提供的问题可以建议你看看photologue 应用程序。它可以帮助您避免模板文件中的直接链接,而是使用对象。 例如:

      <img src="{{ artist.photo.get_face_photo_url }}" alt="{{ artist.photo.title }}"/>
      

      【讨论】:

        【解决方案5】:

        你也可以使用direct_to_template:

        from django.views.generic.simple import direct_to_template
        ...
        return direct_to_template(request, 'Question/latest.html', {'latest': p})
        

        【讨论】:

        • 这会和render_to_response('Question/latest.html', context_instance=RequestContext(request, context))做同样的事情?
        猜你喜欢
        • 2012-08-05
        • 2011-06-16
        • 2011-07-27
        • 2012-09-03
        • 2023-01-09
        • 2012-01-21
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多