staticfiles.txt 15 KB

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