[英]Django STATIC_URL is not working
Django版本是1.4。 我已经阅读了official document
,并搜索了我的问题。
首先我按照官方文档管理静态文件在settings.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" ...>
但是,在我的broswer是:
<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})
更改
return render_to_response('register.html', 'errors':errors)
至
return render_to_response('register.html', {'errors': errors}, RequestContext(request))
不幸的是,Django的render_to_response
快捷方式默认使用普通的模板上下文,它不包括上下文处理器以及所有它们的奇特和有用的东西,如STATIC_URL
。 您需要使用RequestContext
,这确实是precicely。
这可以通过使用新的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))
在Django 1.4中,您应该使用static
模板标签1 。
尝试:
{% load staticfiles %}
<link href="{% static "css/main.css" %} ...>
你在退货声明中不需要这个吗?:
context_instance=RequestContext(request)
我意识到这已经得到了回答,但我想提供另一个答案,即使使用RequestContext,STATIC_URL仍然呈现为空。
如果您正在运行开发服务器,请记住使用insecure标志启动服务器以使服务器为您的静态文件提供服务:
python manage.py runserver --insecure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.