Der*_*rek 6 python django static url-pattern web
这个问题很简单,但我无法弄清楚
添加到我的urlpatterns
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'})
Run Code Online (Sandbox Code Playgroud)
我的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 } ),
Run Code Online (Sandbox Code Playgroud)
在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/'
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我唯一真正改变的是从STATIC_URL ='/ static /'到STATIC_URL ='/ mystatic /'
注意:当我到达http:// localhost:8000/mystatic时 ......我得到的错误与上面相同
我认为STATIC_URL应该是'/ static /',这样你就可以在你的模板中使用{{STATIC_URL}} ......我真的不明白为什么这个修复工作有效以及为什么我必须做出我做过的更改....
为什么这样做?
如果您正在使用内置的开发Web服务器(即运行它manage.py runserver
),Django将在开发过程中处理静态文件.
请注意,这STATIC_ROOT
是Django收集静态文件的路径,而不是它提供文件的路径.你不应该保持STATIC_ROOT
自己!您可以在Django文档中阅读更多相关内容.
通常,您不需要django.views.static.serve
使用内置服务器添加到您的URL.
除此之外,静态文件应该放在别处STATIC_ROOT
.您可以将它们放在myapp/static
路径中(即在单个app静态文件下).您也可以奉献的静态文件夹整个项目(如/path/to/project/proj_settings
)和更新STATICFILES_DIRS
的settings.py
是:
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'),
)
Run Code Online (Sandbox Code Playgroud)
然后你可以把你的css/main.css
文件放入/proj_static/css/main.css
.Django内置的webserver /static/
将从那里服务器.
在生产中,您应该STATIC_ROOT
通过运行收集所有静态文件manage.py collectstatic
.然后,您可以直接通过您的网络服务器(例如nginx,Apache)而不是通过Django来提供该文件夹.