Django 模板继承没有 CSS?
在我的Django项目中,有一些我这个初学者看不懂的神秘输出,特别是在我的开发环境里。 我想要一个基础模板,这个模板里包含一个在静态媒体文件夹中的样式表……到目前为止,这个功能是正常的……但是只有在地址http://localhost/上,所有其他的链接都有一个从基础模板继承的模板。
现在在http://localhost/上的样式表看起来很好……但如果我去http://localhost/hello/,包含的样式表却有一个完整的HTML结构,包括body、doctype等等,为什么会这样呢?它似乎解析了一个HTML页面,而不是直接使用CSS文件……
这是我的代码:有什么想法吗?
urls.py:
from django.views.static import *
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
('^$',home_view),
('^hello/$', hello),
(r'^admin/', include(admin.site.urls)),
('^useragent/$',ua_display_good1),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
)
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
def hello(request):
pagetitle = "Hello World"
return render_to_response('hello.tpl', {'pagetitle': pagetitle})
def home_view(request):
pagetitle = "Something"
return render_to_response('home.tpl', {'pagetitle': pagetitle})
def ua_display_good1(request):
try:
ua = request.META['REMOTE_ADDR']
except KeyError:
ua = 'unknown'
return render_to_response('base.tpl',{'ageone': ua})
基础模板:
<!DOCTYPE html>
<html lang="de">
<meta name="description=" content="{{metadescription}}">
<head>
<link rel="stylesheet" type="text/css" href="media/style.css">
<title>{% block title %}{{pagetitle}}{% endblock %}</title>
</head>
<body>
<h1>{% block h1 %}{{ageone}}{% endblock %}</h1>
{% block content %}{% endblock %}
{% block footer %}{% include "footer.tpl" %}
{% endblock %}
</body>
</html>
hello模板:
{% extends "base.tpl" %}
{% block h1 %}Home{% endblock %}
{% block content %}Welcome{% endblock %}
5 个回答
1
正确的方式来引入样式表是这样的:
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css">
3
可能是因为你对CSS文件的引用方式是相对路径。
试着把:
<link rel="stylesheet" type="text/css" href="media/style.css">
改成
<link rel="stylesheet" type="text/css" href="/media/style.css">
这样它就会总是从根目录去找media/style.css这个文件。
2
现在你把CSS的链接设置成了相对路径,写成了 "media/style.css"
。在首页的时候,它会变成 "/media/style.css"
,但是在“hello”页面的时候,它就变成了 "/hello/media/style.css"
(这就是“hello”页面的地址)。
所以,建议你使用绝对路径的CSS链接,像这样写: "/media/style.css"
。