index.txt 20 KB

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