Django不加载CSS? [英] Django not loading CSS?
问题描述
这是我的urls.py
This is my urls.py
import os.path
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': site_media }),
)
我的site_media文件夹和style.css文件位于
My site_media folder and style.css file is in
myProjectFolder/myApp/static/site_media/css/style.css
和我的base.html模板(全部我的其他模板延伸了这个base.html模板)这是我有的:
and in my base.html template (all my other templates extend off of this base.html template) this is what I have:
<head>
<title>{% block title %}{% endblock %}</title>
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
</head>
<body>
{% block header %}{% endblock %}
{% block content %}
<div id='header'></div>
{% endblock %}
</body>
在我的style.css中,我只有这样:
and in my style.css, all I have is this:
#header {
display: inline;
background-color: black;
color: black;
border: 1px solid green;
}
并且CSS没有应用于
#header
div。任何想法为什么?
div. Any idea why?
推荐答案
问题来自2个方面。
- 错误的document_root变量传递
- 不在HTML中使用模板标签
1。
定义urls.py文件中的site_media变量是不鼓励的,因为它不符合DRY原则。它应该作为您的settings.py文件中的变量保存,以便其他模块可能需要导入。
在您的settings.py文件中,添加以下行:
1. Defining site_media variable in urls.py file is discouraged as it does not adhere to DRY principle. It should be held as a variable in your settings.py file so other modules may import if needed. In your settings.py file, add the following line:
import os.path
SITE_MEDIA_ROOT = os.path.join(
os.path.dirname(__file__), 'myApp/', 'static/', 'site_media' #this should be the correct path instead
)
使用以下代码替换您的urls.py文件:
Replace your urls.py file with this:
from myApp import settings
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.SITE_MEDIA_ROOT }),
)
2.您应该使用django模板标签来获取CSS文件。在您的基本模板中,在头标签上方添加以下行:
2.You should use django template tags to get the css file. In your base template, add this line above the head tag:
{% load static %}
然后替换:
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
with:
<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />
之后应该工作。
这篇关于Django不加载CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!