Debian Codegraph @

docs/ref/contrib/staticfiles.txt

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