Django模板扩展不会调用CSS

时间:2015-01-05 20:36:45

标签: python html css django django-templates

我正在从事一个项目,而关键是要学习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>&copy; 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 &raquo;</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 &raquo;</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 &raquo;</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 &raquo;</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 %} 

现在,当访问者访问该网站时,他们可以加入&#34;,他们输入姓名,然后通过电子邮件重定向到一个新页面,其中包含&#34;感谢您&#34;和所有。这个thankyou页面 NOT 按预期调用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 &raquo;</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 &raquo;</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 &raquo;</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 &raquo;</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%}
  • 重新做一遍
  • 复制&#34;工作&#34;来自signup.html的代码并进行更改

我自己还无法自行调试代码,但我认为 url.py 可能存在问题,但我无法解决问题。我可能会对此感到茫然。

非常感谢您的精彩帮助和时间!

最佳,

罗宾

2 个答案:

答案 0 :(得分:3)

您的样式表链接都是相对的URL,它们应该是绝对的:

<link href="/static/css/bootstrap.min.css" rel="stylesheet">

注意最初的斜线。

在执行static后,您应该使用load static标记:

<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">

答案 1 :(得分:1)

我建议将来使用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文件。此外,请务必注意,尽管{% load static %}base.html {{}}}仍然需要在base.html扩展{% load static %}的所有模板中直接包含{% extends base.html %} static {{1}}如果您希望在特定模板中链接{{1}}目录中的任何静态文件(例如CSS,JS,图像)。