Django 静态文件导致 404 错误
我查看了很多关于在Django中无法使用静态文件应用提供静态内容的讨论,但到现在为止还没有找到解决办法。
settings.py
STATIC_ROOT = '/opt/django/webtools/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/html/static",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
模板
相关的代码行....
<img src="{{ STATIC_URL }}macmonster/img/macmonster-logo-blue.png" >
日志
从日志来看,路径是正确的,但可惜还是出现了404错误。
[10/Feb/2013 16:19:50] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
[10/Feb/2013 16:19:51] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
2 个回答
3
更改
STATIC_URL = '/static/'
设置
STATIC_URL = 'http://yourdomain.com/static/'
这真让人难以置信,但经过一个小时的搜索,解决了我在处理静态文件时遇到的问题,方法是把 STATIC_ROOT
从 STATICFILES_DIRS
中移除。STATICFILES_DIRS
只是用来收集所有模块中的静态文件,并把它们存储到 STATIC_ROOT
中。
14
如果你还没有设置任何方式来收集静态文件,并且你正在使用Django 1.3或更高版本,那么你的 settings.py
文件在处理静态文件时应该是这样的:
# 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 = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# 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.
'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/static',
)
# 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',
)
注意,我这里没有写 STATIC_ROOT
。这是因为我现在还不需要收集静态文件。
收集静态文件的目的是为了方便管理多个不同的静态文件夹,所以他们把通常用来解决这个问题的 staticfiles
应用合并了。这个功能的作用是把你所有应用中的静态文件都放到一个文件夹里,这样在你准备上线应用时会更容易提供这些文件。
所以你遇到的问题是,你“漏掉”了这一步,这就是为什么你在尝试访问静态文件时会出现404错误。
因此,你需要使用静态文件的绝对路径,例如在Mac或Unix系统上,它应该看起来像这样:'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/static',
另外,你可以简化并“修复”我用来举例的那种硬编码路径,可以这样做:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = (
PROJECT_ROOT + '/static/'
)
这样也能解决可移植性的问题。关于这个问题,有一个很好的StackOverflow帖子可以在 这里找到。
希望我能让这个问题更清楚一些,如果我说错了,请纠正我哦 ^_^!
关于如何在新版本的Django中收集和管理静态文件,可以阅读这个链接:静态文件应用