Django 1.3 有关静态资源的改变

django 1.3 版本将 django-staticfiles 收入到了django.contirb.staticfiles 中,另外有关静态资源的配置也变了。

看 1.2 版本 的静态资源配置

MEDIA_ROOT
Default: '' (Empty string)
Absolute path to the directory that holds media for this installation.
Example: "/home/media/media.lawrence.com/" See also MEDIA_URL.

 

MEDIA_URL
Default: '' (Empty string)
URL that handles the media served from MEDIA_ROOT.
Example: "http://media.lawrence.com"
Note that this should have a trailing slash if it has a path component.

Good: "http://www.example.com/static/"
Bad: http://www.example.com/static

也就是说可以将所有静态文件放在 MEDIA_ROOT 中,MEDIA_URL 是静态文件的路径。
当然还要在URL中添加条目

另外用户上传的文件也将自动存在这个目录中

1.3 版本
先看 MEDIA_ROOT 和 MEDIA_URL

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = 'media'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/' 

可以看到 MEDIA_ROOT 仅用来作为用户上传文件的目录了。主要用在FileField,ImageField 中,用户上传的文件将自动保存在这里。
详见:https://docs.djangoproject.com/en/1.3//topics/files/

再看:

STATIC_ROOT
Default: '' (Empty string)
The absolute path to the directory where collectstatic will collect static files for deployment.
Example: "/home/example.com/static/"

也就是说,这个目录是用来收集静态资源的,不是用来放静态资源的。manage.py 有个新命令 collectstatic 会将所有的静态资源复制到这个目录中。
那么在哪放静态资源呢?
django 推荐将静态资源放在app 的static 子目录里。

看settings文件中的注释:

# 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 = 'static'

1.3 添加了两个新选项 STATICFILES_DIRS, STATICFILES_FINDERS
前者用来设置存放静态资源的目录,后者配置了些静态资源的查找规则。
当运行 collectstatic 时, ‘django.contrib.staticfiles.finders.AppDirectoriesFinder’ 会自动把 app 的 static 子目录中的静态资源复制到 STATIC_ROOT 中。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。