2012-02-14 116 views
2

我潜入Django制作博客。问题是渲染视图后,只有文本内容在页面上没有任何CSS样式。其他类型的页面正常渲染。在渲染视图时,CSS不会在Django中加载

这是我的设置:

的mysite /博客/ 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] 
    }) 

的mysite /博客/ 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', 
    ), 

) 

的mysite/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'}), 
) 

mysite/settings.py

# Django settings for mysite project. 

DEBUG = True 
TEMPLATE_DEBUG = DEBUG 

ADMINS = (
# ('Your Name', '[email protected]'), 
) 

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 = '[email protected]!!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 /模板/ cats.html(在mysite的/博客/ 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 /模板/ 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> 

我认为这是在博客/ views.py或/和博客/ urls.py一个错误,因为当我删除的Django来自cats.html的代码,情况保持不变:只有ren dered文本没有任何风格,当我去www.mysite.com/cat/asfas/

(是的,asfas类是一个真正的蛞蝓)

回答

5

{{ STATIC_URL }}标签在你的模板,您需要使用RequestContext呈现您的模板。您的通用视图会自动处理。

view_cat视图中使用render_to_response快捷方式时,必须手动包含上下文实例。目前你没有使用RequestContext,所以{{ static_url }}标签不起作用。这打断了你的样式表的链接,所以你看不到正确的样式。

下面介绍如何在您的视图包括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] 
    }) 
+0

谢谢!它现在工作!;) – 2012-02-14 16:09:27

+0

我也想问是否有可能将view_cat转换为通用的一个在一个地方(urls.py)。或者最好在view.py中有这样的观点? – 2012-02-14 16:39:49

+0

真的是一个单独的问题。你不能直接在你的url中使用任何通用视图,但你可以继承ListView(参见[dynamic filtering](https://docs.djangoproject.com/en/dev/topics/class-based- views /#dynamic-filtering)在Django文档中的例子)。你在哪里保持你的视图功能和课程取决于你。在网址中包含真正简单的视图可能很诱人。py,但随着项目规模的扩大,它将更有条理地将视图保留在自己的模块中。 – Alasdair 2012-02-14 16:53:20

2

请注意,您还需要将请求对象传递给渲染快捷方式。

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

迟了一点,但我现在在我的答案中已经修复了'render'示例。 – Alasdair 2016-11-16 15:50:42