python - 为什么我不能让我的静态目录与 django 1.3 一起工作?

标签 python django web static url-pattern

这个问题很简单,就是想不通

添加到我的 urlpatterns

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'})

我的 main.css 在哪里:/home/user/www/site/static/css/main.css

当我访问 http://localhost:8000/static/

我得到:404:此处不允许目录索引。

当我访问 http://localhost:8000/static/css/main.css

我得到:404:找不到“css/main.css”

我做错了什么?

修复它:

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ),

在 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 = os.path.join(CURRENT_PATH, 'static') #=='/home/user/www/site/static'

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

如您所见,我唯一真正改变的是从 STATIC_URL = '/static/' 到 STATIC_URL = '/mystatic/'

注意:当我到达 http://localhost:8000/mystatic 时...我得到与上面相同的错误

我认为 STATIC_URL 应该是 '/static/' 这样你就可以在你的模板中使用 {{ STATIC_URL }} ...我真的不明白为什么这个修复有效以及为什么我必须做出改变我做的....

为什么会这样?

最佳答案

如果您使用内置的开发网络服务器(即使用 manage.py runserver 运行它),Django 将在开发过程中处理静态文件。

请注意,STATIC_ROOT 是 Django 收集静态文件的路径,而不是它提供文件的路径。您不应该自己维护 STATIC_ROOT!您可以在 the Django documentation 中阅读更多相关信息.

一般情况下,您不需要将 django.views.static.serve 添加到您的 url,使用内置服务器。

静态文件应该放在别处,除了STATIC_ROOT。您可以将它们放在 myapp/static 路径中(即在单个应用程序静态文件下)。您还可以为整个项目指定静态文件夹(例如 /path/to/project/proj_settings)并将 settings.py 中的 STATICFILES_DIRS 更新为是:

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.
    os.path.join(PROJECT_DIR, 'proj_static'),
)

然后您可以将您的css/main.css 文件放在/proj_static/css/main.css 中。 Django 内置网络服务器将从那里为 /static/ 提供服务。

在生产环境中,您应该通过运行 manage.py collectstatic 收集 STATIC_ROOT 中的所有静态文件。然后您可以直接通过您的网络服务器(例如 nginx、Apache)而不是通过 Django 提供该文件夹。

关于python - 为什么我不能让我的静态目录与 django 1.3 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6363728/

相关文章:

尝试安装 gevent-socketio 时找不到 python.h

android - Python框架选择

javascript - 有没有办法让索引页成为网页的唯一访问点

javascript - 如何将 'Prevent this page from creating additional dialogs' 默认为 "OK"选项

java - 将 12000 个文件导入到一张表中

python - 6 分钟后重新启动脚本

python - 更改 Django/Postgres db_table 名称

web - 来到背景图像时多大是太大?

python - 在字符串格式中使用 numpy.bytes_ 对象时超出最大递归深度

python - 一定范围内的随机数组