django1/docs/ref/contrib/staticfiles.txt

454 lines
15 KiB
Plaintext
Raw Normal View History

===================
The staticfiles app
===================
.. module:: django.contrib.staticfiles
:synopsis: An app for handling static files.
.. versionadded:: 1.3
``django.contrib.staticfiles`` collects static files from each of your
applications (and any other places you specify) into a single location that
can easily be served in production.
.. seealso::
For an introduction to the static files app and some usage examples, see
:doc:`/howto/static-files`.
.. _staticfiles-settings:
Settings
========
.. highlight:: python
.. note::
The following settings control the behavior of the staticfiles app.
.. setting:: STATICFILES_DIRS
STATICFILES_DIRS
----------------
Default: ``[]``
This setting defines the additional locations the staticfiles app will traverse
if the :class:`FileSystemFinder` finder is enabled, e.g. if you use the
:djadmin:`collectstatic` or :djadmin:`findstatic` management command or use the
static file serving view.
This should be set to a list or tuple of strings that contain full paths to
your additional files directory(ies) e.g.::
STATICFILES_DIRS = (
"/home/special.polls.com/polls/static",
"/home/polls.com/polls/static",
"/opt/webfiles/common",
)
Prefixes (optional)
"""""""""""""""""""
In case you want to refer to files in one of the locations with an additional
namespace, you can **optionally** provide a prefix as ``(prefix, path)``
tuples, e.g.::
STATICFILES_DIRS = (
# ...
("downloads", "/opt/webfiles/stats"),
)
Example:
Assuming you have :setting:`STATIC_URL` set ``'/static/'``, the
:djadmin:`collectstatic` management command would collect the "stats" files
in a ``'downloads'`` subdirectory of :setting:`STATIC_ROOT`.
This would allow you to refer to the local file
``'/opt/webfiles/stats/polls_20101022.tar.gz'`` with
``'/static/downloads/polls_20101022.tar.gz'`` in your templates, e.g.:
.. code-block:: html+django
<a href="{{ STATIC_URL }}downloads/polls_20101022.tar.gz">
.. setting:: STATICFILES_STORAGE
STATICFILES_STORAGE
-------------------
Default: ``'django.contrib.staticfiles.storage.StaticFilesStorage'``
The file storage engine to use when collecting static files with the
:djadmin:`collectstatic` management command.
.. versionadded:: 1.4
A ready-to-use instance of the storage backend defined in this setting
can be found at ``django.contrib.staticfiles.storage.staticfiles_storage``.
For an example, see :ref:`staticfiles-from-cdn`.
.. setting:: STATICFILES_FINDERS
STATICFILES_FINDERS
-------------------
Default::
("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
The list of finder backends that know how to find static files in
various locations.
The default will find files stored in the :setting:`STATICFILES_DIRS` setting
(using :class:`django.contrib.staticfiles.finders.FileSystemFinder`) and in a
``static`` subdirectory of each app (using
:class:`django.contrib.staticfiles.finders.AppDirectoriesFinder`)
One finder is disabled by default:
:class:`django.contrib.staticfiles.finders.DefaultStorageFinder`. If added to
your :setting:`STATICFILES_FINDERS` setting, it will look for static files in
the default file storage as defined by the :setting:`DEFAULT_FILE_STORAGE`
setting.
.. note::
When using the :class:`AppDirectoriesFinder` finder, make sure your apps
can be found by staticfiles. Simply add the app to the
:setting:`INSTALLED_APPS` setting of your site.
Static file finders are currently considered a private interface, and this
interface is thus undocumented.
Management Commands
===================
.. highlight:: console
``django.contrib.staticfiles`` exposes three management commands.
collectstatic
-------------
.. django-admin:: collectstatic
Collects the static files into :setting:`STATIC_ROOT`.
Duplicate file names are by default resolved in a similar way to how template
resolution works: the file that is first found in one of the specified
locations will be used. If you're confused, the :djadmin:`findstatic` command
can help show you which files are found.
Files are searched by using the :setting:`enabled finders
<STATICFILES_FINDERS>`. The default is to look in all locations defined in
:setting:`STATICFILES_DIRS` and in the ``'static'`` directory of apps
specified by the :setting:`INSTALLED_APPS` setting.
.. versionadded:: 1.4
The :djadmin:`collectstatic` management command calls the
:meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
method of the :setting:`STATICFILES_STORAGE` after each run and passes
a list of paths that have been found by the management command. It also
receives all command line options of :djadmin:`collectstatic`. This is used
by the :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
by default.
Some commonly used options are:
.. django-admin-option:: --noinput
Do NOT prompt the user for input of any kind.
.. django-admin-option:: -i <pattern>
.. django-admin-option:: --ignore <pattern>
Ignore files or directories matching this glob-style pattern. Use multiple
times to ignore more.
.. django-admin-option:: -n
.. django-admin-option:: --dry-run
Do everything except modify the filesystem.
.. django-admin-option:: -c
.. django-admin-option:: --clear
.. versionadded:: 1.4
Clear the existing files before trying to copy or link the original file.
.. django-admin-option:: -l
.. django-admin-option:: --link
Create a symbolic link to each file instead of copying.
.. django-admin-option:: --no-post-process
.. versionadded:: 1.4
Don't call the
:meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
method of the configured :setting:`STATICFILES_STORAGE` storage backend.
.. django-admin-option:: --no-default-ignore
Don't ignore the common private glob-style patterns ``'CVS'``, ``'.*'``
and ``'*~'``.
For a full list of options, refer to the commands own help by running::
$ python manage.py collectstatic --help
findstatic
----------
.. django-admin:: findstatic
Searches for one or more relative paths with the enabled finders.
For example::
$ python manage.py findstatic css/base.css admin/js/core.js
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css
/home/polls.com/src/django/contrib/admin/media/js/core.js
By default, all matching locations are found. To only return the first match
for each relative path, use the ``--first`` option::
$ python manage.py findstatic css/base.css --first
/home/special.polls.com/core/static/css/base.css
This is a debugging aid; it'll show you exactly which static file will be
collected for a given path.
.. _staticfiles-runserver:
runserver
---------
.. django-admin:: runserver
Overrides the core :djadmin:`runserver` command if the ``staticfiles`` app
is :setting:`installed<INSTALLED_APPS>` and adds automatic serving of static
files and the following new options.
.. django-admin-option:: --nostatic
Use the ``--nostatic`` option to disable serving of static files with the
:doc:`staticfiles </ref/contrib/staticfiles>` app entirely. This option is
only available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
in your project's :setting:`INSTALLED_APPS` setting.
Example usage::
django-admin.py runserver --nostatic
.. django-admin-option:: --insecure
Use the ``--insecure`` option to force serving of static files with the
:doc:`staticfiles </ref/contrib/staticfiles>` app even if the :setting:`DEBUG`
setting is ``False``. By using this you acknowledge the fact that it's
**grossly inefficient** and probably **insecure**. This is only intended for
local development, should **never be used in production** and is only
available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is
in your project's :setting:`INSTALLED_APPS` setting.
Example usage::
django-admin.py runserver --insecure
Storages
========
StaticFilesStorage
------------------
.. class:: storage.StaticFilesStorage
A subclass of the :class:`~django.core.files.storage.FileSystemStorage`
storage backend that uses the :setting:`STATIC_ROOT` setting as the base
file system location and the :setting:`STATIC_URL` setting respectively
as the base URL.
.. method:: post_process(paths, **options)
.. versionadded:: 1.4
This method is called by the :djadmin:`collectstatic` management command
after each run and gets passed the local storages and paths of found
files as a dictionary, as well as the command line options.
The :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
uses this behind the scenes to replace the paths with their hashed
counterparts and update the cache appropriately.
CachedStaticFilesStorage
------------------------
.. class:: storage.CachedStaticFilesStorage
.. versionadded:: 1.4
A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
storage backend which caches the files it saves by appending the MD5 hash
of the file's content to the filename. For example, the file
``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
The purpose of this storage is to keep serving the old files in case some
pages still refer to those files, e.g. because they are cached by you or
a 3rd party proxy server. Additionally, it's very helpful if you want to
apply `far future Expires headers`_ to the deployed files to speed up the
load time for subsequent page visits.
The storage backend automatically replaces the paths found in the saved
files matching other saved files with the path of the cached copy (using
the :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`
method). The regular expressions used to find those paths
(``django.contrib.staticfiles.storage.CachedStaticFilesStorage.cached_patterns``)
by default cover the `@import`_ rule and `url()`_ statement of `Cascading
Style Sheets`_. For example, the ``'css/styles.css'`` file with the
content
.. code-block:: css+django
@import url("../admin/css/base.css");
would be replaced by calling the
:meth:`~django.core.files.storage.Storage.url`
method of the ``CachedStaticFilesStorage`` storage backend, ultimatively
saving a ``'css/styles.55e7cbb9ba48.css'`` file with the following
content:
.. code-block:: css+django
@import url("/static/admin/css/base.27e20196a850.css");
To enable the ``CachedStaticFilesStorage`` you have to make sure the
following requirements are met:
* the :setting:`STATICFILES_STORAGE` setting is set to
``'django.contrib.staticfiles.storage.CachedStaticFilesStorage'``
* the :setting:`DEBUG` setting is set to ``False``
* you use the ``staticfiles`` :ttag:`static<staticfiles-static>` template
tag to refer to your static files in your templates
* you've collected all your static files by using the
:djadmin:`collectstatic` management command
Since creating the MD5 hash can be a performance burden to your website
during runtime, ``staticfiles`` will automatically try to cache the
hashed name for each file path using Django's :doc:`caching
framework</topics/cache>`. If you want to override certain options of the
cache backend the storage uses, simply specify a custom entry in the
:setting:`CACHES` setting named ``'staticfiles'``. It falls back to using
the ``'default'`` cache backend.
.. _`far future Expires headers`: http://developer.yahoo.com/performance/rules.html#expires
.. _`@import`: http://www.w3.org/TR/CSS2/cascade.html#at-import
.. _`url()`: http://www.w3.org/TR/CSS2/syndata.html#uri
.. _`Cascading Style Sheets`: http://www.w3.org/Style/CSS/
.. currentmodule:: django.contrib.staticfiles.templatetags.staticfiles
Template tags
=============
static
------
.. templatetag:: staticfiles-static
.. versionadded:: 1.4
Uses the configured :setting:`STATICFILES_STORAGE` storage to create the
full URL for the given relative path, e.g.:
.. code-block:: html+django
{% load static from staticfiles %}
<img src="{% static "css/base.css" %}" />
The previous example is equal to calling the ``url`` method of an instance of
:setting:`STATICFILES_STORAGE` with ``"css/base.css"``. This is especially
useful when using a non-local storage backend to deploy files as documented
in :ref:`staticfiles-from-cdn`.
Other Helpers
=============
There are a few other helpers outside of the
:mod:`staticfiles <django.contrib.staticfiles>` app to work with static
files:
- The :func:`django.core.context_processors.static` context processor
which adds :setting:`STATIC_URL` to every template context rendered
with :class:`~django.template.RequestContext` contexts.
- The builtin template tag :ttag:`static` which takes a path and
urljoins it with the static prefix :setting:`STATIC_URL`.
- The builtin template tag :ttag:`get_static_prefix` which populates a
template variable with the static prefix :setting:`STATIC_URL` to be
used as a variable or directly.
- The similar template tag :ttag:`get_media_prefix` which works like
:ttag:`get_static_prefix` but uses :setting:`MEDIA_URL`.
.. _staticfiles-development-view:
Static file development view
----------------------------
.. highlight:: python
.. function:: django.contrib.staticfiles.views.serve(request, path)
This view function serves static files in development.
.. warning::
This view will only work if :setting:`DEBUG` is ``True``.
That's because this view is **grossly inefficient** and probably
**insecure**. This is only intended for local development, and should
**never be used in production**.
This view is automatically enabled by :djadmin:`runserver` (with a
:setting:`DEBUG` setting set to ``True``). To use the view with a different
local development server, add the following snippet to the end of your
primary URL configuration::
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'^static/(?P<path>.*)$', 'serve'),
)
Note, the beginning of the pattern (``r'^static/'``) should be your
:setting:`STATIC_URL` setting.
Since this is a bit finicky, there's also a helper function that'll do this for you:
.. function:: django.contrib.staticfiles.urls.staticfiles_urlpatterns()
This will return the proper URL pattern for serving static files to your
already defined pattern list. Use it like this::
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
.. warning::
This helper function will only work if :setting:`DEBUG` is ``True``
and your :setting:`STATIC_URL` setting is neither empty nor a full
URL such as ``http://static.example.com/``.