Django静态结构
我正在尝试理解Django 1.3所追求的静态结构:
我有一个项目,结构如下:
Project
someapp
static
someapp
css
etcetera
models.py
views.py
urls.py
urls.py
manage.py
settings.py
现在我想要覆盖Django的管理后台。所以我需要在settings.py文件中设置一些配置,我是这样做的(basepath是指向当前目录的快捷路径):
# 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 = BASE_PATH+'/static/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# 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.
)
如果我使用manage.py命令来收集静态文件(collectstatic),它会把所有的静态文件(包括管理后台的文件)收集到一个名为'static'的目录中,这个过程是正常的……(在主项目目录内)
不过,这些文件的内容还不能被使用,直到我把这个目录添加到STATICFILES_DIRS这个元组中。但是这样一来,我就得改变STATIC_ROOT的目录设置,因为如果不改的话,会出现它们不能是一样的错误……
我觉得我可能忽略了一些明显的东西,因为为了让它正常工作,我所需的步骤似乎有点多余。
3 个回答
你觉得这样怎么样:
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.
STATIC_ROOT,
)
STATICFILES_DIRS 是一个设置,用来告诉你的项目里有哪些不是特定应用的静态文件。STATIC_ROOT 是当你收集这些静态文件时,它们会被放到哪个地方。
根据 Django 的文档:
“你的项目可能还有一些静态资源,这些资源并不是和某个特定的应用相关联。STATICFILES_DIRS 设置是一个包含文件夹路径的列表,用来加载静态文件。默认情况下,这个列表是空的。你可以查看 STATICFILES_DIRS 的文档,了解如何添加更多的路径。”
“设置 STATIC_ROOT 这个选项,指向你希望在使用 collectstatic 命令时,静态文件被收集到的文件系统路径。”
对于本地开发,可以试试这个结构
Project
Project (project directory with settings.py etc..)
stylesheets
someapp
static
base.css
在 settings.py
文件中这样设置:
import os
ROOT_PATH = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(ROOT_PATH, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(ROOT_PATH, 'stylesheets'),
)
用 python manage.py runserver
启动本地服务器,然后访问 http://localhost:8000/static/base.css
你应该能看到样式表。