PageRenderTime 141ms CodeModel.GetById 60ms app.highlight 4ms RepoModel.GetById 37ms app.codeStats 0ms

/docs/howto/static-files.txt

https://code.google.com/p/mango-py/
Plain Text | 498 lines | 360 code | 138 blank | 0 comment | 0 complexity | 23048883a895849422b8d3bca350cd60 MD5 | raw file
  1=====================
  2Managing static files
  3=====================
  4
  5.. versionadded:: 1.3
  6
  7Django developers mostly concern themselves with the dynamic parts of web
  8applications -- the views and templates that render anew for each request. But
  9web applications have other parts: the static files (images, CSS,
 10Javascript, etc.) that are needed to render a complete web page.
 11
 12For small projects, this isn't a big deal, because you can just keep the
 13static files somewhere your web server can find it. However, in bigger
 14projects -- especially those comprised of multiple apps -- dealing with the
 15multiple sets of static files provided by each application starts to get
 16tricky.
 17
 18That's what ``django.contrib.staticfiles`` is for: it collects static files
 19from each of your applications (and any other places you specify) into a
 20single location that can easily be served in production.
 21
 22.. note::
 23
 24    If you've used the `django-staticfiles`_ third-party app before, then
 25    ``django.contrib.staticfiles`` will look very familiar. That's because
 26    they're essentially the same code: ``django.contrib.staticfiles`` started
 27    its life as `django-staticfiles`_ and was merged into Django 1.3.
 28
 29    If you're upgrading from ``django-staticfiles``, please see `Upgrading from
 30    django-staticfiles`_, below, for a few minor changes you'll need to make.
 31
 32.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
 33
 34Using ``django.contrib.staticfiles``
 35====================================
 36
 37Basic usage
 38-----------
 39
 401. Put your static files somewhere that ``staticfiles`` will find them.
 41
 42   By default, this means within ``static/`` subdirectories of apps in your
 43   :setting:`INSTALLED_APPS`.
 44
 45   Your project will probably also have static assets that aren't tied to a
 46   particular app. The :setting:`STATICFILES_DIRS` setting is a tuple of
 47   filesystem directories to check when loading static files. It's a search
 48   path that is by default empty. See the :setting:`STATICFILES_DIRS` docs
 49   how to extend this list of additional paths.
 50
 51   Additionally, see the documentation for the :setting:`STATICFILES_FINDERS`
 52   setting for details on how ``staticfiles`` finds your files.
 53
 542. Make sure that ``django.contrib.staticfiles`` is included in your
 55   :setting:`INSTALLED_APPS`.
 56
 57   For :ref:`local development<staticfiles-development>`, if you are using
 58   :ref:`runserver<staticfiles-runserver>` or adding
 59   :ref:`staticfiles_urlpatterns<staticfiles-development>` to your
 60   URLconf, you're done with the setup -- your static files will
 61   automatically be served at the default (for
 62   :djadmin:`newly created<startproject>` projects) :setting:`STATIC_URL`
 63   of ``/static/``.
 64
 653. You'll probably need to refer to these files in your templates. The
 66   easiest method is to use the included context processor which allows
 67   template code like:
 68
 69   .. code-block:: html+django
 70
 71       <img src="{{ STATIC_URL }}images/hi.jpg" />
 72
 73   See :ref:`staticfiles-in-templates` for more details, including an
 74   alternate method using a template tag.
 75
 76Deploying static files in a nutshell
 77------------------------------------
 78
 79When you're ready to move out of local development and deploy your project:
 80
 811. Set the :setting:`STATIC_URL` setting to the public URL for your static
 82   files (in most cases, the default value of ``/static/`` is just fine).
 83
 842. Set the :setting:`STATIC_ROOT` setting to point to the filesystem path
 85   you'd like your static files collected to when you use the
 86   :djadmin:`collectstatic` management command. For example::
 87
 88       STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"
 89
 903. Run the :djadmin:`collectstatic` management command::
 91
 92       ./manage.py collectstatic
 93
 94   This'll churn through your static file storage and copy them into the
 95   directory given by :setting:`STATIC_ROOT`.
 96
 974. Deploy those files by configuring your webserver of choice to serve the
 98   files in :setting:`STATIC_ROOT` at :setting:`STATIC_URL`.
 99
100   :ref:`staticfiles-production` covers some common deployment strategies
101   for static files.
102
103Those are the **basics**. For more details on common configuration options,
104read on; for a detailed reference of the settings, commands, and other bits
105included with the framework see
106:doc:`the staticfiles reference </ref/contrib/staticfiles>`.
107
108.. note::
109
110   In previous versions of Django, it was common to place static assets in
111   :setting:`MEDIA_ROOT` along with user-uploaded files, and serve them both
112   at :setting:`MEDIA_URL`. Part of the purpose of introducing the
113   ``staticfiles`` app is to make it easier to keep static files separate
114   from user-uploaded files.
115
116   For this reason, you need to make your :setting:`MEDIA_ROOT` and
117   :setting:`MEDIA_URL` different from your :setting:`STATIC_ROOT` and
118   :setting:`STATIC_URL`. You will need to arrange for serving of files in
119   :setting:`MEDIA_ROOT` yourself; ``staticfiles`` does not deal with
120   user-uploaded files at all. You can, however, use
121   :func:`django.views.static.serve` view for serving :setting:`MEDIA_ROOT`
122   in development; see :ref:`staticfiles-other-directories`.
123
124.. _staticfiles-in-templates:
125
126Referring to static files in templates
127======================================
128
129At some point, you'll probably need to link to static files in your templates.
130You could, of course, simply hardcode the path to you assets in the templates:
131
132.. code-block:: html
133
134    <img src="http://static.example.com/static/myimage.jpg" />
135
136Of course, there are some serious problems with this: it doesn't work well in
137development, and it makes it *very* hard to change where you've deployed your
138static files. If, for example, you wanted to switch to using a content
139delivery network (CDN), then you'd need to change more or less every single
140template.
141
142A far better way is to use the value of the :setting:`STATIC_URL` setting
143directly in your templates. This means that a switch of static files servers
144only requires changing that single value. Much better!
145
146``staticfiles`` includes two built-in ways of getting at this setting in your
147templates: a context processor and a template tag.
148
149With a context processor
150------------------------
151
152The included context processor is the easy way. Simply make sure
153``'django.core.context_processors.static'`` is in your
154:setting:`TEMPLATE_CONTEXT_PROCESSORS`. It's there by default, and if you're
155editing that setting by hand it should look something like::
156
157    TEMPLATE_CONTEXT_PROCESSORS = (
158        'django.core.context_processors.debug',
159        'django.core.context_processors.i18n',
160        'django.core.context_processors.media',
161        'django.core.context_processors.static',
162        'django.contrib.auth.context_processors.auth',
163        'django.contrib.messages.context_processors.messages',
164    )
165
166Once that's done, you can refer to :setting:`STATIC_URL` in your templates:
167
168.. code-block:: html+django
169
170     <img src="{{ STATIC_URL }}images/hi.jpg" />
171
172If ``{{ STATIC_URL }}`` isn't working in your template, you're probably not
173using :class:`~django.template.RequestContext` when rendering the template.
174
175As a brief refresher, context processors add variables into the contexts of
176every template. However, context processors require that you use
177:class:`~django.template.RequestContext` when rendering templates. This happens
178automatically if you're using a :doc:`generic view </ref/class-based-views>`,
179but in views written by hand you'll need to explicitly use ``RequestContext``
180To see how that works, and to read more details, check out
181:ref:`subclassing-context-requestcontext`.
182
183With a template tag
184-------------------
185
186The second option is the :ttag:`get_static_prefix` template tag. You can
187use this if you're not using :class:`~django.template.RequestContext`, or if you
188need more control over exactly where and how :setting:`STATIC_URL` is
189injected into the template. Here's an example:
190
191.. code-block:: html+django
192
193    {% load static %}
194    <img src="{% get_static_prefix %}images/hi.jpg" />
195
196There's also a second form you can use to avoid extra processing if you need the
197value multiple times:
198
199.. code-block:: html+django
200
201    {% load static %}
202    {% get_static_prefix as STATIC_PREFIX %}
203
204    <img src="{{ STATIC_PREFIX }}images/hi.jpg" />
205    <img src="{{ STATIC_PREFIX }}images/hi2.jpg" />
206
207.. _staticfiles-development:
208
209Serving static files in development
210===================================
211
212The static files tools are mostly designed to help with getting static files
213successfully deployed into production. This usually means a separate,
214dedicated static file server, which is a lot of overhead to mess with when
215developing locally. Thus, the ``staticfiles`` app ships with a
216**quick and dirty helper view** that you can use to serve files locally in
217development.
218
219This view is automatically enabled and will serve your static files at
220:setting:`STATIC_URL` when you use the built-in
221:ref:`runserver<staticfiles-runserver>` management command.
222
223To enable this view if you are using some other server for local development,
224you'll add a couple of lines to your URLconf. The first line goes at the top
225of the file, and the last line at the bottom::
226
227    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
228
229    # ... the rest of your URLconf goes here ...
230
231    urlpatterns += staticfiles_urlpatterns()
232
233This will inspect your :setting:`STATIC_URL` setting and wire up the view
234to serve static files accordingly. Don't forget to set the
235:setting:`STATICFILES_DIRS` setting appropriately to let
236``django.contrib.staticfiles`` know where to look for files additionally to
237files in app directories.
238
239.. warning::
240
241    This will only work if :setting:`DEBUG` is ``True``.
242
243    That's because this view is **grossly inefficient** and probably
244    **insecure**. This is only intended for local development, and should
245    **never be used in production**.
246
247    Additionally, when using ``staticfiles_urlpatterns`` your
248    :setting:`STATIC_URL` setting can't be empty or a full URL, such as
249    ``http://static.example.com/``.
250
251For a few more details on how the ``staticfiles`` can be used during
252development, see :ref:`staticfiles-development-view`.
253
254.. _staticfiles-other-directories:
255
256Serving other directories
257-------------------------
258
259.. currentmodule:: django.views.static
260.. function:: serve(request, path, document_root, show_indexes=False)
261
262There may be files other than your project's static assets that, for
263convenience, you'd like to have Django serve for you in local development.
264The :func:`~django.views.static.serve` view can be used to serve any directory
265you give it. (Again, this view is **not** hardened for production
266use, and should be used only as a development aid; you should serve these files
267in production using a real front-end webserver).
268
269The most likely example is user-uploaded content in :setting:`MEDIA_ROOT`.
270``staticfiles`` is intended for static assets and has no built-in handling
271for user-uploaded files, but you can have Django serve your
272:setting:`MEDIA_ROOT` by appending something like this to your URLconf::
273
274    from django.conf import settings
275
276    # ... the rest of your URLconf goes here ...
277
278    if settings.DEBUG:
279        urlpatterns += patterns('',
280            url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
281                'document_root': settings.MEDIA_ROOT,
282            }),
283       )
284
285Note, the snippet assumes your :setting:`MEDIA_URL` has a value of
286``'/media/'``. This will call the :func:`~django.views.static.serve` view,
287passing in the path from the URLconf and the (required) ``document_root``
288parameter.
289
290.. currentmodule:: django.conf.urls.static
291.. function:: static(prefix, view='django.views.static.serve', **kwargs)
292
293Since it can become a bit cumbersome to define this URL pattern, Django
294ships with a small URL helper function
295:func:`~django.conf.urls.static.static` that takes as parameters the prefix
296such as :setting:`MEDIA_URL` and a dotted path to a view, such as
297``'django.views.static.serve'``. Any other function parameter will be
298transparently passed to the view.
299
300An example for serving :setting:`MEDIA_URL` (``'/media/'``) during
301development::
302
303    from django.conf import settings
304    from django.conf.urls.static import static
305
306    urlpatterns = patterns('',
307        # ... the rest of your URLconf goes here ...
308    ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
309
310.. note::
311
312    This helper function will only be operational in debug mode and if
313    the given prefix is local (e.g. ``/static/``) and not a URL (e.g.
314    ``http://static.example.com/``).
315
316.. _staticfiles-production:
317
318Serving static files in production
319==================================
320
321The basic outline of putting static files into production is simple: run the
322:djadmin:`collectstatic` command when static files change, then arrange for
323the collected static files directory (:setting:`STATIC_ROOT`) to be moved to
324the static file server and served.
325
326Of course, as with all deployment tasks, the devil's in the details. Every
327production setup will be a bit different, so you'll need to adapt the basic
328outline to fit your needs. Below are a few common patterns that might help.
329
330Serving the app and your static files from the same server
331----------------------------------------------------------
332
333If you want to serve your static files from the same server that's already
334serving your site, the basic outline gets modified to look something like:
335
336    * Push your code up to the deployment server.
337    * On the server, run :djadmin:`collectstatic` to copy all the static files
338      into :setting:`STATIC_ROOT`.
339    * Point your web server at :setting:`STATIC_ROOT`. For example, here's
340      :ref:`how to do this under Apache and mod_wsgi <serving-files>`.
341
342You'll probably want to automate this process, especially if you've got
343multiple web servers. There's any number of ways to do this automation, but
344one option that many Django developers enjoy is `Fabric`__.
345
346__ http://fabfile.org/
347
348Below, and in the following sections, we'll show off a few example fabfiles
349(i.e. Fabric scripts) that automate these file deployment options. The syntax
350of a fabfile is fairly straightforward but won't be covered here; consult
351`Fabric's documentation`__, for a complete explanation of the syntax..
352
353__ http://docs.fabfile.org/
354
355So, a fabfile to deploy static files to a couple of web servers might look
356something like::
357
358    from fabric.api import *
359
360    # Hosts to deploy onto
361    env.hosts = ['www1.example.com', 'www2.example.com']
362
363    # Where your project code lives on the server
364    env.project_root = '/home/www/myproject'
365
366    def deploy_static():
367        with cd(env.project_root):
368            run('./manage.py collectstatic -v0 --noinput')
369
370Serving static files from a dedicated server
371--------------------------------------------
372
373Most larger Django apps use a separate Web server -- i.e., one that's not also
374running Django -- for serving static files. This server often runs a different
375type of web server -- faster but less full-featured. Some good choices are:
376
377    * lighttpd_
378    * Nginx_
379    * TUX_
380    * Cherokee_
381    * A stripped-down version of Apache_
382
383.. _lighttpd: http://www.lighttpd.net/
384.. _Nginx: http://wiki.nginx.org/Main
385.. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
386.. _Apache: http://httpd.apache.org/
387.. _Cherokee: http://www.cherokee-project.com/
388
389Configuring these servers is out of scope of this document; check each
390server's respective documentation for instructions.
391
392Since your static file server won't be running Django, you'll need to modify
393the deployment strategy to look something like:
394
395    * When your static files change, run :djadmin:`collectstatic` locally.
396    * Push your local :setting:`STATIC_ROOT` up to the static file server
397      into the directory that's being served. ``rsync`` is a good
398      choice for this step since it only needs to transfer the
399      bits of static files that have changed.
400
401Here's how this might look in a fabfile::
402
403    from fabric.api import *
404    from fabric.contrib import project
405
406    # Where the static files get collected locally
407    env.local_static_root = '/tmp/static'
408
409    # Where the static files should go remotely
410    env.remote_static_root = '/home/www/static.example.com'
411
412    @roles('static')
413    def deploy_static():
414        local('./manage.py collectstatic')
415        project.rysnc_project(
416            remote_dir = env.remote_static_root,
417            local_dir = env.local_static_root,
418            delete = True
419        )
420
421.. _staticfiles-from-cdn:
422
423Serving static files from a cloud service or CDN
424------------------------------------------------
425
426Another common tactic is to serve static files from a cloud storage provider
427like Amazon's S3__ and/or a CDN (content delivery network). This lets you
428ignore the problems of serving static files, and can often make for
429faster-loading webpages (especially when using a CDN).
430
431When using these services, the basic workflow would look a bit like the above,
432except that instead of using ``rsync`` to transfer your static files to the
433server you'd need to transfer the static files to the storage provider or CDN.
434
435There's any number of ways you might do this, but if the provider has an API a
436:doc:`custom file storage backend </howto/custom-file-storage>` will make the
437process incredibly simple. If you've written or are using a 3rd party custom
438storage backend, you can tell :djadmin:`collectstatic` to use it by setting
439:setting:`STATICFILES_STORAGE` to the storage engine.
440
441For example, if you've written an S3 storage backend in
442``myproject.storage.S3Storage`` you could use it with::
443
444    STATICFILES_STORAGE = 'myproject.storage.S3Storage'
445
446Once that's done, all you have to do is run :djadmin:`collectstatic` and your
447static files would be pushed through your storage package up to S3. If you
448later needed to switch to a different storage provider, it could be as simple
449as changing your :setting:`STATICFILES_STORAGE` setting.
450
451For details on how you'd write one of these backends,
452:doc:`/howto/custom-file-storage`.
453
454.. seealso::
455
456    The `django-storages`__ project is a 3rd party app that provides many
457    storage backends for many common file storage APIs (including `S3`__).
458
459__ http://s3.amazonaws.com/
460__ http://code.welldev.org/django-storages/
461__ http://code.welldev.org/django-storages/wiki/S3Storage
462
463Upgrading from ``django-staticfiles``
464=====================================
465
466``django.contrib.staticfiles`` began its life as `django-staticfiles`_. If
467you're upgrading from `django-staticfiles`_ older than 1.0 (e.g. 0.3.4) to
468``django.contrib.staticfiles``, you'll need to make a few changes:
469
470    * Application files should now live in a ``static`` directory in each app
471      (`django-staticfiles`_ used the name ``media``, which was slightly
472      confusing).
473
474    * The management commands ``build_static`` and ``resolve_static`` are now
475      called :djadmin:`collectstatic` and :djadmin:`findstatic`.
476
477    * The settings ``STATICFILES_PREPEND_LABEL_APPS``,
478      ``STATICFILES_MEDIA_DIRNAMES`` and ``STATICFILES_EXCLUDED_APPS`` were
479      removed.
480
481    * The setting ``STATICFILES_RESOLVERS`` was removed, and replaced by the
482      new :setting:`STATICFILES_FINDERS`.
483
484    * The default for :setting:`STATICFILES_STORAGE` was renamed from
485      ``staticfiles.storage.StaticFileStorage`` to
486      ``staticfiles.storage.StaticFilesStorage``
487
488    * If using :ref:`runserver<staticfiles-runserver>` for local development
489      (and the :setting:`DEBUG` setting is ``True``), you no longer need to add
490      anything to your URLconf for serving static files in development.
491
492Learn more
493==========
494
495This document has covered the basics and some common usage patterns. For
496complete details on all the settings, commands, template tags, and other pieces
497include in ``django.contrib.staticfiles``, see :doc:`the staticfiles reference
498</ref/contrib/staticfiles>`.