staticfiles.txt 19 KB

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