纸上得来终觉浅,绝知此事要躬行。

 

Python+Django静态文件配置

环境:

  OS:Windows Server 2012

  Python:2.7.5

  Django:1.5.2

站点目录结构:

  

创建 Django Web项目参见:创建Django Web 项目

配置步骤:

  1. 在 settings.py 文件中引用命令空间:
import os.path

  2. 配置 STATICFILES_DIRS 变量,代码如下:

# 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: "/var/www/example.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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.
    os.path.join(os.path.dirname(__file__),'templates/static').replace('\\','/'),
)

接下来查看静态文件配置是否成功可以用 dos 命令定位到 manage.py 所在目录,使用 Django 提供的一个 findstatic 命令,命令如下

python manage.py findstatic Global.css

 返回结果:

Found 'Global.css' here:
F:\javaWorkspace\website\blog\blog\templates\static\Global.css

 

这就表示 Django 可以处理静态文件了。

在模版中使用静态文件:

就像平时引用样式表一样。

<link rel="stylesheet" href="/static/Global.css" />

 需要注意的地方就是引用相对路径必须用 /static/ 开头,这也与配置 STATIC_URL 相对应。

posted on 2013-09-07 23:37  JRoger  阅读(559)  评论(0编辑  收藏  举报

导航