App Engine Python SDK version 1.7.4 (2)
[gae.git] / python / lib / django_1_4 / docs / ref / contrib / staticfiles.txt
blob1dbd00b2996364836196bc5f4dfbb0a7b7d2e4fc
1 ===================
2 The staticfiles app
3 ===================
5 .. module:: django.contrib.staticfiles
6    :synopsis: An app for handling static files.
8 .. versionadded:: 1.3
10 ``django.contrib.staticfiles`` collects static files from each of your
11 applications (and any other places you specify) into a single location that
12 can easily be served in production.
14 .. seealso::
16     For an introduction to the static files app and some usage examples, see
17     :doc:`/howto/static-files`.
19 .. _staticfiles-settings:
21 Settings
22 ========
24 .. highlight:: python
26 .. note::
28     The following settings control the behavior of the staticfiles app.
30 .. setting:: STATICFILES_DIRS
32 STATICFILES_DIRS
33 ----------------
35 Default: ``[]``
37 This setting defines the additional locations the staticfiles app will traverse
38 if the :class:`FileSystemFinder` finder is enabled, e.g. if you use the
39 :djadmin:`collectstatic` or :djadmin:`findstatic` management command or use the
40 static file serving view.
42 This should be set to a list or tuple of strings that contain full paths to
43 your additional files directory(ies) e.g.::
45     STATICFILES_DIRS = (
46         "/home/special.polls.com/polls/static",
47         "/home/polls.com/polls/static",
48         "/opt/webfiles/common",
49     )
51 Prefixes (optional)
52 """""""""""""""""""
54 In case you want to refer to files in one of the locations with an additional
55 namespace, you can **optionally** provide a prefix as ``(prefix, path)``
56 tuples, e.g.::
58     STATICFILES_DIRS = (
59         # ...
60         ("downloads", "/opt/webfiles/stats"),
61     )
63 Example:
65 Assuming you have :setting:`STATIC_URL` set ``'/static/'``, the
66 :djadmin:`collectstatic` management command would collect the "stats" files
67 in a ``'downloads'`` subdirectory of :setting:`STATIC_ROOT`.
69 This would allow you to refer to the local file
70 ``'/opt/webfiles/stats/polls_20101022.tar.gz'`` with
71 ``'/static/downloads/polls_20101022.tar.gz'`` in your templates, e.g.:
73 .. code-block:: html+django
75     <a href="{{ STATIC_URL }}downloads/polls_20101022.tar.gz">
77 .. setting:: STATICFILES_STORAGE
79 STATICFILES_STORAGE
80 -------------------
82 Default: ``'django.contrib.staticfiles.storage.StaticFilesStorage'``
84 The file storage engine to use when collecting static files with the
85 :djadmin:`collectstatic` management command.
87 .. versionadded:: 1.4
89 A ready-to-use instance of the storage backend defined in this setting
90 can be found at ``django.contrib.staticfiles.storage.staticfiles_storage``.
92 For an example, see :ref:`staticfiles-from-cdn`.
94 .. setting:: STATICFILES_FINDERS
96 STATICFILES_FINDERS
97 -------------------
99 Default::
101     ("django.contrib.staticfiles.finders.FileSystemFinder",
102      "django.contrib.staticfiles.finders.AppDirectoriesFinder")
104 The list of finder backends that know how to find static files in
105 various locations.
107 The default will find files stored in the :setting:`STATICFILES_DIRS` setting
108 (using :class:`django.contrib.staticfiles.finders.FileSystemFinder`) and in a
109 ``static`` subdirectory of each app (using
110 :class:`django.contrib.staticfiles.finders.AppDirectoriesFinder`)
112 One finder is disabled by default:
113 :class:`django.contrib.staticfiles.finders.DefaultStorageFinder`. If added to
114 your :setting:`STATICFILES_FINDERS` setting, it will look for static files in
115 the default file storage as defined by the :setting:`DEFAULT_FILE_STORAGE`
116 setting.
118 .. note::
120     When using the :class:`AppDirectoriesFinder` finder, make sure your apps
121     can be found by staticfiles. Simply add the app to the
122     :setting:`INSTALLED_APPS` setting of your site.
124 Static file finders are currently considered a private interface, and this
125 interface is thus undocumented.
127 Management Commands
128 ===================
130 .. highlight:: console
132 ``django.contrib.staticfiles`` exposes three management commands.
134 collectstatic
135 -------------
137 .. django-admin:: collectstatic
139 Collects the static files into :setting:`STATIC_ROOT`.
141 Duplicate file names are by default resolved in a similar way to how template
142 resolution works: the file that is first found in one of the specified
143 locations will be used. If you're confused, the :djadmin:`findstatic` command
144 can help show you which files are found.
146 Files are searched by using the :setting:`enabled finders
147 <STATICFILES_FINDERS>`. The default is to look in all locations defined in
148 :setting:`STATICFILES_DIRS` and in the ``'static'`` directory of apps
149 specified by the :setting:`INSTALLED_APPS` setting.
151 .. versionadded:: 1.4
153 The :djadmin:`collectstatic` management command calls the
154 :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
155 method of the :setting:`STATICFILES_STORAGE` after each run and passes
156 a list of paths that have been found by the management command. It also
157 receives all command line options of :djadmin:`collectstatic`. This is used
158 by the :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
159 by default.
161 Some commonly used options are:
163 .. django-admin-option:: --noinput
165     Do NOT prompt the user for input of any kind.
167 .. django-admin-option:: -i <pattern>
168 .. django-admin-option:: --ignore <pattern>
170     Ignore files or directories matching this glob-style pattern. Use multiple
171     times to ignore more.
173 .. django-admin-option:: -n
174 .. django-admin-option:: --dry-run
176     Do everything except modify the filesystem.
178 .. django-admin-option:: -c
179 .. django-admin-option:: --clear
181     .. versionadded:: 1.4
183     Clear the existing files before trying to copy or link the original file.
185 .. django-admin-option:: -l
186 .. django-admin-option:: --link
188     Create a symbolic link to each file instead of copying.
190 .. django-admin-option:: --no-post-process
192     .. versionadded:: 1.4
194     Don't call the
195     :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
196     method of the configured :setting:`STATICFILES_STORAGE` storage backend.
198 .. django-admin-option:: --no-default-ignore
200     Don't ignore the common private glob-style patterns ``'CVS'``, ``'.*'``
201     and ``'*~'``.
203 For a full list of options, refer to the commands own help by running::
205    $ python manage.py collectstatic --help
207 findstatic
208 ----------
210 .. django-admin:: findstatic
212 Searches for one or more relative paths with the enabled finders.
214 For example::
216    $ python manage.py findstatic css/base.css admin/js/core.js
217    /home/special.polls.com/core/static/css/base.css
218    /home/polls.com/core/static/css/base.css
219    /home/polls.com/src/django/contrib/admin/media/js/core.js
221 By default, all matching locations are found. To only return the first match
222 for each relative path, use the ``--first`` option::
224    $ python manage.py findstatic css/base.css --first
225    /home/special.polls.com/core/static/css/base.css
227 This is a debugging aid; it'll show you exactly which static file will be
228 collected for a given path.
230 .. _staticfiles-runserver:
232 runserver
233 ---------
235 .. django-admin:: runserver
237 Overrides the core :djadmin:`runserver` command if the ``staticfiles`` app
238 is :setting:`installed<INSTALLED_APPS>` and adds automatic serving of static
239 files and the following new options.
241 .. django-admin-option:: --nostatic
243 Use the ``--nostatic`` option to disable serving of static files with the
244 :doc:`staticfiles </ref/contrib/staticfiles>` app entirely. This option is
245 only available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
246 in your project's :setting:`INSTALLED_APPS` setting.
248 Example usage::
250     django-admin.py runserver --nostatic
252 .. django-admin-option:: --insecure
254 Use the ``--insecure`` option to force serving of static files with the
255 :doc:`staticfiles </ref/contrib/staticfiles>` app even if the :setting:`DEBUG`
256 setting is ``False``. By using this you acknowledge the fact that it's
257 **grossly inefficient** and probably **insecure**. This is only intended for
258 local development, should **never be used in production** and is only
259 available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
260 in your project's :setting:`INSTALLED_APPS` setting.
262 Example usage::
264     django-admin.py runserver --insecure
266 Storages
267 ========
269 StaticFilesStorage
270 ------------------
272 .. class:: storage.StaticFilesStorage
274     A subclass of the :class:`~django.core.files.storage.FileSystemStorage`
275     storage backend that uses the :setting:`STATIC_ROOT` setting as the base
276     file system location and the :setting:`STATIC_URL` setting respectively
277     as the base URL.
279     .. method:: post_process(paths, **options)
281     .. versionadded:: 1.4
283     This method is called by the :djadmin:`collectstatic` management command
284     after each run and gets passed the local storages and paths of found
285     files as a dictionary, as well as the command line options.
287     The :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
288     uses this behind the scenes to replace the paths with their hashed
289     counterparts and update the cache appropriately.
291 CachedStaticFilesStorage
292 ------------------------
294 .. class:: storage.CachedStaticFilesStorage
296     .. versionadded:: 1.4
298     A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
299     storage backend which caches the files it saves by appending the MD5 hash
300     of the file's content to the filename. For example, the file
301     ``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
303     The purpose of this storage is to keep serving the old files in case some
304     pages still refer to those files, e.g. because they are cached by you or
305     a 3rd party proxy server. Additionally, it's very helpful if you want to
306     apply `far future Expires headers`_ to the deployed files to speed up the
307     load time for subsequent page visits.
309     The storage backend automatically replaces the paths found in the saved
310     files matching other saved files with the path of the cached copy (using
311     the :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
312     method). The regular expressions used to find those paths
313     (``django.contrib.staticfiles.storage.CachedStaticFilesStorage.cached_patterns``)
314     by default cover the `@import`_ rule and `url()`_ statement of `Cascading
315     Style Sheets`_. For example, the ``'css/styles.css'`` file with the
316     content
318     .. code-block:: css+django
320         @import url("../admin/css/base.css");
322     would be replaced by calling the
323     :meth:`~django.core.files.storage.Storage.url`
324     method of the ``CachedStaticFilesStorage`` storage backend, ultimatively
325     saving a ``'css/styles.55e7cbb9ba48.css'`` file with the following
326     content:
328     .. code-block:: css+django
330         @import url("../admin/css/base.27e20196a850.css");
332     To enable the ``CachedStaticFilesStorage`` you have to make sure the
333     following requirements are met:
335     * the :setting:`STATICFILES_STORAGE` setting is set to
336       ``'django.contrib.staticfiles.storage.CachedStaticFilesStorage'``
337     * the :setting:`DEBUG` setting is set to ``False``
338     * you use the ``staticfiles`` :ttag:`static<staticfiles-static>` template
339       tag to refer to your static files in your templates
340     * you've collected all your static files by using the
341       :djadmin:`collectstatic` management command
343     Since creating the MD5 hash can be a performance burden to your website
344     during runtime, ``staticfiles`` will automatically try to cache the
345     hashed name for each file path using Django's :doc:`caching
346     framework</topics/cache>`. If you want to override certain options of the
347     cache backend the storage uses, simply specify a custom entry in the
348     :setting:`CACHES` setting named ``'staticfiles'``. It falls back to using
349     the ``'default'`` cache backend.
351 .. _`far future Expires headers`: http://developer.yahoo.com/performance/rules.html#expires
352 .. _`@import`: http://www.w3.org/TR/CSS2/cascade.html#at-import
353 .. _`url()`: http://www.w3.org/TR/CSS2/syndata.html#uri
354 .. _`Cascading Style Sheets`: http://www.w3.org/Style/CSS/
356 .. currentmodule:: django.contrib.staticfiles.templatetags.staticfiles
358 Template tags
359 =============
361 static
362 ------
364 .. templatetag:: staticfiles-static
366 .. versionadded:: 1.4
368 Uses the configured :setting:`STATICFILES_STORAGE` storage to create the
369 full URL for the given relative path, e.g.:
371 .. code-block:: html+django
373     {% load static from staticfiles %}
374     <img src="{% static "css/base.css" %}" />
376 The previous example is equal to calling the ``url`` method of an instance of
377 :setting:`STATICFILES_STORAGE` with ``"css/base.css"``. This is especially
378 useful when using a non-local storage backend to deploy files as documented
379 in :ref:`staticfiles-from-cdn`.
381 Other Helpers
382 =============
384 There are a few other helpers outside of the
385 :mod:`staticfiles <django.contrib.staticfiles>` app to work with static
386 files:
388 - The :func:`django.core.context_processors.static` context processor
389   which adds :setting:`STATIC_URL` to every template context rendered
390   with :class:`~django.template.RequestContext` contexts.
392 - The builtin template tag :ttag:`static` which takes a path and
393   urljoins it with the static prefix :setting:`STATIC_URL`.
395 - The builtin template tag :ttag:`get_static_prefix` which populates a
396   template variable with the static prefix :setting:`STATIC_URL` to be
397   used as a variable or directly.
399 - The similar template tag :ttag:`get_media_prefix` which works like
400   :ttag:`get_static_prefix` but uses :setting:`MEDIA_URL`.
402 .. _staticfiles-development-view:
404 Static file development view
405 ----------------------------
407 .. highlight:: python
409 .. function:: django.contrib.staticfiles.views.serve(request, path)
411 This view function serves static files in development.
413 .. warning::
415     This view will only work if :setting:`DEBUG` is ``True``.
417     That's because this view is **grossly inefficient** and probably
418     **insecure**. This is only intended for local development, and should
419     **never be used in production**.
421 This view is automatically enabled by :djadmin:`runserver` (with a
422 :setting:`DEBUG` setting set to ``True``). To use the view with a different
423 local development server, add the following snippet to the end of your
424 primary URL configuration::
426    from django.conf import settings
428    if settings.DEBUG:
429        urlpatterns += patterns('django.contrib.staticfiles.views',
430            url(r'^static/(?P<path>.*)$', 'serve'),
431        )
433 Note, the beginning of the pattern (``r'^static/'``) should be your
434 :setting:`STATIC_URL` setting.
436 Since this is a bit finicky, there's also a helper function that'll do this for you:
438 .. function:: django.contrib.staticfiles.urls.staticfiles_urlpatterns()
440 This will return the proper URL pattern for serving static files to your
441 already defined pattern list. Use it like this::
443    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
445    # ... the rest of your URLconf here ...
447    urlpatterns += staticfiles_urlpatterns()
449 .. warning::
451     This helper function will only work if :setting:`DEBUG` is ``True``
452     and your :setting:`STATIC_URL` setting is neither empty nor a full
453     URL such as ``http://static.example.com/``.