7 Django developers mostly concern themselves with the dynamic parts of web
8 applications -- the views and templates that render anew for each request. But
9 web applications have other parts: the static files (images, CSS,
10 Javascript, etc.) that are needed to render a complete web page.
12 For small projects, this isn't a big deal, because you can just keep the
13 static files somewhere your web server can find it. However, in bigger
14 projects -- especially those comprised of multiple apps -- dealing with the
15 multiple sets of static files provided by each application starts to get
18 That's what ``django.contrib.staticfiles`` is for: it collects static files
19 from each of your applications (and any other places you specify) into a
20 single location that can easily be served in production.
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.
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.
32 .. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
34 Using ``django.contrib.staticfiles``
35 ====================================
40 1. Put your static files somewhere that ``staticfiles`` will find them.
42 By default, this means within ``static/`` subdirectories of apps in your
43 :setting:`INSTALLED_APPS`.
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.
51 Additionally, see the documentation for the :setting:`STATICFILES_FINDERS`
52 setting for details on how ``staticfiles`` finds your files.
54 2. Make sure that ``django.contrib.staticfiles`` is included in your
55 :setting:`INSTALLED_APPS`.
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`
65 3. 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
69 .. code-block:: html+django
71 <img src="{{ STATIC_URL }}images/hi.jpg" />
73 See :ref:`staticfiles-in-templates` for more details, **including** an
74 alternate method using a template tag.
76 Deploying static files in a nutshell
77 ------------------------------------
79 When you're ready to move out of local development and deploy your project:
81 1. 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).
84 2. 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::
88 STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"
90 3. Run the :djadmin:`collectstatic` management command::
92 ./manage.py collectstatic
94 This'll churn through your static file storage and copy them into the
95 directory given by :setting:`STATIC_ROOT`.
97 4. Deploy those files by configuring your webserver of choice to serve the
98 files in :setting:`STATIC_ROOT` at :setting:`STATIC_URL`.
100 :ref:`staticfiles-production` covers some common deployment strategies
103 Those are the **basics**. For more details on common configuration options,
104 read on; for a detailed reference of the settings, commands, and other bits
105 included with the framework see
106 :doc:`the staticfiles reference </ref/contrib/staticfiles>`.
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.
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`.
124 .. _staticfiles-in-templates:
126 Referring to static files in templates
127 ======================================
129 At some point, you'll probably need to link to static files in your templates.
130 You could, of course, simply hardcode the path to you assets in the templates:
134 <img src="http://static.example.com/static/myimage.jpg" />
136 Of course, there are some serious problems with this: it doesn't work well in
137 development, and it makes it *very* hard to change where you've deployed your
138 static files. If, for example, you wanted to switch to using a content
139 delivery network (CDN), then you'd need to change more or less every single
142 A far better way is to use the value of the :setting:`STATIC_URL` setting
143 directly in your templates. This means that a switch of static files servers
144 only requires changing that single value. Much better!
146 Django includes multiple built-in ways of using this setting in your
147 templates: a context processor and a template tag.
149 With a context processor
150 ------------------------
152 The 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
155 editing that setting by hand it should look something like::
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',
166 Once that's done, you can refer to :setting:`STATIC_URL` in your templates:
168 .. code-block:: html+django
170 <img src="{{ STATIC_URL }}images/hi.jpg" />
172 If ``{{ STATIC_URL }}`` isn't working in your template, you're probably not
173 using :class:`~django.template.RequestContext` when rendering the template.
175 As a brief refresher, context processors add variables into the contexts of
176 every template. However, context processors require that you use
177 :class:`~django.template.RequestContext` when rendering templates. This happens
178 automatically if you're using a :doc:`generic view </ref/class-based-views>`,
179 but in views written by hand you'll need to explicitly use ``RequestContext``
180 To see how that works, and to read more details, check out
181 :ref:`subclassing-context-requestcontext`.
183 Another option is the :ttag:`get_static_prefix` template tag that is part of
189 The more powerful tool is the :ttag:`static<staticfiles-static>` template
190 tag. It builds the URL for the given relative path by using the configured
191 :setting:`STATICFILES_STORAGE` storage.
193 .. code-block:: html+django
195 {% load staticfiles %}
196 <img src="{% static "images/hi.jpg" %}" />
198 It is also able to consume standard context variables, e.g. assuming a
199 ``user_stylesheet`` variable is passed to the template:
201 .. code-block:: html+django
203 {% load staticfiles %}
204 <link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen" />
208 There is also a template tag named :ttag:`static` in Django's core set
209 of :ref:`built in template tags<ref-templates-builtins-tags>` which has
210 the same argument signature but only uses `urlparse.urljoin()`_ with the
211 :setting:`STATIC_URL` setting and the given path. This has the
212 disadvantage of not being able to easily switch the storage backend
213 without changing the templates, so in doubt use the ``staticfiles``
214 :ttag:`static<staticfiles-static>`
217 .. _`urlparse.urljoin()`: http://docs.python.org/library/urlparse.html#urlparse.urljoin
219 .. _staticfiles-development:
221 Serving static files in development
222 ===================================
224 The static files tools are mostly designed to help with getting static files
225 successfully deployed into production. This usually means a separate,
226 dedicated static file server, which is a lot of overhead to mess with when
227 developing locally. Thus, the ``staticfiles`` app ships with a
228 **quick and dirty helper view** that you can use to serve files locally in
231 This view is automatically enabled and will serve your static files at
232 :setting:`STATIC_URL` when you use the built-in
233 :ref:`runserver<staticfiles-runserver>` management command.
235 To enable this view if you are using some other server for local development,
236 you'll add a couple of lines to your URLconf. The first line goes at the top
237 of the file, and the last line at the bottom::
239 from django.contrib.staticfiles.urls import staticfiles_urlpatterns
241 # ... the rest of your URLconf goes here ...
243 urlpatterns += staticfiles_urlpatterns()
245 This will inspect your :setting:`STATIC_URL` setting and wire up the view
246 to serve static files accordingly. Don't forget to set the
247 :setting:`STATICFILES_DIRS` setting appropriately to let
248 ``django.contrib.staticfiles`` know where to look for files additionally to
249 files in app directories.
253 This will only work if :setting:`DEBUG` is ``True``.
255 That's because this view is **grossly inefficient** and probably
256 **insecure**. This is only intended for local development, and should
257 **never be used in production**.
259 Additionally, when using ``staticfiles_urlpatterns`` your
260 :setting:`STATIC_URL` setting can't be empty or a full URL, such as
261 ``http://static.example.com/``.
263 For a few more details on how the ``staticfiles`` can be used during
264 development, see :ref:`staticfiles-development-view`.
266 .. _staticfiles-other-directories:
268 Serving other directories
269 -------------------------
271 .. currentmodule:: django.views.static
272 .. function:: serve(request, path, document_root, show_indexes=False)
274 There may be files other than your project's static assets that, for
275 convenience, you'd like to have Django serve for you in local development.
276 The :func:`~django.views.static.serve` view can be used to serve any directory
277 you give it. (Again, this view is **not** hardened for production
278 use, and should be used only as a development aid; you should serve these files
279 in production using a real front-end webserver).
281 The most likely example is user-uploaded content in :setting:`MEDIA_ROOT`.
282 ``staticfiles`` is intended for static assets and has no built-in handling
283 for user-uploaded files, but you can have Django serve your
284 :setting:`MEDIA_ROOT` by appending something like this to your URLconf::
286 from django.conf import settings
288 # ... the rest of your URLconf goes here ...
291 urlpatterns += patterns('',
292 url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
293 'document_root': settings.MEDIA_ROOT,
297 Note, the snippet assumes your :setting:`MEDIA_URL` has a value of
298 ``'/media/'``. This will call the :func:`~django.views.static.serve` view,
299 passing in the path from the URLconf and the (required) ``document_root``
302 .. currentmodule:: django.conf.urls.static
303 .. function:: static(prefix, view='django.views.static.serve', **kwargs)
305 Since it can become a bit cumbersome to define this URL pattern, Django
306 ships with a small URL helper function
307 :func:`~django.conf.urls.static.static` that takes as parameters the prefix
308 such as :setting:`MEDIA_URL` and a dotted path to a view, such as
309 ``'django.views.static.serve'``. Any other function parameter will be
310 transparently passed to the view.
312 An example for serving :setting:`MEDIA_URL` (``'/media/'``) during
315 from django.conf import settings
316 from django.conf.urls.static import static
318 urlpatterns = patterns('',
319 # ... the rest of your URLconf goes here ...
320 ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
324 This helper function will only be operational in debug mode and if
325 the given prefix is local (e.g. ``/static/``) and not a URL (e.g.
326 ``http://static.example.com/``).
328 .. _staticfiles-production:
330 Serving static files in production
331 ==================================
333 The basic outline of putting static files into production is simple: run the
334 :djadmin:`collectstatic` command when static files change, then arrange for
335 the collected static files directory (:setting:`STATIC_ROOT`) to be moved to
336 the static file server and served.
338 Of course, as with all deployment tasks, the devil's in the details. Every
339 production setup will be a bit different, so you'll need to adapt the basic
340 outline to fit your needs. Below are a few common patterns that might help.
342 Serving the app and your static files from the same server
343 ----------------------------------------------------------
345 If you want to serve your static files from the same server that's already
346 serving your site, the basic outline gets modified to look something like:
348 * Push your code up to the deployment server.
349 * On the server, run :djadmin:`collectstatic` to copy all the static files
350 into :setting:`STATIC_ROOT`.
351 * Point your web server at :setting:`STATIC_ROOT`. For example, here's
352 :ref:`how to do this under Apache and mod_wsgi <serving-files>`.
354 You'll probably want to automate this process, especially if you've got
355 multiple web servers. There's any number of ways to do this automation, but
356 one option that many Django developers enjoy is `Fabric`__.
358 __ http://fabfile.org/
360 Below, and in the following sections, we'll show off a few example fabfiles
361 (i.e. Fabric scripts) that automate these file deployment options. The syntax
362 of a fabfile is fairly straightforward but won't be covered here; consult
363 `Fabric's documentation`__, for a complete explanation of the syntax..
365 __ http://docs.fabfile.org/
367 So, a fabfile to deploy static files to a couple of web servers might look
370 from fabric.api import *
372 # Hosts to deploy onto
373 env.hosts = ['www1.example.com', 'www2.example.com']
375 # Where your project code lives on the server
376 env.project_root = '/home/www/myproject'
379 with cd(env.project_root):
380 run('./manage.py collectstatic -v0 --noinput')
382 Serving static files from a dedicated server
383 --------------------------------------------
385 Most larger Django apps use a separate Web server -- i.e., one that's not also
386 running Django -- for serving static files. This server often runs a different
387 type of web server -- faster but less full-featured. Some good choices are:
393 * A stripped-down version of Apache_
395 .. _lighttpd: http://www.lighttpd.net/
396 .. _Nginx: http://wiki.nginx.org/Main
397 .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
398 .. _Apache: http://httpd.apache.org/
399 .. _Cherokee: http://www.cherokee-project.com/
401 Configuring these servers is out of scope of this document; check each
402 server's respective documentation for instructions.
404 Since your static file server won't be running Django, you'll need to modify
405 the deployment strategy to look something like:
407 * When your static files change, run :djadmin:`collectstatic` locally.
408 * Push your local :setting:`STATIC_ROOT` up to the static file server
409 into the directory that's being served. ``rsync`` is a good
410 choice for this step since it only needs to transfer the
411 bits of static files that have changed.
413 Here's how this might look in a fabfile::
415 from fabric.api import *
416 from fabric.contrib import project
418 # Where the static files get collected locally
419 env.local_static_root = '/tmp/static'
421 # Where the static files should go remotely
422 env.remote_static_root = '/home/www/static.example.com'
426 local('./manage.py collectstatic')
427 project.rysnc_project(
428 remote_dir = env.remote_static_root,
429 local_dir = env.local_static_root,
433 .. _staticfiles-from-cdn:
435 Serving static files from a cloud service or CDN
436 ------------------------------------------------
438 Another common tactic is to serve static files from a cloud storage provider
439 like Amazon's S3__ and/or a CDN (content delivery network). This lets you
440 ignore the problems of serving static files, and can often make for
441 faster-loading webpages (especially when using a CDN).
443 When using these services, the basic workflow would look a bit like the above,
444 except that instead of using ``rsync`` to transfer your static files to the
445 server you'd need to transfer the static files to the storage provider or CDN.
447 There's any number of ways you might do this, but if the provider has an API a
448 :doc:`custom file storage backend </howto/custom-file-storage>` will make the
449 process incredibly simple. If you've written or are using a 3rd party custom
450 storage backend, you can tell :djadmin:`collectstatic` to use it by setting
451 :setting:`STATICFILES_STORAGE` to the storage engine.
453 For example, if you've written an S3 storage backend in
454 ``myproject.storage.S3Storage`` you could use it with::
456 STATICFILES_STORAGE = 'myproject.storage.S3Storage'
458 Once that's done, all you have to do is run :djadmin:`collectstatic` and your
459 static files would be pushed through your storage package up to S3. If you
460 later needed to switch to a different storage provider, it could be as simple
461 as changing your :setting:`STATICFILES_STORAGE` setting.
463 For details on how you'd write one of these backends,
464 :doc:`/howto/custom-file-storage`.
468 The `django-storages`__ project is a 3rd party app that provides many
469 storage backends for many common file storage APIs (including `S3`__).
471 __ http://s3.amazonaws.com/
472 __ http://code.larlet.fr/django-storages/
473 __ http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
475 Upgrading from ``django-staticfiles``
476 =====================================
478 ``django.contrib.staticfiles`` began its life as `django-staticfiles`_. If
479 you're upgrading from `django-staticfiles`_ older than 1.0 (e.g. 0.3.4) to
480 ``django.contrib.staticfiles``, you'll need to make a few changes:
482 * Application files should now live in a ``static`` directory in each app
483 (`django-staticfiles`_ used the name ``media``, which was slightly
486 * The management commands ``build_static`` and ``resolve_static`` are now
487 called :djadmin:`collectstatic` and :djadmin:`findstatic`.
489 * The settings ``STATICFILES_PREPEND_LABEL_APPS``,
490 ``STATICFILES_MEDIA_DIRNAMES`` and ``STATICFILES_EXCLUDED_APPS`` were
493 * The setting ``STATICFILES_RESOLVERS`` was removed, and replaced by the
494 new :setting:`STATICFILES_FINDERS`.
496 * The default for :setting:`STATICFILES_STORAGE` was renamed from
497 ``staticfiles.storage.StaticFileStorage`` to
498 ``staticfiles.storage.StaticFilesStorage``
500 * If using :ref:`runserver<staticfiles-runserver>` for local development
501 (and the :setting:`DEBUG` setting is ``True``), you no longer need to add
502 anything to your URLconf for serving static files in development.
507 This document has covered the basics and some common usage patterns. For
508 complete details on all the settings, commands, template tags, and other pieces
509 include in ``django.contrib.staticfiles``, see :doc:`the staticfiles reference
510 </ref/contrib/staticfiles>`.