staticfiles.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. ===================
  2. The staticfiles app
  3. ===================
  4. .. module:: django.contrib.staticfiles
  5. :synopsis: An app for handling static files.
  6. ``django.contrib.staticfiles`` collects static files from each of your
  7. applications (and any other places you specify) into a single location that
  8. can easily be served in production.
  9. .. seealso::
  10. For an introduction to the static files app and some usage examples, see
  11. :doc:`/howto/static-files`.
  12. .. _staticfiles-settings:
  13. Settings
  14. ========
  15. .. highlight:: python
  16. .. note::
  17. The following settings control the behavior of the staticfiles app.
  18. .. setting:: STATICFILES_DIRS
  19. STATICFILES_DIRS
  20. ----------------
  21. Default: ``[]``
  22. This setting defines the additional locations the staticfiles app will traverse
  23. if the :class:`FileSystemFinder` finder is enabled, e.g. if you use the
  24. :djadmin:`collectstatic` or :djadmin:`findstatic` management command or use the
  25. static file serving view.
  26. This should be set to a list or tuple of strings that contain full paths to
  27. your additional files directory(ies) e.g.::
  28. STATICFILES_DIRS = (
  29. "/home/special.polls.com/polls/static",
  30. "/home/polls.com/polls/static",
  31. "/opt/webfiles/common",
  32. )
  33. Prefixes (optional)
  34. """""""""""""""""""
  35. In case you want to refer to files in one of the locations with an additional
  36. namespace, you can **optionally** provide a prefix as ``(prefix, path)``
  37. tuples, e.g.::
  38. STATICFILES_DIRS = (
  39. # ...
  40. ("downloads", "/opt/webfiles/stats"),
  41. )
  42. Example:
  43. Assuming you have :setting:`STATIC_URL` set ``'/static/'``, the
  44. :djadmin:`collectstatic` management command would collect the "stats" files
  45. in a ``'downloads'`` subdirectory of :setting:`STATIC_ROOT`.
  46. This would allow you to refer to the local file
  47. ``'/opt/webfiles/stats/polls_20101022.tar.gz'`` with
  48. ``'/static/downloads/polls_20101022.tar.gz'`` in your templates, e.g.:
  49. .. code-block:: html+django
  50. <a href="{{ STATIC_URL }}downloads/polls_20101022.tar.gz">
  51. .. setting:: STATICFILES_STORAGE
  52. STATICFILES_STORAGE
  53. -------------------
  54. Default: ``'django.contrib.staticfiles.storage.StaticFilesStorage'``
  55. The file storage engine to use when collecting static files with the
  56. :djadmin:`collectstatic` management command.
  57. A ready-to-use instance of the storage backend defined in this setting
  58. can be found at ``django.contrib.staticfiles.storage.staticfiles_storage``.
  59. For an example, see :ref:`staticfiles-from-cdn`.
  60. .. setting:: STATICFILES_FINDERS
  61. STATICFILES_FINDERS
  62. -------------------
  63. Default::
  64. ("django.contrib.staticfiles.finders.FileSystemFinder",
  65. "django.contrib.staticfiles.finders.AppDirectoriesFinder")
  66. The list of finder backends that know how to find static files in
  67. various locations.
  68. The default will find files stored in the :setting:`STATICFILES_DIRS` setting
  69. (using :class:`django.contrib.staticfiles.finders.FileSystemFinder`) and in a
  70. ``static`` subdirectory of each app (using
  71. :class:`django.contrib.staticfiles.finders.AppDirectoriesFinder`)
  72. One finder is disabled by default:
  73. :class:`django.contrib.staticfiles.finders.DefaultStorageFinder`. If added to
  74. your :setting:`STATICFILES_FINDERS` setting, it will look for static files in
  75. the default file storage as defined by the :setting:`DEFAULT_FILE_STORAGE`
  76. setting.
  77. .. note::
  78. When using the :class:`AppDirectoriesFinder` finder, make sure your apps
  79. can be found by staticfiles. Simply add the app to the
  80. :setting:`INSTALLED_APPS` setting of your site.
  81. Static file finders are currently considered a private interface, and this
  82. interface is thus undocumented.
  83. Management Commands
  84. ===================
  85. .. highlight:: console
  86. ``django.contrib.staticfiles`` exposes three management commands.
  87. collectstatic
  88. -------------
  89. .. django-admin:: collectstatic
  90. Collects the static files into :setting:`STATIC_ROOT`.
  91. Duplicate file names are by default resolved in a similar way to how template
  92. resolution works: the file that is first found in one of the specified
  93. locations will be used. If you're confused, the :djadmin:`findstatic` command
  94. can help show you which files are found.
  95. Files are searched by using the :setting:`enabled finders
  96. <STATICFILES_FINDERS>`. The default is to look in all locations defined in
  97. :setting:`STATICFILES_DIRS` and in the ``'static'`` directory of apps
  98. specified by the :setting:`INSTALLED_APPS` setting.
  99. The :djadmin:`collectstatic` management command calls the
  100. :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  101. method of the :setting:`STATICFILES_STORAGE` after each run and passes
  102. a list of paths that have been found by the management command. It also
  103. receives all command line options of :djadmin:`collectstatic`. This is used
  104. by the :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
  105. by default.
  106. Some commonly used options are:
  107. .. django-admin-option:: --noinput
  108. Do NOT prompt the user for input of any kind.
  109. .. django-admin-option:: -i <pattern>
  110. .. django-admin-option:: --ignore <pattern>
  111. Ignore files or directories matching this glob-style pattern. Use multiple
  112. times to ignore more.
  113. .. django-admin-option:: -n
  114. .. django-admin-option:: --dry-run
  115. Do everything except modify the filesystem.
  116. .. django-admin-option:: -c
  117. .. django-admin-option:: --clear
  118. Clear the existing files before trying to copy or link the original file.
  119. .. django-admin-option:: -l
  120. .. django-admin-option:: --link
  121. Create a symbolic link to each file instead of copying.
  122. .. django-admin-option:: --no-post-process
  123. Don't call the
  124. :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  125. method of the configured :setting:`STATICFILES_STORAGE` storage backend.
  126. .. django-admin-option:: --no-default-ignore
  127. Don't ignore the common private glob-style patterns ``'CVS'``, ``'.*'``
  128. and ``'*~'``.
  129. For a full list of options, refer to the commands own help by running::
  130. $ python manage.py collectstatic --help
  131. findstatic
  132. ----------
  133. .. django-admin:: findstatic
  134. Searches for one or more relative paths with the enabled finders.
  135. For example::
  136. $ python manage.py findstatic css/base.css admin/js/core.js
  137. /home/special.polls.com/core/static/css/base.css
  138. /home/polls.com/core/static/css/base.css
  139. /home/polls.com/src/django/contrib/admin/media/js/core.js
  140. By default, all matching locations are found. To only return the first match
  141. for each relative path, use the ``--first`` option::
  142. $ python manage.py findstatic css/base.css --first
  143. /home/special.polls.com/core/static/css/base.css
  144. This is a debugging aid; it'll show you exactly which static file will be
  145. collected for a given path.
  146. .. _staticfiles-runserver:
  147. runserver
  148. ---------
  149. .. django-admin:: runserver
  150. Overrides the core :djadmin:`runserver` command if the ``staticfiles`` app
  151. is :setting:`installed<INSTALLED_APPS>` and adds automatic serving of static
  152. files and the following new options.
  153. .. django-admin-option:: --nostatic
  154. Use the ``--nostatic`` option to disable serving of static files with the
  155. :doc:`staticfiles </ref/contrib/staticfiles>` app entirely. This option is
  156. only available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
  157. in your project's :setting:`INSTALLED_APPS` setting.
  158. Example usage::
  159. django-admin.py runserver --nostatic
  160. .. django-admin-option:: --insecure
  161. Use the ``--insecure`` option to force serving of static files with the
  162. :doc:`staticfiles </ref/contrib/staticfiles>` app even if the :setting:`DEBUG`
  163. setting is ``False``. By using this you acknowledge the fact that it's
  164. **grossly inefficient** and probably **insecure**. This is only intended for
  165. local development, should **never be used in production** and is only
  166. available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
  167. in your project's :setting:`INSTALLED_APPS` setting.
  168. Example usage::
  169. django-admin.py runserver --insecure
  170. Storages
  171. ========
  172. StaticFilesStorage
  173. ------------------
  174. .. class:: storage.StaticFilesStorage
  175. A subclass of the :class:`~django.core.files.storage.FileSystemStorage`
  176. storage backend that uses the :setting:`STATIC_ROOT` setting as the base
  177. file system location and the :setting:`STATIC_URL` setting respectively
  178. as the base URL.
  179. .. method:: post_process(paths, **options)
  180. This method is called by the :djadmin:`collectstatic` management command
  181. after each run and gets passed the local storages and paths of found
  182. files as a dictionary, as well as the command line options.
  183. The :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
  184. uses this behind the scenes to replace the paths with their hashed
  185. counterparts and update the cache appropriately.
  186. CachedStaticFilesStorage
  187. ------------------------
  188. .. class:: storage.CachedStaticFilesStorage
  189. A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
  190. storage backend which caches the files it saves by appending the MD5 hash
  191. of the file's content to the filename. For example, the file
  192. ``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
  193. The purpose of this storage is to keep serving the old files in case some
  194. pages still refer to those files, e.g. because they are cached by you or
  195. a 3rd party proxy server. Additionally, it's very helpful if you want to
  196. apply `far future Expires headers`_ to the deployed files to speed up the
  197. load time for subsequent page visits.
  198. The storage backend automatically replaces the paths found in the saved
  199. files matching other saved files with the path of the cached copy (using
  200. the :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  201. method). The regular expressions used to find those paths
  202. (``django.contrib.staticfiles.storage.CachedStaticFilesStorage.cached_patterns``)
  203. by default cover the `@import`_ rule and `url()`_ statement of `Cascading
  204. Style Sheets`_. For example, the ``'css/styles.css'`` file with the
  205. content
  206. .. code-block:: css+django
  207. @import url("../admin/css/base.css");
  208. would be replaced by calling the
  209. :meth:`~django.core.files.storage.Storage.url`
  210. method of the ``CachedStaticFilesStorage`` storage backend, ultimatively
  211. saving a ``'css/styles.55e7cbb9ba48.css'`` file with the following
  212. content:
  213. .. code-block:: css+django
  214. @import url("../admin/css/base.27e20196a850.css");
  215. To enable the ``CachedStaticFilesStorage`` you have to make sure the
  216. following requirements are met:
  217. * the :setting:`STATICFILES_STORAGE` setting is set to
  218. ``'django.contrib.staticfiles.storage.CachedStaticFilesStorage'``
  219. * the :setting:`DEBUG` setting is set to ``False``
  220. * you use the ``staticfiles`` :ttag:`static<staticfiles-static>` template
  221. tag to refer to your static files in your templates
  222. * you've collected all your static files by using the
  223. :djadmin:`collectstatic` management command
  224. Since creating the MD5 hash can be a performance burden to your website
  225. during runtime, ``staticfiles`` will automatically try to cache the
  226. hashed name for each file path using Django's :doc:`caching
  227. framework</topics/cache>`. If you want to override certain options of the
  228. cache backend the storage uses, simply specify a custom entry in the
  229. :setting:`CACHES` setting named ``'staticfiles'``. It falls back to using
  230. the ``'default'`` cache backend.
  231. .. method:: file_hash(name, content=None)
  232. .. versionadded:: 1.5
  233. The method that is used when creating the hashed name of a file.
  234. Needs to return a hash for the given file name and content.
  235. By default it calculates a MD5 hash from the content's chunks as
  236. mentioned above.
  237. .. _`far future Expires headers`: http://developer.yahoo.com/performance/rules.html#expires
  238. .. _`@import`: http://www.w3.org/TR/CSS2/cascade.html#at-import
  239. .. _`url()`: http://www.w3.org/TR/CSS2/syndata.html#uri
  240. .. _`Cascading Style Sheets`: http://www.w3.org/Style/CSS/
  241. .. currentmodule:: django.contrib.staticfiles.templatetags.staticfiles
  242. Template tags
  243. =============
  244. static
  245. ------
  246. .. templatetag:: staticfiles-static
  247. Uses the configured :setting:`STATICFILES_STORAGE` storage to create the
  248. full URL for the given relative path, e.g.:
  249. .. code-block:: html+django
  250. {% load static from staticfiles %}
  251. <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
  252. The previous example is equal to calling the ``url`` method of an instance of
  253. :setting:`STATICFILES_STORAGE` with ``"images/hi.jpg"``. This is especially
  254. useful when using a non-local storage backend to deploy files as documented
  255. in :ref:`staticfiles-from-cdn`.
  256. .. versionadded:: 1.5
  257. If you'd like to retrieve a static URL without displaying it, you can use a
  258. slightly different call:
  259. .. code-block:: html+django
  260. {% load static from staticfiles %}
  261. {% static "images/hi.jpg" as myphoto %}
  262. <img src="{{ myphoto }}" alt="Hi!" />
  263. Other Helpers
  264. =============
  265. There are a few other helpers outside of the
  266. :mod:`staticfiles <django.contrib.staticfiles>` app to work with static
  267. files:
  268. - The :func:`django.core.context_processors.static` context processor
  269. which adds :setting:`STATIC_URL` to every template context rendered
  270. with :class:`~django.template.RequestContext` contexts.
  271. - The builtin template tag :ttag:`static` which takes a path and
  272. urljoins it with the static prefix :setting:`STATIC_URL`.
  273. - The builtin template tag :ttag:`get_static_prefix` which populates a
  274. template variable with the static prefix :setting:`STATIC_URL` to be
  275. used as a variable or directly.
  276. - The similar template tag :ttag:`get_media_prefix` which works like
  277. :ttag:`get_static_prefix` but uses :setting:`MEDIA_URL`.
  278. .. _staticfiles-development-view:
  279. Static file development view
  280. ----------------------------
  281. .. highlight:: python
  282. .. function:: django.contrib.staticfiles.views.serve(request, path)
  283. This view function serves static files in development.
  284. .. warning::
  285. This view will only work if :setting:`DEBUG` is ``True``.
  286. That's because this view is **grossly inefficient** and probably
  287. **insecure**. This is only intended for local development, and should
  288. **never be used in production**.
  289. This view is automatically enabled by :djadmin:`runserver` (with a
  290. :setting:`DEBUG` setting set to ``True``). To use the view with a different
  291. local development server, add the following snippet to the end of your
  292. primary URL configuration::
  293. from django.conf import settings
  294. if settings.DEBUG:
  295. urlpatterns += patterns('django.contrib.staticfiles.views',
  296. url(r'^static/(?P<path>.*)$', 'serve'),
  297. )
  298. Note, the beginning of the pattern (``r'^static/'``) should be your
  299. :setting:`STATIC_URL` setting.
  300. Since this is a bit finicky, there's also a helper function that'll do this for you:
  301. .. function:: django.contrib.staticfiles.urls.staticfiles_urlpatterns()
  302. This will return the proper URL pattern for serving static files to your
  303. already defined pattern list. Use it like this::
  304. from django.contrib.staticfiles.urls import staticfiles_urlpatterns
  305. # ... the rest of your URLconf here ...
  306. urlpatterns += staticfiles_urlpatterns()
  307. .. warning::
  308. This helper function will only work if :setting:`DEBUG` is ``True``
  309. and your :setting:`STATIC_URL` setting is neither empty nor a full
  310. URL such as ``http://static.example.com/``.