staticfiles.txt 14 KB

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