staticfiles.txt 18 KB

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