我已经检查了很多其他线程无法使用 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

最佳答案

对于本地提供的静态文件,如果您尚未设置任何形式的静态文件收集,并且您正在运行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文件夹提供服务时遇到的问题,因此他们合并了通常用于解决此问题的staticfiles应用程序。
它所做的工作(在文档中进行了描述)是从所有应用程序中提取所有静态文件,并将它们放在一(1)个文件夹中,以便在将应用程序投入生产时更容易提供。

因此,您的问题是您已“错过”了这一步,这就是为什么尝试访问它们时得到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帖子被发现here

我希望我把它弄得更清楚一些,否则,如果我错了,请纠正我^ _ ^!

有关在较新版本的Django中收集和管理静态文件的信息,请阅读此链接
The staticfiles app

10-08 17:02
查看更多