Django模板扩展不调用CSS
Posted
技术标签:
【中文标题】Django模板扩展不调用CSS【英文标题】:Django template extends does not call CSS 【发布时间】:2015-03-03 11:02:51 【问题描述】:我正在做一个项目,而关键是学习 django 和 python。
当我尝试使用命令 % extends 'base.html' %
扩展 html 代码并创建新模板或新页面时出现问题。
它的结构是这样的; base.html 是索引文件或我放置实际网站上显示的大部分代码的文件。然后我为我想要制作的每个功能制作模板。所以我想要一个可以正常加载的注册(提交)模板。
这是我的base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="icon/favicon.ico">
<title>Jumbotron Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="static/css/jumbotron.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="static/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="static/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
% block jumbotron %% endblock %
<div class="container">
% if messages %
<div class='row'>
<div class='col-sm-12 col-sm-offset'>
% for message in messages %
<p% if message.tags == "success" % class="alert alert-success" % endif %> message </p>
% endfor %
</div>
</div>
% endif %
<div class="row">
% block content%% endblock %
</div>
<hr>
<footer>
<p>© Copyright 2014</p>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
还有我的url.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'signups.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^thank-you/$', 'signups.views.thankyou', name='thankyou'),
url(r'^about-us/$', 'signups.views.aboutus', name='aboutus'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
还有 view.py:
from django.shortcuts import render, render_to_response, RequestContext, HttpResponseRedirect
from django.contrib import messages
# Create your views here.
from .forms import SignUpForm
def home(request):
form =SignUpForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
messages.success(request, 'Thank you for joining! We will be in touch with you as soon as possible:) ')
return HttpResponseRedirect('/thank-you/')
return render_to_response("signup.html", locals(), context_instance=RequestContext(request))
def thankyou(request):
return render_to_response("thankyou.html", locals(), context_instance=RequestContext(request))
def aboutus(request):
return render_to_response("aboutus.html", locals(), context_instance=RequestContext(request))
这是我正在工作的 signup.html 模板(即它按预期调用 CSS)。
% extends 'base.html' %
% block jumbotron %
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
% endblock %
% block content %
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Join Now</h2>
<form method='POST' action=''> % csrf_token %
form.as_p
<input type='submit' class='btn btn-success btn-block'>
</form>
</div>
% endblock %
现在,当访问者访问该网站时,他们可以“加入”,他们输入姓名和电子邮件,然后被重定向到一个新页面,上面写着“谢谢”等等。此感谢页面确实不按预期调用 CSS。它只是显示为带有现在格式的纯 HTML(当然除了 h1、h2 等)。 thankyou.html 模板如下所示:
% extends 'base.html' %
% block content %
<div class='col-sm-12' style='text-align: center'>
<h1>Thank you for joining!</h1>
</div>
% endblock %
最后,我尝试创建一个 AboutUs 页面,只是为了看看 CSS 是否会被调用到那个页面,但这里也没有运气。 AboutUs 页面和thankyou 页面一样。 aboutus.html 模板如下所示:
% extends 'base.html' %
% block jumbotron %
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>This is Us</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
% endblock %
% block content %
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn btn-block btn-primary" href="#" role="button">View details »</a></p>
</div>
<div class="col-sm-3">
<h2>Join Now</h2>
<form method='POST' action=''> % csrf_token %
form.as_p
<input type='submit' class='btn btn-success btn-block'>
</form>
</div>
% endblock %
我试过了:
添加 % load static % 从头再来 从 signup.html 复制“工作”代码并进行更改我还不能自己调试代码,但我认为 url.py 中可能存在问题,但我无法真正弄清楚。我可能会对此感到失望。
非常感谢您的宝贵帮助和时间!
最好的,
罗宾
【问题讨论】:
【参考方案1】:您的样式表链接都是相对 URL,它们应该是绝对的:
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
注意最初的斜线。
在执行load static
之后,您应该使用static
标签:
<link href="% static "css/bootstrap.min.css" %" rel="stylesheet">
【讨论】:
使用绝对 URL 的解决方案非常有效。但是您可能已经知道这一点:)另一方面,我对静态标签不太确定。我试过了,正如你和 aus_lacy 所示,但我无法让它正常工作。 @RobinWiman 这是配置静态文件并在模板中使用它们的示例。相信你看看之后就能让它工作起来 --> tangowithdjango.com/book/chapters/templates_static.html【参考方案2】:我建议将来使用static
标记以提高可维护性。您当前定义了完整路径,例如:
<link href="static/css/bootstrap.min.css" rel="stylesheet">
虽然这可能有效,但这不是最佳做法。您提到使用% load static %
,这实际上是链接静态文件(如 CSS、javascript 和图像文件)的首选方法。一旦你习惯并熟悉了这种方法,你会发现它实际上更容易实现,出错的可能性更小(即在完整路径中打错字),并且可以更有效地调试。
这里有一个简单的例子来证明这个想法:
#base.html template
<!DOCTYPE html>
% load static %
<head>
<!-- meta settings and other code that you have within your head tag -->
<link href="% static "css/boostrap.min.css" %" rel="stylesheet">
<!-- rest of your content here -->
</head>
现在假设在您的static
目录中有一个名为css
的目录,您的CSS 文件位于该目录中。此外,重要的是要注意,尽管您的 base.html
中有 % load static %
,但如果您希望在其中链接任何静态文件,您仍然需要在扩展 base.html
的每个模板中直接在您的 % load static %
下方包含 % load static %
该特定模板中的static
目录(例如CSS、JS、图像)。
【讨论】:
以上是关于Django模板扩展不调用CSS的主要内容,如果未能解决你的问题,请参考以下文章
CSS 字体仅适用于从相同基础扩展的一些 Django 模板
可以为 Django 中的扩展 html 模板定义一个单独的 css 文件吗?