【问题标题】:Django STATIC_URL is not workingDjango STATIC_URL 不工作
【发布时间】:2012-07-25 21:25:23
【问题描述】:

Django 版本是 1.4。我已经阅读了official document,并用谷歌搜索了我的问题。

首先我按照官方文档Managing static filessettings.py中添加了这个:

TEMPLATE_CONTEXT_PROCESSORS = (
  'django.core.context_processors.debug',
  'django.core.context_processors.i18n',
  'django.core.context_processors.media',
  'django.core.context_processors.static',
  'django.contrib.auth.context_processors.auth',
  'django.contrib.messages.context_processors.messages',
)

在我的模板中:

<link href="{{ STATIC_URL }}css/main.css" ...>

但是,在我的浏览器中是:

<link href="css/main.css" ...> (Just render `STATIC_URL` as empty)

我的设置是:

STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'

在我的views

def register(request):
    ...
    return render_to_response('register.html', {'errors':errors})

【问题讨论】:

  • 您的应用中有static 文件夹吗?

标签: python django web django-staticfiles


【解决方案1】:

改变

return render_to_response('register.html', 'errors':errors)

return render_to_response('register.html', {'errors': errors}, RequestContext(request))

【讨论】:

【解决方案2】:

在 Django 1.4 中,您应该使用 static templatetag1

试试:

{% load staticfiles %}
<link href="{% static "css/main.css" %} ...>

【讨论】:

  • 这个是正确答案但是负载线错误,应该是:{% load staticfiles %}
  • @sberder,是的,你是对的。 {% load static %} 来自 Django 1.3。我已经改变了答案。
【解决方案3】:

不幸的是,Django 的render_to_response 快捷方式默认使用普通的模板上下文,它不包括上下文处理器和所有像STATIC_URL 这样的花哨和有用的东西。您需要使用RequestContext,它正是这样做的。

这可以通过使用新的render(从 Django 1.3 开始可用)来调用:

from django.shortcuts import render

return render(request, 'register.html', {'errors':errors})

在 Django 1.2 及更早版本中,您需要显式提供上下文:

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('register.html', {'errors':errors},
    context_instance=RequestContext(request))

【讨论】:

    【解决方案4】:

    您的退货声明中不需要这个吗?:

    context_instance=RequestContext(request)

    【讨论】:

      【解决方案5】:

      我意识到这个问题已经得到解答,但我想提供另一个答案,以防 STATIC_URL 即使在使用 RequestContext 时仍呈现为空。

      如果您正在运行开发服务器,请记住使用 insecure 标志启动服务器,以让服务器为您的静态文件提供服务:

      python manage.py runserver --insecure
      

      【讨论】:

        猜你喜欢
        • 2013-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 2012-09-03
        • 1970-01-01
        • 2012-07-08
        • 1970-01-01
        • 2012-01-21
        相关资源
        最近更新 更多