如何在 Django 模板中加载 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9339226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load CSS in Django templates?
提问by John
I'm having trouble loading CSS for my Django template.
我在为 Django 模板加载 CSS 时遇到问题。
I have the following settings:
我有以下设置:
STATIC_ROOT = ''
STATIC_URL = '/css/'
STATICFILES_DIRS = ("/css")
INSTALLED_APPS = (
'django.contrib.staticfiles',
)
Do I need to use both static_url
and also staticfiles_dirs
?
我需要同时使用static_url
和staticfiles_dirs
吗?
urls.py is
urls.py 是
urlpatterns = patterns('',
(r'^$',homefun),
)
views.py is
views.py 是
def homefun(request):
return render_to_response('home.html')
And the parent template is base.html which loads the css.
父模板是加载 css 的 base.html。
<link rel="stylesheet" type="text/css" href="/css/style.css" />
回答by neoascetic
You need to use {{ STATIC_URL }}
as variable in templates, like so:
您需要{{ STATIC_URL }}
在模板中使用as 变量,如下所示:
<link rel="stylesheet" href="{{ STATIC_URL }}style.css">
Official Django documentationhave a good explanation about serving static files.
官方 Django 文档对提供静态文件有很好的解释。
You mustset STATIC_ROOT
variable. Using STATICFILES_DIRS
is optional, by default Django search within static
directories of all your apps.
您必须设置STATIC_ROOT
变量。使用STATICFILES_DIRS
是可选的,默认情况下 Django 在static
所有应用程序的目录中搜索。
回答by David Wolever
Your STATICFILES_DIRS = ("/css")
should actually be STATICFILES_DIRS = ("/path/to/your/css", )
(note the trailing comma?— necessary because (eggs)
evaluates to the value eggs
, but the trailing comma forces it to evaluate to a tuple).
您STATICFILES_DIRS = ("/css")
实际上应该是STATICFILES_DIRS = ("/path/to/your/css", )
(注意尾随逗号?— 必要,因为(eggs)
计算结果为 value eggs
,但尾随逗号强制它计算为元组)。
回答by mgibsonbr
STATIC_URL
is for the URL of your static media (for which requests the webserver will serve static media to the browser), while STATICFILES_DIRS
is a list of folders in your machine (where the webserver will find the files to serve). AFAIK the latter must use absolute paths, not relative ones, maybe that's why it's not working for you.
STATIC_URL
是您的静态媒体的 URL(对于该请求,网络服务器将向浏览器提供静态媒体),而STATICFILES_DIRS
是您机器中的文件夹列表(网络服务器将在其中找到要提供的文件)。AFAIK 后者必须使用绝对路径,而不是相对路径,也许这就是它不适合您的原因。
回答by Julia T
This solution worked for me.
这个解决方案对我有用。
I am converting code from python2.7
to python3.4
and couldn't get the static files to displaying after the conversion.
我正在将代码从 转换python2.7
为python3.4
并且无法在转换后显示静态文件。
I changed script(src='#{STATIC_URL}js/libs/jquery-2.1.1.min.js')
to script(src='{{STATIC_URL}}js/libs/jquery-2.1.1.min.js')
and all works perfectly now.
我换script(src='#{STATIC_URL}js/libs/jquery-2.1.1.min.js')
到script(src='{{STATIC_URL}}js/libs/jquery-2.1.1.min.js')
现在一切完美的作品。