Monthly Archives: October 2011

usage notes on STATIC_ROOT, STATIC_URL, MEDIA_ROOT, MEDIA_URL in Django v1.3+

In case I get confused again when I come back later.

  • Difference of *_ROOT and *_URL
  1.   *_ROOT are paths in the file system that actually stores the files, which are absolute paths.
  2. *_URL are urls in the HTTP requests. Meant to be used in templates.
  • Difference of STATIC_* and MEDIA_*
  1. STATIC_*  are for .js, .css and background images(.jpg, .png, .gif) that construct the webpages.
  2. MEDIA_* are media files (picture, music etc) that are uploaded by users or the like.

This separation is more logic than technical, and only introduced inv1.3 see release notes. Pictures can be served either in STATIC_ROOT  for  MEDIA_ROOT  as long as they are referenced with the corresponding *_URL. In a word, STATIC_*  are for infrastructure files, while MEDIA_ROOT are for content files(e.g photos in a photo gallery site)

  • Typical settings
  1. MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, ‘media/’)
  2. MEDIA_URL = ‘/media/’
  3. STATIC_ROOT = os.path.join(PROJECT_ROOT_PATH, ‘static/’)
  4. STATIC_URL = ‘/static/’
  • Static-specific
  1. If ‘django.contrib.staticfiles.finders.FileSystemFinder’ is enabled, STATICFILES_DIRS are searched by the development server.
  2. If ‘django.contrib.staticfiles.finders. AppDirectoriesFinderis is enabled, static/ subfolder for each app (i.e. app/static) are searched by the development server.
  3. Run ‘manage.py collectstatic’ would copy static file from the above folders to STATIC_ROOT. This is for 3rd servers like nginx, Apache etc. The development server does not use it.
  • Issues between the development server and 3rd servers (nginx, apache etc.)
  1. *_URL is for both the development server and 3rd servers (apache etc).
  2. *_ROOT is a way to collect things together for 3rd servers, and 3rd servers would only look into *_ROOT for files when configured in their own server config files. The development server does not care about them.
  3. By default, the development server look into the subfolders (static/) under each app for static files, but never care about media files cause it does not server media files, but template files only(js, css are needed for templates thus being searched).

The following code would enable the development server to server media files.from django.conf import settings

urlpatterns += patterns(”,
(r’^media/(?P<path>.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.MEDIA_ROOT}),
)

Advertisements