Django仅为首页加载静态文件

1 投票
3 回答
793 浏览
提问于 2025-04-17 09:00

我在使用Django 1.3.1和Python 2.7,系统是WinVista。不管是在本地开发服务器上还是部署到我的主机上,我都遇到了同样的问题。

在我网站的主页上,静态资源可以正常显示:

http://www.drugpolicyreformmovement.com

但是在其他页面上,CSS、图片等都不显示:

http://www.drugpolicyreformmovement.com/newsarchive2003

http://www.drugpolicyreformmovement.com/newsarchive2010

或者

http://www.drugpolicyreformmovement.com/newsarchive2009

当我运行'manage runserver'时,输出显示在那些二级'newsarchive'页面上静态资源出现了404错误。似乎在二级页面上'document_root'和主页不同,导致它在'/newsclippings2003/static'中查找,而不是像主页那样在'/static'中查找所有资源。

我不知道我的URL配置中哪些部分对你有用,所以我把整个文件都放在这里:

import os
from django.conf.urls.defaults import *
from django.views.generic import ListView, YearArchiveView
from newsclippings.models import Article
from drugpolicyreformmovement.views import ArticleYearArchiveView

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^$', ListView.as_view(
       queryset = Article.objects.order_by("-date", "publication", "author", "headline"),
       context_object_name='articles',
       template_name='index.html')),
    (r'^newsarchive(?P<year>\d+)/$', ArticleYearArchiveView.as_view()),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
       { 'document_root' : os.path.join( os.path.dirname(__file__), 'static') }),
    # url(r'^drugpolicyreformmovement/', include('drugpolicyreformmovement.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)

我认为问题出在这一行:

(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    { 'document_root' : os.path.join( os.path.dirname(__file__), 'static') }),

我把URL配置的顺序放成什么样子都没关系。这一行是为了让我在部署时不需要做改动。

3 个回答

1

当我查看你的HTML源代码时,我发现你的静态资源使用的是相对路径。你需要使用绝对路径

这是不对的:

<link rel="stylesheet" href="static/css/blueprint/screen.css" media="screen, projection">

应该这样用:

<link rel="stylesheet" href="/static/css/blueprint/screen.css" media="screen, projection">

很可能是你的模板有问题,但你没有展示你的模板文件。

1

与其试图让它以那种方式提供网址,不如在你的模板中使用 {{ STATIC_URL }} 这个标签。这样你在部署的时候也不需要做任何改动,而且你可以随意移动文件,也不用担心要处理其他的上下文变量。

2

你在首页的链接是

http://www.drugpolicyreformmovement.com/static/css/blueprint/print.css

在内页的链接是

http://www.drugpolicyreformmovement.com/newsarchive2003/static/css/blueprint/print.css

只需要在链接后面加上 /,或者使用 {{ STATIC_URL }}

比如说

  • /static/css/blueprint/print.css

或者

  • <img src="{{ STATIC_URL }}css/blueprint/print.css" />

只需要在设置中配置 STATIC_ROOT

可以参考这里:

撰写回答