【问题标题】:Django: Can't render STATIC_URL from settings in templateDjango:无法从模板中的设置呈现 STATIC_URL
【发布时间】:2011-07-25 15:09:28
【问题描述】:

http://docs.djangoproject.com/en/dev/howto/static-files/

这表明我可以在我的模板中使用 STATIC_URL 从 settings.py 中获取值。

模板如下所示:

<link href="{{STATIC_URL}}stylesheets/tabs.css" rel="stylesheet" type="text/css"  media="screen" />

Settings.py 如下所示:

STATIC_ROOT = ''
STATIC_URL = '/static/'

当我转到该页面时,我只会得到&lt;link href="stylesheets/tabs.css",即没有 STATIC_URL。

我错过了什么?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您必须在render_to_response 中使用context_instance=RequestContext(request),例如:

    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
    

    或者使用新的快捷方式render

    正如 Dave 指出的,您应该检查 django.core.context_processors.static 是否在 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 变量中。正如the docs 所说,它默认在那里。

    【讨论】:

    • 您可能还需要添加静态上下文处理器
    • 感谢您的渲染快捷提示 :)
    • 在惩罚了自己一段时间后,我发现您的小评论“django.core.context_processors.static”是过去 24 小时内我听到的最有用的东西。谢谢你
    • @rburhum。哈哈,太好了!我很乐意提供帮助!
    • 我的 settings.py 文件中没有 TEMPLATE_CONTEXT_PROCESSORS 变量,这是怎么回事?或者我该怎么办?
    【解决方案2】:

    不建议直接使用STATIC_URL 变量。请参阅this question 中的accepted answer

    代替

    {{STATIC_URL}}stylesheets/tabs.css
    

    使用

    {% load staticfiles %}
    {% static 'stylesheets/tabs.css' %}
    

    【讨论】:

      【解决方案3】:

      我也有同样的问题,解决方法如下:

      在 settings.py 中 添加:

      django.template.context_processors.static
      

      这里:

      TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': TEMPLATE_DIRS,
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  'django.template.context_processors.debug',
                  'django.template.context_processors.request',
                  'django.template.context_processors.static',
                  'django.contrib.auth.context_processors.auth',
                  'django.contrib.messages.context_processors.messages',
              ],
          },
      },
      

      ]

      【讨论】:

        猜你喜欢
        • 2016-09-18
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2021-02-14
        • 2018-11-09
        • 1970-01-01
        • 2019-04-06
        • 2015-11-14
        相关资源
        最近更新 更多