静态资源指javascript images 和css文件,这里django 提供django.contrib.staticfiles来管理它们。
使用方法
1.settings 文件中,确保INSTALLED_APPS中有django.contrib.staticfiles
2.设置STATIC_URL
STATIC_URL = '/static/'
3.设置STATICFILES_DIRS,这里style.css文件在ui_content/css/中
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), '../ui_content').replace('\\', '/'),
)
STATICFILES_DIRS将会手机所有的静态资源文件,并映射到STATIC_URL所设置的路径中,在模板中使用/static/css/style.css,就可以找到此文件。
STATICFILES_FINDERS的规则
Default:
("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
默认从STATICFILES_DIRS设置的目录中寻找,其次从每个app的static子目录中找,以先找到的为准。
如果设置了django.contrib.staticfiles.finders.DefaultStorageFinder.则回从DEFAULT_FILE_STORAGE中寻找,这个主要用于从云或者CDN中加载使用的。
部署
例如设置STATIC_ROOT = "/var/www/example.com/static/"
部署的时候通常使用一定的WEB服务器,使用
./manage.py collectstatic
可以将所有的静态资源收集到STATIC_ROOT中
关于 MEDIA_ROOT
MEDIA_ROOT 应该是对应用户上传的文件的。在开发过程中可以这么用,例如 MEDIA_URL是 ‘/media/’,
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这个功能仅在debug模式匣使用,而且前缀必须是local而不能是一个URL http://static,example.com这种。
参考
https://docs.djangoproject.com/en/1.5/howto/static-files/
https://docs.djangoproject.com/en/1.5/ref/contrib/staticfiles/#module-django.contrib.staticfiles