staticfiles.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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:`STORAGES`
  19. * :setting:`STATIC_ROOT`
  20. * :setting:`STATIC_URL`
  21. * :setting:`STATICFILES_DIRS`
  22. * :setting:`STATICFILES_STORAGE`
  23. * :setting:`STATICFILES_FINDERS`
  24. Management Commands
  25. ===================
  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. On subsequent ``collectstatic`` runs (if ``STATIC_ROOT`` isn't empty), files
  36. are copied only if they have a modified timestamp greater than the timestamp of
  37. the file in ``STATIC_ROOT``. Therefore if you remove an application from
  38. :setting:`INSTALLED_APPS`, it's a good idea to use the :option:`collectstatic
  39. --clear` option in order to remove stale static files.
  40. Files are searched by using the :setting:`enabled finders
  41. <STATICFILES_FINDERS>`. The default is to look in all locations defined in
  42. :setting:`STATICFILES_DIRS` and in the ``'static'`` directory of apps
  43. specified by the :setting:`INSTALLED_APPS` setting.
  44. The :djadmin:`collectstatic` management command calls the
  45. :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  46. method of the ``staticfiles`` storage backend from :setting:`STORAGES` after
  47. each run and passes a list of paths that have been found by the management
  48. command. It also receives all command line options of :djadmin:`collectstatic`.
  49. This is used by the
  50. :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` by
  51. default.
  52. By default, collected files receive permissions from
  53. :setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive permissions
  54. from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would like different
  55. permissions for these files and/or directories, you can subclass either of the
  56. :ref:`static files storage classes <staticfiles-storages>` and specify the
  57. ``file_permissions_mode`` and/or ``directory_permissions_mode`` parameters,
  58. respectively. For example::
  59. from django.contrib.staticfiles import storage
  60. class MyStaticFilesStorage(storage.StaticFilesStorage):
  61. def __init__(self, *args, **kwargs):
  62. kwargs["file_permissions_mode"] = 0o640
  63. kwargs["directory_permissions_mode"] = 0o760
  64. super().__init__(*args, **kwargs)
  65. Then set the ``staticfiles`` storage backend in :setting:`STORAGES` setting to
  66. ``'path.to.MyStaticFilesStorage'``.
  67. Some commonly used options are:
  68. .. django-admin-option:: --noinput, --no-input
  69. Do NOT prompt the user for input of any kind.
  70. .. django-admin-option:: --ignore PATTERN, -i PATTERN
  71. Ignore files, directories, or paths matching this glob-style pattern. Use
  72. multiple times to ignore more. When specifying a path, always use forward
  73. slashes, even on Windows.
  74. .. django-admin-option:: --dry-run, -n
  75. Do everything except modify the filesystem.
  76. .. django-admin-option:: --clear, -c
  77. Clear the existing files before trying to copy or link the original file.
  78. .. django-admin-option:: --link, -l
  79. Create a symbolic link to each file instead of copying.
  80. .. django-admin-option:: --no-post-process
  81. Don't call the
  82. :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  83. method of the configured ``staticfiles`` storage backend from
  84. :setting:`STORAGES`.
  85. .. django-admin-option:: --no-default-ignore
  86. Don't ignore the common private glob-style patterns ``'CVS'``, ``'.*'``
  87. and ``'*~'``.
  88. For a full list of options, refer to the commands own help by running:
  89. .. console::
  90. $ python manage.py collectstatic --help
  91. .. _customize-staticfiles-ignore-patterns:
  92. Customizing the ignored pattern list
  93. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  94. The default ignored pattern list, ``['CVS', '.*', '*~']``, can be customized in
  95. a more persistent way than providing the ``--ignore`` command option at each
  96. ``collectstatic`` invocation. Provide a custom :class:`~django.apps.AppConfig`
  97. class, override the ``ignore_patterns`` attribute of this class and replace
  98. ``'django.contrib.staticfiles'`` with that class path in your
  99. :setting:`INSTALLED_APPS` setting::
  100. from django.contrib.staticfiles.apps import StaticFilesConfig
  101. class MyStaticFilesConfig(StaticFilesConfig):
  102. ignore_patterns = [...] # your custom ignore list
  103. ``findstatic``
  104. --------------
  105. .. django-admin:: findstatic staticfile [staticfile ...]
  106. Searches for one or more relative paths with the enabled finders.
  107. For example:
  108. .. console::
  109. $ python manage.py findstatic css/base.css admin/js/core.js
  110. Found 'css/base.css' here:
  111. /home/special.polls.com/core/static/css/base.css
  112. /home/polls.com/core/static/css/base.css
  113. Found 'admin/js/core.js' here:
  114. /home/polls.com/src/django/contrib/admin/media/js/core.js
  115. .. django-admin-option:: findstatic --first
  116. By default, all matching locations are found. To only return the first match
  117. for each relative path, use the ``--first`` option:
  118. .. console::
  119. $ python manage.py findstatic css/base.css --first
  120. Found 'css/base.css' here:
  121. /home/special.polls.com/core/static/css/base.css
  122. This is a debugging aid; it'll show you exactly which static file will be
  123. collected for a given path.
  124. By setting the ``--verbosity`` flag to 0, you can suppress the extra output and
  125. just get the path names:
  126. .. console::
  127. $ python manage.py findstatic css/base.css --verbosity 0
  128. /home/special.polls.com/core/static/css/base.css
  129. /home/polls.com/core/static/css/base.css
  130. On the other hand, by setting the ``--verbosity`` flag to 2, you can get all
  131. the directories which were searched:
  132. .. console::
  133. $ python manage.py findstatic css/base.css --verbosity 2
  134. Found 'css/base.css' here:
  135. /home/special.polls.com/core/static/css/base.css
  136. /home/polls.com/core/static/css/base.css
  137. Looking in the following locations:
  138. /home/special.polls.com/core/static
  139. /home/polls.com/core/static
  140. /some/other/path/static
  141. .. _staticfiles-runserver:
  142. ``runserver``
  143. -------------
  144. .. django-admin:: runserver [addrport]
  145. :noindex:
  146. Overrides the core :djadmin:`runserver` command if the ``staticfiles`` app
  147. is :setting:`installed<INSTALLED_APPS>` and adds automatic serving of static
  148. files. File serving doesn't run through :setting:`MIDDLEWARE`.
  149. The command adds these options:
  150. .. django-admin-option:: --nostatic
  151. Use the ``--nostatic`` option to disable serving of static files with the
  152. :doc:`staticfiles </ref/contrib/staticfiles>` app entirely. This option is
  153. only available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
  154. in your project's :setting:`INSTALLED_APPS` setting.
  155. Example usage:
  156. .. console::
  157. $ django-admin runserver --nostatic
  158. .. django-admin-option:: --insecure
  159. Use the ``--insecure`` option to force serving of static files with the
  160. :doc:`staticfiles </ref/contrib/staticfiles>` app even if the :setting:`DEBUG`
  161. setting is ``False``. By using this you acknowledge the fact that it's
  162. **grossly inefficient** and probably **insecure**. This is only intended for
  163. local development, should **never be used in production** and is only
  164. available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
  165. in your project's :setting:`INSTALLED_APPS` setting.
  166. ``--insecure`` doesn't work with :class:`~.storage.ManifestStaticFilesStorage`.
  167. Example usage:
  168. .. console::
  169. $ django-admin runserver --insecure
  170. .. _staticfiles-storages:
  171. Storages
  172. ========
  173. ``StaticFilesStorage``
  174. ----------------------
  175. .. class:: storage.StaticFilesStorage
  176. A subclass of the :class:`~django.core.files.storage.FileSystemStorage`
  177. storage backend that uses the :setting:`STATIC_ROOT` setting as the base
  178. file system location and the :setting:`STATIC_URL` setting respectively
  179. as the base URL.
  180. .. method:: storage.StaticFilesStorage.post_process(paths, **options)
  181. If this method is defined on a storage, it's called by the
  182. :djadmin:`collectstatic` management command after each run and gets passed the
  183. local storages and paths of found files as a dictionary, as well as the command
  184. line options. It yields tuples of three values:
  185. ``original_path, processed_path, processed``. The path values are strings and
  186. ``processed`` is a boolean indicating whether or not the value was
  187. post-processed, or an exception if post-processing failed.
  188. The :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`
  189. uses this behind the scenes to replace the paths with their hashed
  190. counterparts and update the cache appropriately.
  191. ``ManifestStaticFilesStorage``
  192. ------------------------------
  193. .. class:: storage.ManifestStaticFilesStorage
  194. A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
  195. storage backend which stores the file names it handles by appending the MD5
  196. hash of the file's content to the filename. For example, the file
  197. ``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
  198. The purpose of this storage is to keep serving the old files in case some
  199. pages still refer to those files, e.g. because they are cached by you or
  200. a 3rd party proxy server. Additionally, it's very helpful if you want to
  201. apply `far future Expires headers`_ to the deployed files to speed up the
  202. load time for subsequent page visits.
  203. The storage backend automatically replaces the paths found in the saved
  204. files matching other saved files with the path of the cached copy (using
  205. the :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
  206. method). The regular expressions used to find those paths
  207. (``django.contrib.staticfiles.storage.HashedFilesMixin.patterns``) cover:
  208. * The `@import`_ rule and `url()`_ statement of `Cascading Style Sheets`_.
  209. * `Source map`_ comments in CSS and JavaScript files.
  210. Subclass ``ManifestStaticFilesStorage`` and set the
  211. ``support_js_module_import_aggregation`` attribute to ``True``, if you want to
  212. use the experimental regular expressions to cover:
  213. * The `modules import`_ in JavaScript.
  214. * The `modules aggregation`_ in JavaScript.
  215. For example, the ``'css/styles.css'`` file with this content:
  216. .. code-block:: css
  217. @import url("../admin/css/base.css");
  218. ...would be replaced by calling the
  219. :meth:`~django.core.files.storage.Storage.url` method of the
  220. ``ManifestStaticFilesStorage`` storage backend, ultimately saving a
  221. ``'css/styles.55e7cbb9ba48.css'`` file with the following content:
  222. .. code-block:: css
  223. @import url("../admin/css/base.27e20196a850.css");
  224. .. admonition:: Usage of the ``integrity`` HTML attribute with local files
  225. When using the optional ``integrity`` attribute within tags like
  226. ``<script>`` or ``<link>``, its value should be calculated based on the
  227. files as they are served, not as stored in the filesystem. This is
  228. particularly important because depending on how static files are collected,
  229. their checksum may have changed (for example when using
  230. :djadmin:`collectstatic`). At the moment, there is no out-of-the-box
  231. tooling available for this.
  232. You can change the location of the manifest file by using a custom
  233. ``ManifestStaticFilesStorage`` subclass that sets the ``manifest_storage``
  234. argument. For example::
  235. from django.conf import settings
  236. from django.contrib.staticfiles.storage import (
  237. ManifestStaticFilesStorage,
  238. StaticFilesStorage,
  239. )
  240. class MyManifestStaticFilesStorage(ManifestStaticFilesStorage):
  241. def __init__(self, *args, **kwargs):
  242. manifest_storage = StaticFilesStorage(location=settings.BASE_DIR)
  243. super().__init__(*args, manifest_storage=manifest_storage, **kwargs)
  244. .. admonition:: References in comments
  245. ``ManifestStaticFilesStorage`` doesn't ignore paths in statements that are
  246. commented out. This :ticket:`may crash on the nonexistent paths <21080>`.
  247. You should check and eventually strip comments.
  248. .. versionchanged:: 4.2
  249. Experimental optional support for finding paths to JavaScript modules in
  250. ``import`` and ``export`` statements was added.
  251. .. attribute:: storage.ManifestStaticFilesStorage.manifest_hash
  252. .. versionadded:: 4.2
  253. This attribute provides a single hash that changes whenever a file in the
  254. manifest changes. This can be useful to communicate to SPAs that the assets on
  255. the server have changed (due to a new deployment).
  256. .. attribute:: storage.ManifestStaticFilesStorage.max_post_process_passes
  257. Since static files might reference other static files that need to have their
  258. paths replaced, multiple passes of replacing paths may be needed until the file
  259. hashes converge. To prevent an infinite loop due to hashes not converging (for
  260. example, if ``'foo.css'`` references ``'bar.css'`` which references
  261. ``'foo.css'``) there is a maximum number of passes before post-processing is
  262. abandoned. In cases with a large number of references, a higher number of
  263. passes might be needed. Increase the maximum number of passes by subclassing
  264. ``ManifestStaticFilesStorage`` and setting the ``max_post_process_passes``
  265. attribute. It defaults to 5.
  266. To enable the ``ManifestStaticFilesStorage`` you have to make sure the
  267. following requirements are met:
  268. * the ``staticfiles`` storage backend in :setting:`STORAGES` setting is set to
  269. ``'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'``
  270. * the :setting:`DEBUG` setting is set to ``False``
  271. * you've collected all your static files by using the
  272. :djadmin:`collectstatic` management command
  273. Since creating the MD5 hash can be a performance burden to your website
  274. during runtime, ``staticfiles`` will automatically store the mapping with
  275. hashed names for all processed files in a file called ``staticfiles.json``.
  276. This happens once when you run the :djadmin:`collectstatic` management
  277. command.
  278. .. attribute:: storage.ManifestStaticFilesStorage.manifest_strict
  279. If a file isn't found in the ``staticfiles.json`` manifest at runtime, a
  280. ``ValueError`` is raised. This behavior can be disabled by subclassing
  281. ``ManifestStaticFilesStorage`` and setting the ``manifest_strict`` attribute to
  282. ``False`` -- nonexistent paths will remain unchanged.
  283. Due to the requirement of running :djadmin:`collectstatic`, this storage
  284. typically shouldn't be used when running tests as ``collectstatic`` isn't run
  285. as part of the normal test setup. During testing, ensure that ``staticfiles``
  286. storage backend in the :setting:`STORAGES` setting is set to something else
  287. like ``'django.contrib.staticfiles.storage.StaticFilesStorage'`` (the default).
  288. .. method:: storage.ManifestStaticFilesStorage.file_hash(name, content=None)
  289. The method that is used when creating the hashed name of a file.
  290. Needs to return a hash for the given file name and content.
  291. By default it calculates a MD5 hash from the content's chunks as
  292. mentioned above. Feel free to override this method to use your own
  293. hashing algorithm.
  294. .. _`far future Expires headers`: https://developer.yahoo.com/performance/rules.html#expires
  295. .. _`@import`: https://www.w3.org/TR/CSS2/cascade.html#at-import
  296. .. _`url()`: https://www.w3.org/TR/CSS2/syndata.html#uri
  297. .. _`Cascading Style Sheets`: https://www.w3.org/Style/CSS/
  298. .. _`source map`: https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/
  299. .. _`modules import`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_features_into_your_script
  300. .. _`modules aggregation`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#aggregating_modules
  301. ``ManifestFilesMixin``
  302. ----------------------
  303. .. class:: storage.ManifestFilesMixin
  304. Use this mixin with a custom storage to append the MD5 hash of the file's
  305. content to the filename as :class:`~storage.ManifestStaticFilesStorage` does.
  306. Finders Module
  307. ==============
  308. ``staticfiles`` finders has a ``searched_locations`` attribute which is a list
  309. of directory paths in which the finders searched. Example usage::
  310. from django.contrib.staticfiles import finders
  311. result = finders.find("css/base.css")
  312. searched_locations = finders.searched_locations
  313. Other Helpers
  314. =============
  315. There are a few other helpers outside of the
  316. :mod:`staticfiles <django.contrib.staticfiles>` app to work with static
  317. files:
  318. - The :func:`django.template.context_processors.static` context processor
  319. which adds :setting:`STATIC_URL` to every template context rendered
  320. with :class:`~django.template.RequestContext` contexts.
  321. - The builtin template tag :ttag:`static` which takes a path and urljoins it
  322. with the static prefix :setting:`STATIC_URL`. If
  323. ``django.contrib.staticfiles`` is installed, the tag uses the ``url()``
  324. method of the ``staticfiles`` storage backend from :setting:`STORAGES`
  325. instead.
  326. - The builtin template tag :ttag:`get_static_prefix` which populates a
  327. template variable with the static prefix :setting:`STATIC_URL` to be
  328. used as a variable or directly.
  329. - The similar template tag :ttag:`get_media_prefix` which works like
  330. :ttag:`get_static_prefix` but uses :setting:`MEDIA_URL`.
  331. - The ``staticfiles`` key in :data:`django.core.files.storage.storages`
  332. contains a ready-to-use instance of the staticfiles storage backend.
  333. .. _staticfiles-development-view:
  334. Static file development view
  335. ----------------------------
  336. .. currentmodule:: django.contrib.staticfiles
  337. The static files tools are mostly designed to help with getting static files
  338. successfully deployed into production. This usually means a separate,
  339. dedicated static file server, which is a lot of overhead to mess with when
  340. developing locally. Thus, the ``staticfiles`` app ships with a
  341. **quick and dirty helper view** that you can use to serve files locally in
  342. development.
  343. .. function:: views.serve(request, path)
  344. This view function serves static files in development.
  345. .. warning::
  346. This view will only work if :setting:`DEBUG` is ``True``.
  347. That's because this view is **grossly inefficient** and probably
  348. **insecure**. This is only intended for local development, and should
  349. **never be used in production**.
  350. .. note::
  351. To guess the served files' content types, this view relies on the
  352. :py:mod:`mimetypes` module from the Python standard library, which itself
  353. relies on the underlying platform's map files. If you find that this view
  354. doesn't return proper content types for certain files, it is most likely
  355. that the platform's map files are incorrect or need to be updated. This can
  356. be achieved, for example, by installing or updating the ``mailcap`` package
  357. on a Red Hat distribution, ``mime-support`` on a Debian distribution, or by
  358. editing the keys under ``HKEY_CLASSES_ROOT`` in the Windows registry.
  359. This view is automatically enabled by :djadmin:`runserver` (with a
  360. :setting:`DEBUG` setting set to ``True``). To use the view with a different
  361. local development server, add the following snippet to the end of your
  362. primary URL configuration::
  363. from django.conf import settings
  364. from django.contrib.staticfiles import views
  365. from django.urls import re_path
  366. if settings.DEBUG:
  367. urlpatterns += [
  368. re_path(r"^static/(?P<path>.*)$", views.serve),
  369. ]
  370. Note, the beginning of the pattern (``r'^static/'``) should be your
  371. :setting:`STATIC_URL` setting.
  372. Since this is a bit finicky, there's also a helper function that'll do this for
  373. you:
  374. .. function:: urls.staticfiles_urlpatterns()
  375. This will return the proper URL pattern for serving static files to your
  376. already defined pattern list. Use it like this::
  377. from django.contrib.staticfiles.urls import staticfiles_urlpatterns
  378. # ... the rest of your URLconf here ...
  379. urlpatterns += staticfiles_urlpatterns()
  380. This will inspect your :setting:`STATIC_URL` setting and wire up the view
  381. to serve static files accordingly. Don't forget to set the
  382. :setting:`STATICFILES_DIRS` setting appropriately to let
  383. ``django.contrib.staticfiles`` know where to look for files in addition to
  384. files in app directories.
  385. .. warning::
  386. This helper function will only work if :setting:`DEBUG` is ``True``
  387. and your :setting:`STATIC_URL` setting is neither empty nor a full
  388. URL such as ``http://static.example.com/``.
  389. That's because this view is **grossly inefficient** and probably
  390. **insecure**. This is only intended for local development, and should
  391. **never be used in production**.
  392. Specialized test case to support 'live testing'
  393. -----------------------------------------------
  394. .. class:: testing.StaticLiveServerTestCase
  395. This unittest TestCase subclass extends :class:`django.test.LiveServerTestCase`.
  396. Just like its parent, you can use it to write tests that involve running the
  397. code under test and consuming it with testing tools through HTTP (e.g. Selenium,
  398. PhantomJS, etc.), because of which it's needed that the static assets are also
  399. published.
  400. But given the fact that it makes use of the
  401. :func:`django.contrib.staticfiles.views.serve` view described above, it can
  402. transparently overlay at test execution-time the assets provided by the
  403. ``staticfiles`` finders. This means you don't need to run
  404. :djadmin:`collectstatic` before or as a part of your tests setup.