Django 模板扩展不调用 CSS

Django template extends does not call CSS

我正在做一个项目,而关键是学习 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'^

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 %} 

现在,当访问者访问该网站时,他们能够 "join",他们输入姓名和电子邮件,然后被重定向到一个显示 "thank you" 和所有内容的新页面。此感谢页面确实 按预期调用 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 %} 

最后,我尝试创建一个关于我们的页面,只是为了看看 CSS 是否会被调用到那个页面,但这里也没有运气。 AboutUs 页面与感谢页面的情况相同。 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 复制 "working" 代码并更改它

我还不能自己调试代码,但我认为 url.py 中可能存在问题,但我真的无法弄清楚。我可能会遇到这种情况。

非常感谢您的大力帮助和时间!

最佳,

罗宾

, 'signups.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^thank-you/

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 %}

       
    

Hello, world!

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

现在,当访问者访问该网站时,他们能够 "join",他们输入姓名和电子邮件,然后被重定向到一个显示 "thank you" 和所有内容的新页面。此感谢页面确实 按预期调用 CSS。它只是显示为普通 HTML,现在完全格式化(当然除了 h1、h2 等)。 thankyou.html 模板如下所示:

{% extends 'base.html' %}



{% block content %}

Thank you for joining!

{% endblock %}

最后,我尝试创建一个关于我们的页面,只是为了看看 CSS 是否会被调用到那个页面,但这里也没有运气。 AboutUs 页面与感谢页面的情况相同。 aboutus.html 模板如下所示:

{% extends 'base.html' %}

{% block jumbotron %}

       
    

This is Us

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

我试过:

  • 添加 {% load static %}
  • 重来一遍
  • 从 signup.html 复制 "working" 代码并更改它

我还不能自己调试代码,但我认为 url.py 中可能存在问题,但我真的无法弄清楚。我可能会遇到这种情况。

非常感谢您的大力帮助和时间!

最佳,

罗宾

, 'signups.views.thankyou', name='thankyou'), url(r'^about-us/

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 %}

       
    

Hello, world!

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

现在,当访问者访问该网站时,他们能够 "join",他们输入姓名和电子邮件,然后被重定向到一个显示 "thank you" 和所有内容的新页面。此感谢页面确实 按预期调用 CSS。它只是显示为普通 HTML,现在完全格式化(当然除了 h1、h2 等)。 thankyou.html 模板如下所示:

{% extends 'base.html' %}



{% block content %}

Thank you for joining!

{% endblock %}

最后,我尝试创建一个关于我们的页面,只是为了看看 CSS 是否会被调用到那个页面,但这里也没有运气。 AboutUs 页面与感谢页面的情况相同。 aboutus.html 模板如下所示:

{% extends 'base.html' %}

{% block jumbotron %}

       
    

This is Us

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

我试过:

  • 添加 {% load static %}
  • 重来一遍
  • 从 signup.html 复制 "working" 代码并更改它

我还不能自己调试代码,但我认为 url.py 中可能存在问题,但我真的无法弄清楚。我可能会遇到这种情况。

非常感谢您的大力帮助和时间!

最佳,

罗宾

, '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 %}

       
    

Hello, world!

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

现在,当访问者访问该网站时,他们能够 "join",他们输入姓名和电子邮件,然后被重定向到一个显示 "thank you" 和所有内容的新页面。此感谢页面确实 按预期调用 CSS。它只是显示为普通 HTML,现在完全格式化(当然除了 h1、h2 等)。 thankyou.html 模板如下所示:

{% extends 'base.html' %}



{% block content %}

Thank you for joining!

{% endblock %}

最后,我尝试创建一个关于我们的页面,只是为了看看 CSS 是否会被调用到那个页面,但这里也没有运气。 AboutUs 页面与感谢页面的情况相同。 aboutus.html 模板如下所示:

{% extends 'base.html' %}

{% block jumbotron %}

       
    

This is Us

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.

Learn more »

{% endblock %} {% block content %}

Heading

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.

View details »

Heading

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.

View details »

Heading

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.

View details »

Join Now

{% csrf_token %} {{form.as_p }}
{% endblock %}

我试过:

我还不能自己调试代码,但我认为 url.py 中可能存在问题,但我真的无法弄清楚。我可能会遇到这种情况。

非常感谢您的大力帮助和时间!

最佳,

罗宾

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

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

注意开头的斜杠。

你应该使用 static 标签,在 load static:

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

我建议将来使用 static 标签以提高可维护性。您当前定义了完整路径,例如:

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

虽然这可能有效,但这不是最佳做法。您提到使用 {% load static %},这实际上是 link 静态文件(如 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 的模板中仍然需要在 [=20= 正下方包含 {% load static %} ] 如果您希望 link 您的 static 目录中的任何静态文件(例如 CSS、JS、图像)在 该特定模板.