Ticket #15983: static-files.txt

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