PageRenderTime 40ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

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