python - 渲染 View 时 CSS 不会在 Django 中加载

标签 python css django rendering django-views

我潜心研究 Django 制作博客。问题是渲染 View 后页面上只有文本内容,没有任何 CSS 样式。其他类型的页面可以正确呈现。

这是我的设置:

我的网站/博客/views.py

from django.shortcuts import render_to_response, get_object_or_404
from blog.models import Post,Cat

def view_cat(request, slug):
    cat = get_object_or_404(Cat, slug=slug)
    return render_to_response('cats.html', {
        'cat': cat,
        'posts': Post.objects.filter(cat=cat)[:5]
    })

我的网站/博客/urls.py

from django.conf.urls.defaults import *
from django.views.generic import DetailView, ListView
from blog.models import Post, Cat

urlpatterns = patterns('',
url(r'^$',
    ListView.as_view(
        queryset=Post.objects.order_by('-pub_date')[:10],
        template_name='index.html'
        )
    ),

url(r'^(?P<pk>\d+)/$',
    DetailView.as_view(
        model=Post,
        template_name='detail.html'
        )
    ),
 url(r'^cat/(?P<slug>\w+)/$', 
    'blog.views.view_cat', 
    ),

)

我的网站/urls.py

from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
url(r'',include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^about/$', 'django.views.generic.simple.direct_to_template', 
{'template': 'about.html'}),
url(r'^contact/$', 'django.views.generic.simple.direct_to_template', 
{'template': 'contact.html'}),
)

我的网站/settings.py

# Django settings for mysite project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
# ('Your Name', 'your_email@example.com'),
) 

MANAGERS = ADMINS

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3', 
# Add 'postgresql_psycopg2', 'postgresql','mysql', 'sqlite3' or 'oracle'.
    'NAME': '/home/user/www/mysite/sqlite3.db',# Or path to
             database file if using sqlite3.
    'USER': '',                      # Not used with sqlite3.
    'PASSWORD': '',                  # Not used with sqlite3.
    'HOST': '',              # Set to empty string for localhost. Not used with sqlite3.
    'PORT': '',              # Set to empty string for default. Not used with sqlite3.
}
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/user/www/mysite/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/home/user/www/mysite/static/'

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '26m-1=h8m+a+s3y@tv!!3pagdcjt)0(bz)lr79%yiy8e8&0=c-'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)   

ROOT_URLCONF = 'mysite.urls'

TEMPLATE_DIRS = (
'/home/user/www/mysite/templates'
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.comments',
# Uncomment the next line to enable the admin:
 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'blog',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'class': 'django.utils.log.AdminEmailHandler'
    }
},
'loggers': {
    'django.request': {
        'handlers': ['mail_admins'],
        'level': 'ERROR',
        'propagate': True,
    },
}
}

mysite/templates/cats.html(在 mysite/blog/views.py 中表示),CSS 不会在此处加载

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mysite.com</title>
<meta name="description" content="">
<meta name="author" content="">

<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

<!-- Le styles -->
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<style>
  body {
    padding-top: 60px; 
/* 60px to make the container go all the way to the bottom of the topbar */
  }
</style>


<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico">
<link rel="apple-touch-icon" href="{{ STATIC_URL }}images/apple-touch-icon.png">

<link rel="apple-touch-icon" 
sizes="72x72" href="{{ STATIC_URL }}images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" 
href="{{ STATIC_URL }}images/apple-touch-icon-114x114.png">
</head>

<body>

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>
      <a class="brand" href="/">Mysite.com</a>
      <div class="nav-collapse">
        <ul class="nav">
          <li class="active"><a href="/">Blog</a></li>
          <li><a href="/about">About</a></li>
          <li><a href="/contact">Contact</a></li>

        </ul>
      </div><!--/.nav-collapse -->
    </div>
  </div>
</div>

<div class="container">

<div class="row">

<div class="span9">
<ul class="breadcrumb">
<li>
<a href="/">Home</a> <span class="divider">/</span>
</li>
<li>
<strong><a href="">{{ cat.name }}</a></strong>
</li>

</ul>




</div>
<div class="span3">
<h3>Construction progress...</h3>
<span class="label label-info">Functionality</span></p>
<div class="progress progress-info
progress-striped active">
<div class="bar"
style="width: 50%;"></div>
</div>
<span class="label label-info">Design</span></p>
<div class="progress progress-info
progress-striped active">
<div class="bar"
style="width: 30%;"></div>
</div>
<span class="label label-info">Usability</span></p>
<div class="progress progress-info
progress-striped active">
<div class="bar"
style="width: 5%;"></div>
</div>
</div>
</div>
</div> <!-- /container -->

<!-- Le javascript
================================================== -->

<!-- Placed at the end of the document so the pages load faster -->
<script src="{{ STATIC_URL }}js/jquery.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap-alert.js"></script>


</body>
</html>

mysite/templates/index.html(例如),CSS 加载在这里,但 cats.html 和 index.html 之间只有很少的区别

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Mysite.com</title>
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le styles -->
    <link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
    <style>
      body {
        padding-top: 60px; 
 /* 60px to make the container go all the way to the bottom of the topbar */
      }
    </style>


    <!-- Le fav and touch icons -->
    <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico">
    <link rel="apple-touch-icon" href="{{ STATIC_URL }}images/apple-touch-icon.png">

    <link rel="apple-touch-icon" sizes="72x72" 
href="{{ STATIC_URL }}images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" 
     sizes="114x114" href="{{ STATIC_URL }}images/apple-touch-icon-114x114.png">
  </head>

  <body>

    <div class="navbar navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="/">Mysite.com</a>
          <div class="nav-collapse">
            <ul class="nav">
              <li class="active"><a href="/">Blog</a></li>
              <li><a href='/about'>About</a></li>
              <li><a href="/contact">Contact</a></li>

            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

    <div class="container">
<div class="row">

<div class="span9">

{% if post_list %}

    {% for post in post_list %}
        <strong><a href="/{{ post.id }}/">{{ post.title }}</a></strong> at 
<a href="/cat/{{post.cat.slug}}/">{{post.cat}}</a></p>
        <p>{{ post.body }} <a href="/{{ post.id }}/">read more</a></p>
        <hr>
    {% endfor %}

{% else %}

    <p>No posts are available.</p>

{% endif %}
</div>
<div class="span3">
<h3>Construction progress...</h3>
<span class="label label-info">Functionality</span></p>
    <div class="progress progress-info
    progress-striped active">
    <div class="bar"
    style="width: 50%;"></div>
    </div>
    <span class="label label-info">Design</span></p>
    <div class="progress progress-info
    progress-striped active">
    <div class="bar"
    style="width: 30%;"></div>
    </div>
    <span class="label label-info">Usability</span></p>
    <div class="progress progress-info
    progress-striped active">
    <div class="bar"
    style="width: 5%;"></div>
    </div>
</div>
</div>

    </div> <!-- /container -->

    <!-- Le javascript
    ================================================== -->

    <!-- Placed at the end of the document so the pages load faster -->
    <script src="{{ STATIC_URL }}js/jquery.js"></script>
    <script src="{{ STATIC_URL }}js/bootstrap.js"></script>
    <script src="{{ STATIC_URL }}js/bootstrap-alert.js"></script>

  </body>
</html>

我认为 blog/views.py 或/和 blog/urls.py 中存在错误,因为当我从 cats.html 中删除 django 代码时,情况保持不变:当我去 www.mysite.com/cat/asfas/

(是的,asfas 是一个真正的类别)

最佳答案

要使 {{ STATIC_URL }} 标记在您的模板中起作用,您需要使用 RequestContext 呈现您的模板。您的通用 View 会自动处理此问题。

当您使用 render_to_response view_cat View 中的快捷方式,您必须手动包含上下文实例。目前您没有使用 RequestContext,因此 {{ static_url }} 标签不起作用。这会破坏样式表的链接,因此您看不到正确的样式。

以下是如何在您的 View 中包含 RequestContext:

return render_to_response('cats.html', {
    'cat': cat,
    'posts': Post.objects.filter(cat=cat)[:5]
},
context_instance=RequestContext(request))

或者,如果您使用的是 Django 1.3 或更高版本,则可以使用 render改为快捷方式:

from django.shortcuts import render
...
    return render(request, 'cats.html', {        
        'cat': cat,
        'posts': Post.objects.filter(cat=cat)[:5]
    })

关于python - 渲染 View 时 CSS 不会在 Django 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9279777/

相关文章:

python - 如何在 CKAN 扩展中自定义 authz.py 文件?

jquery - 根据表单字段值(电子邮件地址域)显示特定内容

html - 为什么我的图像忽略了其包含元素的大小(高度)?

python - South 在尝试迁移时引发 ValueError

python - 新列的列名来自索引 Pandas 的最大列

python - PyQt6中QStyle.StandardPixmap是如何定义的

django - 需要帮助使用 xhtml2pdf 从模板以 pdf 格式呈现图像

django - 在 Django 中测试自定义管理操作

javascript - 如何在管理页面中将自定义脚本实现到django中? Python

css - 此 CSS 动画 (.less) 适用于 Firefox 和 Chrome,不适用于 Safari