api.txt 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. ====================================================
  2. The Django template language: for Python programmers
  3. ====================================================
  4. .. currentmodule:: django.template
  5. This document explains the Django template system from a technical
  6. perspective -- how it works and how to extend it. If you're just looking for
  7. reference on the language syntax, see :doc:`/ref/templates/language`.
  8. It assumes an understanding of templates, contexts, variables, tags, and
  9. rendering. Start with the :ref:`introduction to the Django template language
  10. <template-language-intro>` if you aren't familiar with these concepts.
  11. Overview
  12. ========
  13. Using the template system in Python is a three-step process:
  14. 1. You configure an :class:`Engine`.
  15. 2. You compile template code into a :class:`Template`.
  16. 3. You render the template with a :class:`Context`.
  17. Django projects generally rely on the :ref:`high level, backend agnostic APIs
  18. <template-engines>` for each of these steps instead of the template system's
  19. lower level APIs:
  20. 1. For each :class:`~django.template.backends.django.DjangoTemplates` backend
  21. in the :setting:`TEMPLATES` setting, Django instantiates an
  22. :class:`Engine`. :class:`~django.template.backends.django.DjangoTemplates`
  23. wraps :class:`Engine` and adapts it to the common template backend API.
  24. 2. The :mod:`django.template.loader` module provides functions such as
  25. :func:`~django.template.loader.get_template` for loading templates. They
  26. return a ``django.template.backends.django.Template`` which wraps the
  27. actual :class:`django.template.Template`.
  28. 3. The ``Template`` obtained in the previous step has a
  29. :meth:`~django.template.backends.base.Template.render` method which
  30. marshals a context and possibly a request into a :class:`Context` and
  31. delegates the rendering to the underlying :class:`Template`.
  32. Configuring an engine
  33. =====================
  34. .. class:: Engine([dirs][, app_dirs][, allowed_include_roots][, context_processors][, debug][, loaders][, string_if_invalid][, file_charset][, libraries][, builtins])
  35. .. versionadded:: 1.8
  36. When instantiating an ``Engine`` all arguments must be passed as keyword
  37. arguments:
  38. * ``dirs`` is a list of directories where the engine should look for
  39. template source files. It is used to configure
  40. :class:`filesystem.Loader <django.template.loaders.filesystem.Loader>`.
  41. It defaults to an empty list.
  42. * ``app_dirs`` only affects the default value of ``loaders``. See below.
  43. It defaults to ``False``.
  44. * ``allowed_include_roots`` is a list of strings representing allowed
  45. prefixes for the ``{% ssi %}`` template tag. This is a security measure,
  46. so that template authors can't access files that they shouldn't be
  47. accessing.
  48. For example, if ``'allowed_include_roots'`` is ``['/home/html',
  49. '/var/www']``, then ``{% ssi /home/html/foo.txt %}`` would work, but ``{%
  50. ssi /etc/passwd %}`` wouldn't.
  51. It defaults to an empty list.
  52. .. deprecated:: 1.8
  53. ``allowed_include_roots`` is deprecated.
  54. * ``context_processors`` is a list of dotted Python paths to callables
  55. that are used to populate the context when a template is rendered with a
  56. request. These callables take a request object as their argument and
  57. return a :class:`dict` of items to be merged into the context.
  58. It defaults to an empty list.
  59. See :class:`~django.template.RequestContext` for more information.
  60. * ``debug`` is a boolean that turns on/off template debug mode. If it is
  61. ``True``, the template engine will store additional debug information
  62. which can be used to display a detailed report for any exception raised
  63. during template rendering.
  64. It defaults to ``False``.
  65. * ``loaders`` is a list of template loader classes, specified as strings.
  66. Each ``Loader`` class knows how to import templates from a particular
  67. source. Optionally, a tuple can be used instead of a string. The first
  68. item in the tuple should be the ``Loader`` class name, subsequent items
  69. are passed to the ``Loader`` during initialization.
  70. It defaults to a list containing:
  71. * ``'django.template.loaders.filesystem.Loader'``
  72. * ``'django.template.loaders.app_directories.Loader'`` if and only if
  73. ``app_dirs`` is ``True``.
  74. See :ref:`template-loaders` for details.
  75. * ``string_if_invalid`` is the output, as a string, that the template
  76. system should use for invalid (e.g. misspelled) variables.
  77. It defaults to the empty string.
  78. See :ref:`invalid-template-variables` for details.
  79. * ``file_charset`` is the charset used to read template files on disk.
  80. It defaults to ``'utf-8'``.
  81. * ``'libraries'``: A dictionary of labels and dotted Python paths of template
  82. tag modules to register with the template engine. This is used to add new
  83. libraries or provide alternate labels for existing ones. For example::
  84. Engine(
  85. libraries={
  86. 'myapp_tags': 'path.to.myapp.tags',
  87. 'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
  88. },
  89. )
  90. Libraries can be loaded by passing the corresponding dictionary key to
  91. the :ttag:`{% load %}<load>` tag.
  92. * ``'builtins'``: A list of dotted Python paths of template tag modules to
  93. add to :doc:`built-ins </ref/templates/builtins>`. For example::
  94. Engine(
  95. builtins=['myapp.builtins'],
  96. )
  97. Tags and filters from built-in libraries can be used without first calling
  98. the :ttag:`{% load %}<load>` tag.
  99. .. versionadded:: 1.9
  100. The ``libraries`` and ``builtins`` arguments were added.
  101. .. staticmethod:: Engine.get_default()
  102. When a Django project configures one and only one
  103. :class:`~django.template.backends.django.DjangoTemplates` engine, this
  104. method returns the underlying :class:`Engine`. In other circumstances it
  105. will raise :exc:`~django.core.exceptions.ImproperlyConfigured`.
  106. It's required for preserving APIs that rely on a globally available,
  107. implicitly configured engine. Any other use is strongly discouraged.
  108. .. method:: Engine.from_string(template_code)
  109. Compiles the given template code and returns a :class:`Template` object.
  110. .. method:: Engine.get_template(template_name)
  111. Loads a template with the given name, compiles it and returns a
  112. :class:`Template` object.
  113. .. method:: Engine.select_template(self, template_name_list)
  114. Like :meth:`~Engine.get_template`, except it takes a list of names
  115. and returns the first template that was found.
  116. Loading a template
  117. ==================
  118. The recommended way to create a :class:`Template` is by calling the factory
  119. methods of the :class:`Engine`: :meth:`~Engine.get_template`,
  120. :meth:`~Engine.select_template` and :meth:`~Engine.from_string`.
  121. In a Django project where the :setting:`TEMPLATES` setting defines exactly one
  122. :class:`~django.template.backends.django.DjangoTemplates` engine, it's
  123. possible to instantiate a :class:`Template` directly.
  124. .. class:: Template
  125. This class lives at ``django.template.Template``. The constructor takes
  126. one argument — the raw template code::
  127. from django.template import Template
  128. template = Template("My name is {{ my_name }}.")
  129. .. admonition:: Behind the scenes
  130. The system only parses your raw template code once -- when you create the
  131. ``Template`` object. From then on, it's stored internally as a tree
  132. structure for performance.
  133. Even the parsing itself is quite fast. Most of the parsing happens via a
  134. single call to a single, short, regular expression.
  135. Rendering a context
  136. ===================
  137. Once you have a compiled :class:`Template` object, you can render a context
  138. with it. You can reuse the same template to render it several times with
  139. different contexts.
  140. .. class:: Context([dict_][, current_app])
  141. This class lives at ``django.template.Context``. The constructor takes
  142. two optional arguments:
  143. * A dictionary mapping variable names to variable values.
  144. * The name of the current application. This application name is used
  145. to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
  146. If you're not using namespaced URLs, you can ignore this argument.
  147. .. deprecated:: 1.8
  148. The ``current_app`` argument is deprecated. If you need it, you must
  149. now use a :class:`RequestContext` instead of a :class:`Context`.
  150. For details, see :ref:`playing-with-context` below.
  151. .. method:: Template.render(context)
  152. Call the :class:`Template` object's ``render()`` method with a
  153. :class:`Context` to "fill" the template::
  154. >>> from django.template import Context, Template
  155. >>> template = Template("My name is {{ my_name }}.")
  156. >>> context = Context({"my_name": "Adrian"})
  157. >>> template.render(context)
  158. "My name is Adrian."
  159. >>> context = Context({"my_name": "Dolores"})
  160. >>> template.render(context)
  161. "My name is Dolores."
  162. Variables and lookups
  163. ---------------------
  164. Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
  165. (but they must not start with an underscore) or a dot.
  166. Dots have a special meaning in template rendering. A dot in a variable name
  167. signifies a **lookup**. Specifically, when the template system encounters a
  168. dot in a variable name, it tries the following lookups, in this order:
  169. * Dictionary lookup. Example: ``foo["bar"]``
  170. * Attribute lookup. Example: ``foo.bar``
  171. * List-index lookup. Example: ``foo[bar]``
  172. Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
  173. interpreted as a literal string and not using the value of the variable "bar",
  174. if one exists in the template context.
  175. The template system uses the first lookup type that works. It's short-circuit
  176. logic. Here are a few examples::
  177. >>> from django.template import Context, Template
  178. >>> t = Template("My name is {{ person.first_name }}.")
  179. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  180. >>> t.render(Context(d))
  181. "My name is Joe."
  182. >>> class PersonClass: pass
  183. >>> p = PersonClass()
  184. >>> p.first_name = "Ron"
  185. >>> p.last_name = "Nasty"
  186. >>> t.render(Context({"person": p}))
  187. "My name is Ron."
  188. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  189. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  190. >>> t.render(c)
  191. "The first stooge in the list is Larry."
  192. If any part of the variable is callable, the template system will try calling
  193. it. Example::
  194. >>> class PersonClass2:
  195. ... def name(self):
  196. ... return "Samantha"
  197. >>> t = Template("My name is {{ person.name }}.")
  198. >>> t.render(Context({"person": PersonClass2}))
  199. "My name is Samantha."
  200. Callable variables are slightly more complex than variables which only require
  201. straight lookups. Here are some things to keep in mind:
  202. * If the variable raises an exception when called, the exception will be
  203. propagated, unless the exception has an attribute
  204. ``silent_variable_failure`` whose value is ``True``. If the exception
  205. *does* have a ``silent_variable_failure`` attribute whose value is
  206. ``True``, the variable will render as the value of the engine's
  207. ``string_if_invalid`` configuration option (an empty string, by default).
  208. Example::
  209. >>> t = Template("My name is {{ person.first_name }}.")
  210. >>> class PersonClass3:
  211. ... def first_name(self):
  212. ... raise AssertionError("foo")
  213. >>> p = PersonClass3()
  214. >>> t.render(Context({"person": p}))
  215. Traceback (most recent call last):
  216. ...
  217. AssertionError: foo
  218. >>> class SilentAssertionError(Exception):
  219. ... silent_variable_failure = True
  220. >>> class PersonClass4:
  221. ... def first_name(self):
  222. ... raise SilentAssertionError
  223. >>> p = PersonClass4()
  224. >>> t.render(Context({"person": p}))
  225. "My name is ."
  226. Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the
  227. base class for all Django database API ``DoesNotExist`` exceptions, has
  228. ``silent_variable_failure = True``. So if you're using Django templates
  229. with Django model objects, any ``DoesNotExist`` exception will fail
  230. silently.
  231. * A variable can only be called if it has no required arguments. Otherwise,
  232. the system will return the value of the engine's ``string_if_invalid``
  233. option.
  234. .. _alters-data-description:
  235. * Obviously, there can be side effects when calling some variables, and
  236. it'd be either foolish or a security hole to allow the template system
  237. to access them.
  238. A good example is the :meth:`~django.db.models.Model.delete` method on
  239. each Django model object. The template system shouldn't be allowed to do
  240. something like this::
  241. I will now delete this valuable data. {{ data.delete }}
  242. To prevent this, set an ``alters_data`` attribute on the callable
  243. variable. The template system won't call a variable if it has
  244. ``alters_data=True`` set, and will instead replace the variable with
  245. ``string_if_invalid``, unconditionally. The
  246. dynamically-generated :meth:`~django.db.models.Model.delete` and
  247. :meth:`~django.db.models.Model.save` methods on Django model objects get
  248. ``alters_data=True`` automatically. Example::
  249. def sensitive_function(self):
  250. self.database_record.delete()
  251. sensitive_function.alters_data = True
  252. * Occasionally you may want to turn off this feature for other reasons,
  253. and tell the template system to leave a variable uncalled no matter
  254. what. To do so, set a ``do_not_call_in_templates`` attribute on the
  255. callable with the value ``True``. The template system then will act as
  256. if your variable is not callable (allowing you to access attributes of
  257. the callable, for example).
  258. .. _invalid-template-variables:
  259. How invalid variables are handled
  260. ---------------------------------
  261. Generally, if a variable doesn't exist, the template system inserts the value
  262. of the engine's ``string_if_invalid`` configuration option, which is set to
  263. ``''`` (the empty string) by default.
  264. Filters that are applied to an invalid variable will only be applied if
  265. ``string_if_invalid`` is set to ``''`` (the empty string). If
  266. ``string_if_invalid`` is set to any other value, variable filters will be
  267. ignored.
  268. This behavior is slightly different for the ``if``, ``for`` and ``regroup``
  269. template tags. If an invalid variable is provided to one of these template
  270. tags, the variable will be interpreted as ``None``. Filters are always
  271. applied to invalid variables within these template tags.
  272. If ``string_if_invalid`` contains a ``'%s'``, the format marker will be
  273. replaced with the name of the invalid variable.
  274. .. admonition:: For debug purposes only!
  275. While ``string_if_invalid`` can be a useful debugging tool, it is a bad
  276. idea to turn it on as a 'development default'.
  277. Many templates, including those in the Admin site, rely upon the silence
  278. of the template system when a non-existent variable is encountered. If you
  279. assign a value other than ``''`` to ``string_if_invalid``, you will
  280. experience rendering problems with these templates and sites.
  281. Generally, ``string_if_invalid`` should only be enabled in order to debug
  282. a specific template problem, then cleared once debugging is complete.
  283. Built-in variables
  284. ------------------
  285. Every context contains ``True``, ``False`` and ``None``. As you would expect,
  286. these variables resolve to the corresponding Python objects.
  287. Limitations with string literals
  288. --------------------------------
  289. Django's template language has no way to escape the characters used for its own
  290. syntax. For example, the :ttag:`templatetag` tag is required if you need to
  291. output character sequences like ``{%`` and ``%}``.
  292. A similar issue exists if you want to include these sequences in template filter
  293. or tag arguments. For example, when parsing a block tag, Django's template
  294. parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents
  295. the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError``
  296. will be raised for the following expressions::
  297. {% include "template.html" tvar="Some string literal with %} in it." %}
  298. {% with tvar="Some string literal with %} in it." %}{% endwith %}
  299. The same issue can be triggered by using a reserved sequence in filter
  300. arguments::
  301. {{ some.variable|default:"}}" }}
  302. If you need to use strings with these sequences, store them in template
  303. variables or use a custom template tag or filter to workaround the limitation.
  304. .. _playing-with-context:
  305. Playing with Context objects
  306. ============================
  307. Most of the time, you'll instantiate :class:`Context` objects by passing in a
  308. fully-populated dictionary to ``Context()``. But you can add and delete items
  309. from a ``Context`` object once it's been instantiated, too, using standard
  310. dictionary syntax::
  311. >>> from django.template import Context
  312. >>> c = Context({"foo": "bar"})
  313. >>> c['foo']
  314. 'bar'
  315. >>> del c['foo']
  316. >>> c['foo']
  317. Traceback (most recent call last):
  318. ...
  319. KeyError: 'foo'
  320. >>> c['newvariable'] = 'hello'
  321. >>> c['newvariable']
  322. 'hello'
  323. .. method:: Context.get(key, otherwise=None)
  324. Returns the value for ``key`` if ``key`` is in the context, else returns
  325. ``otherwise``.
  326. .. method:: Context.setdefault(key, default=None)
  327. .. versionadded:: 1.9
  328. If ``key`` is in the context, returns its value. Otherwise inserts ``key``
  329. with a value of ``default`` and returns ``default``.
  330. .. method:: Context.pop()
  331. .. method:: Context.push()
  332. .. exception:: ContextPopException
  333. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  334. If you ``pop()`` too much, it'll raise
  335. ``django.template.ContextPopException``::
  336. >>> c = Context()
  337. >>> c['foo'] = 'first level'
  338. >>> c.push()
  339. {}
  340. >>> c['foo'] = 'second level'
  341. >>> c['foo']
  342. 'second level'
  343. >>> c.pop()
  344. {'foo': 'second level'}
  345. >>> c['foo']
  346. 'first level'
  347. >>> c['foo'] = 'overwritten'
  348. >>> c['foo']
  349. 'overwritten'
  350. >>> c.pop()
  351. Traceback (most recent call last):
  352. ...
  353. ContextPopException
  354. You can also use ``push()`` as a context manager to ensure a matching ``pop()``
  355. is called.
  356. >>> c = Context()
  357. >>> c['foo'] = 'first level'
  358. >>> with c.push():
  359. ... c['foo'] = 'second level'
  360. ... c['foo']
  361. 'second level'
  362. >>> c['foo']
  363. 'first level'
  364. All arguments passed to ``push()`` will be passed to the ``dict`` constructor
  365. used to build the new context level.
  366. >>> c = Context()
  367. >>> c['foo'] = 'first level'
  368. >>> with c.push(foo='second level'):
  369. ... c['foo']
  370. 'second level'
  371. >>> c['foo']
  372. 'first level'
  373. .. method:: Context.update(other_dict)
  374. In addition to ``push()`` and ``pop()``, the ``Context``
  375. object also defines an ``update()`` method. This works like ``push()``
  376. but takes a dictionary as an argument and pushes that dictionary onto
  377. the stack instead of an empty one.
  378. >>> c = Context()
  379. >>> c['foo'] = 'first level'
  380. >>> c.update({'foo': 'updated'})
  381. {'foo': 'updated'}
  382. >>> c['foo']
  383. 'updated'
  384. >>> c.pop()
  385. {'foo': 'updated'}
  386. >>> c['foo']
  387. 'first level'
  388. Like ``push()``, you can use ``update()`` as a context manager to ensure a
  389. matching ``pop()`` is called.
  390. >>> c = Context()
  391. >>> c['foo'] = 'first level'
  392. >>> with c.update({'foo': 'second level'}):
  393. ... c['foo']
  394. 'second level'
  395. >>> c['foo']
  396. 'first level'
  397. .. versionadded:: 1.9
  398. The ability to use ``update()`` as a context manager was added.
  399. Using a ``Context`` as a stack comes in handy in :ref:`some custom template
  400. tags <howto-writing-custom-template-tags>`.
  401. .. method:: Context.flatten()
  402. Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary
  403. including builtin variables.
  404. >>> c = Context()
  405. >>> c['foo'] = 'first level'
  406. >>> c.update({'bar': 'second level'})
  407. {'bar': 'second level'}
  408. >>> c.flatten()
  409. {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
  410. A ``flatten()`` method is also internally used to make ``Context`` objects comparable.
  411. >>> c1 = Context()
  412. >>> c1['foo'] = 'first level'
  413. >>> c1['bar'] = 'second level'
  414. >>> c2 = Context()
  415. >>> c2.update({'bar': 'second level', 'foo': 'first level'})
  416. {'foo': 'first level', 'bar': 'second level'}
  417. >>> c1 == c2
  418. True
  419. Result from ``flatten()`` can be useful in unit tests to compare ``Context``
  420. against ``dict``::
  421. class ContextTest(unittest.TestCase):
  422. def test_against_dictionary(self):
  423. c1 = Context()
  424. c1['update'] = 'value'
  425. self.assertEqual(c1.flatten(), {
  426. 'True': True,
  427. 'None': None,
  428. 'False': False,
  429. 'update': 'value',
  430. })
  431. .. _subclassing-context-requestcontext:
  432. Subclassing Context: RequestContext
  433. -----------------------------------
  434. .. class:: RequestContext(request[, dict_][, processors])
  435. Django comes with a special ``Context`` class,
  436. ``django.template.RequestContext``, that acts slightly differently from the
  437. normal ``django.template.Context``. The first difference is that it takes an
  438. :class:`~django.http.HttpRequest` as its first argument. For example::
  439. c = RequestContext(request, {
  440. 'foo': 'bar',
  441. })
  442. The second difference is that it automatically populates the context with a
  443. few variables, according to the engine's ``context_processors`` configuration
  444. option.
  445. The ``context_processors`` option is a list of callables -- called **context
  446. processors** -- that take a request object as their argument and return a
  447. dictionary of items to be merged into the context. In the default generated
  448. settings file, the default template engine contains the following context
  449. processors::
  450. [
  451. 'django.template.context_processors.debug',
  452. 'django.template.context_processors.request',
  453. 'django.contrib.auth.context_processors.auth',
  454. 'django.contrib.messages.context_processors.messages',
  455. ]
  456. .. versionchanged:: 1.8
  457. Built-in template context processors were moved from
  458. ``django.core.context_processors`` to
  459. ``django.template.context_processors`` in Django 1.8.
  460. In addition to these, :class:`RequestContext` always enables
  461. ``'django.template.context_processors.csrf'``. This is a security related
  462. context processor required by the admin and other contrib apps, and, in case
  463. of accidental misconfiguration, it is deliberately hardcoded in and cannot be
  464. turned off in the ``context_processors`` option.
  465. Each processor is applied in order. That means, if one processor adds a
  466. variable to the context and a second processor adds a variable with the same
  467. name, the second will override the first. The default processors are explained
  468. below.
  469. .. admonition:: When context processors are applied
  470. Context processors are applied on top of context data. This means that a
  471. context processor may overwrite variables you've supplied to your
  472. :class:`Context` or :class:`RequestContext`, so take care to avoid
  473. variable names that overlap with those supplied by your context
  474. processors.
  475. If you want context data to take priority over context processors, use the
  476. following pattern::
  477. from django.template import RequestContext
  478. request_context = RequestContext(request)
  479. request_context.push({"my_name": "Adrian"})
  480. Django does this to allow context data to override context processors in
  481. APIs such as :func:`~django.shortcuts.render` and
  482. :class:`~django.template.response.TemplateResponse`.
  483. Also, you can give :class:`RequestContext` a list of additional processors,
  484. using the optional, third positional argument, ``processors``. In this
  485. example, the :class:`RequestContext` instance gets a ``ip_address`` variable::
  486. from django.http import HttpResponse
  487. from django.template import RequestContext
  488. def ip_address_processor(request):
  489. return {'ip_address': request.META['REMOTE_ADDR']}
  490. def some_view(request):
  491. # ...
  492. c = RequestContext(request, {
  493. 'foo': 'bar',
  494. }, [ip_address_processor])
  495. return HttpResponse(t.render(c))
  496. Built-in template context processors
  497. ------------------------------------
  498. .. _context-processors:
  499. Context processors
  500. ------------------
  501. Here's what each of the built-in processors does:
  502. django.contrib.auth.context_processors.auth
  503. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  504. If this processor is enabled, every ``RequestContext`` will contain these
  505. variables:
  506. * ``user`` -- An ``auth.User`` instance representing the currently
  507. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  508. logged in).
  509. * ``perms`` -- An instance of
  510. ``django.contrib.auth.context_processors.PermWrapper``, representing the
  511. permissions that the currently logged-in user has.
  512. .. currentmodule:: django.template.context_processors
  513. django.template.context_processors.debug
  514. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  515. If this processor is enabled, every ``RequestContext`` will contain these two
  516. variables -- but only if your :setting:`DEBUG` setting is set to ``True`` and
  517. the request's IP address (``request.META['REMOTE_ADDR']``) is in the
  518. :setting:`INTERNAL_IPS` setting:
  519. * ``debug`` -- ``True``. You can use this in templates to test whether
  520. you're in :setting:`DEBUG` mode.
  521. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  522. representing every SQL query that has happened so far during the request
  523. and how long it took. The list is in order by query and lazily generated
  524. on access.
  525. django.template.context_processors.i18n
  526. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  527. If this processor is enabled, every ``RequestContext`` will contain these two
  528. variables:
  529. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  530. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  531. the value of the :setting:`LANGUAGE_CODE` setting.
  532. See :doc:`/topics/i18n/index` for more.
  533. django.template.context_processors.media
  534. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  535. If this processor is enabled, every ``RequestContext`` will contain a variable
  536. ``MEDIA_URL``, providing the value of the :setting:`MEDIA_URL` setting.
  537. django.template.context_processors.static
  538. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  539. .. function:: static
  540. If this processor is enabled, every ``RequestContext`` will contain a variable
  541. ``STATIC_URL``, providing the value of the :setting:`STATIC_URL` setting.
  542. django.template.context_processors.csrf
  543. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  544. This processor adds a token that is needed by the :ttag:`csrf_token` template
  545. tag for protection against :doc:`Cross Site Request Forgeries
  546. </ref/csrf>`.
  547. django.template.context_processors.request
  548. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  549. If this processor is enabled, every ``RequestContext`` will contain a variable
  550. ``request``, which is the current :class:`~django.http.HttpRequest`.
  551. django.contrib.messages.context_processors.messages
  552. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  553. If this processor is enabled, every ``RequestContext`` will contain these two
  554. variables:
  555. * ``messages`` -- A list of messages (as strings) that have been set
  556. via the :doc:`messages framework </ref/contrib/messages>`.
  557. * ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to
  558. :ref:`their numeric value <message-level-constants>`.
  559. Writing your own context processors
  560. -----------------------------------
  561. A context processor has a very simple interface: It's just a Python function
  562. that takes one argument, an :class:`~django.http.HttpRequest` object, and
  563. returns a dictionary that gets added to the template context. Each context
  564. processor *must* return a dictionary.
  565. Custom context processors can live anywhere in your code base. All Django
  566. cares about is that your custom context processors are pointed to by the
  567. ``'context_processors'`` option in your :setting:`TEMPLATES` setting — or the
  568. ``context_processors`` argument of :class:`~django.template.Engine` if you're
  569. using it directly.
  570. Loading templates
  571. =================
  572. Generally, you'll store templates in files on your filesystem rather than
  573. using the low-level :class:`~django.template.Template` API yourself. Save
  574. templates in a directory specified as a **template directory**.
  575. Django searches for template directories in a number of places, depending on
  576. your template loading settings (see "Loader types" below), but the most basic
  577. way of specifying template directories is by using the :setting:`DIRS
  578. <TEMPLATES-DIRS>` option.
  579. The :setting:`DIRS <TEMPLATES-DIRS>` option
  580. -------------------------------------------
  581. .. versionchanged:: 1.8
  582. This value used to be defined by the ``TEMPLATE_DIRS`` setting.
  583. Tell Django what your template directories are by using the :setting:`DIRS
  584. <TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting in your settings
  585. file — or the ``dirs`` argument of :class:`~django.template.Engine`. This
  586. should be set to a list of strings that contain full paths to your template
  587. directories::
  588. TEMPLATES = [
  589. {
  590. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  591. 'DIRS': [
  592. '/home/html/templates/lawrence.com',
  593. '/home/html/templates/default',
  594. ],
  595. },
  596. ]
  597. Your templates can go anywhere you want, as long as the directories and
  598. templates are readable by the Web server. They can have any extension you want,
  599. such as ``.html`` or ``.txt``, or they can have no extension at all.
  600. Note that these paths should use Unix-style forward slashes, even on Windows.
  601. .. _template-loaders:
  602. Loader types
  603. ------------
  604. By default, Django uses a filesystem-based template loader, but Django comes
  605. with a few other template loaders, which know how to load templates from other
  606. sources.
  607. Some of these other loaders are disabled by default, but you can activate them
  608. by adding a ``'loaders'`` option to your ``DjangoTemplates`` backend in the
  609. :setting:`TEMPLATES` setting or passing a ``loaders`` argument to
  610. :class:`~django.template.Engine`. ``loaders`` should be a list of strings or
  611. tuples, where each represents a template loader class. Here are the template
  612. loaders that come with Django:
  613. .. currentmodule:: django.template.loaders
  614. ``django.template.loaders.filesystem.Loader``
  615. .. class:: filesystem.Loader
  616. Loads templates from the filesystem, according to
  617. :setting:`DIRS <TEMPLATES-DIRS>`.
  618. This loader is enabled by default. However it won't find any templates
  619. until you set :setting:`DIRS <TEMPLATES-DIRS>` to a non-empty list::
  620. TEMPLATES = [{
  621. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  622. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  623. }]
  624. ``django.template.loaders.app_directories.Loader``
  625. .. class:: app_directories.Loader
  626. Loads templates from Django apps on the filesystem. For each app in
  627. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  628. subdirectory. If the directory exists, Django looks for templates in there.
  629. This means you can store templates with your individual apps. This also
  630. makes it easy to distribute Django apps with default templates.
  631. For example, for this setting::
  632. INSTALLED_APPS = ['myproject.polls', 'myproject.music']
  633. ...then ``get_template('foo.html')`` will look for ``foo.html`` in these
  634. directories, in this order:
  635. * ``/path/to/myproject/polls/templates/``
  636. * ``/path/to/myproject/music/templates/``
  637. ... and will use the one it finds first.
  638. The order of :setting:`INSTALLED_APPS` is significant! For example, if you
  639. want to customize the Django admin, you might choose to override the
  640. standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
  641. with your own ``admin/base_site.html`` in ``myproject.polls``. You must
  642. then make sure that your ``myproject.polls`` comes *before*
  643. ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
  644. ``django.contrib.admin``’s will be loaded first and yours will be ignored.
  645. Note that the loader performs an optimization when it first runs:
  646. it caches a list of which :setting:`INSTALLED_APPS` packages have a
  647. ``templates`` subdirectory.
  648. You can enable this loader simply by setting
  649. :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` to ``True``::
  650. TEMPLATES = [{
  651. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  652. 'APP_DIRS': True,
  653. }]
  654. ``django.template.loaders.eggs.Loader``
  655. .. class:: eggs.Loader
  656. Just like ``app_directories`` above, but it loads templates from Python
  657. eggs rather than from the filesystem.
  658. This loader is disabled by default.
  659. ``django.template.loaders.cached.Loader``
  660. .. class:: cached.Loader
  661. By default, the templating system will read and compile your templates every
  662. time they need to be rendered. While the Django templating system is quite
  663. fast, the overhead from reading and compiling templates can add up.
  664. The cached template loader is a class-based loader that you configure with
  665. a list of other loaders that it should wrap. The wrapped loaders are used to
  666. locate unknown templates when they are first encountered. The cached loader
  667. then stores the compiled ``Template`` in memory. The cached ``Template``
  668. instance is returned for subsequent requests to load the same template.
  669. For example, to enable template caching with the ``filesystem`` and
  670. ``app_directories`` template loaders you might use the following settings::
  671. TEMPLATES = [{
  672. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  673. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  674. 'OPTIONS': {
  675. 'loaders': [
  676. ('django.template.loaders.cached.Loader', [
  677. 'django.template.loaders.filesystem.Loader',
  678. 'django.template.loaders.app_directories.Loader',
  679. ]),
  680. ],
  681. },
  682. }]
  683. .. note::
  684. All of the built-in Django template tags are safe to use with the
  685. cached loader, but if you're using custom template tags that come from
  686. third party packages, or that you wrote yourself, you should ensure
  687. that the ``Node`` implementation for each tag is thread-safe. For more
  688. information, see :ref:`template tag thread safety considerations
  689. <template_tag_thread_safety>`.
  690. This loader is disabled by default.
  691. ``django.template.loaders.locmem.Loader``
  692. .. versionadded:: 1.8
  693. .. class:: locmem.Loader
  694. Loads templates from a Python dictionary. This is useful for testing.
  695. This loader takes a dictionary of templates as its first argument::
  696. TEMPLATES = [{
  697. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  698. 'OPTIONS': {
  699. 'loaders': [
  700. ('django.template.loaders.locmem.Loader', {
  701. 'index.html': 'content here',
  702. }),
  703. ],
  704. },
  705. }]
  706. This loader is disabled by default.
  707. Django uses the template loaders in order according to the ``'loaders'``
  708. option. It uses each loader until a loader finds a match.
  709. .. _custom-template-loaders:
  710. .. currentmodule:: django.template.loaders.base
  711. Custom loaders
  712. ==============
  713. It's possible to load templates from additional sources using custom template
  714. loaders. Custom ``Loader`` classes should inherit from
  715. ``django.template.loaders.base.Loader`` and define the ``get_contents()`` and
  716. ``get_template_sources()`` methods.
  717. .. versionchanged:: 1.8
  718. ``django.template.loaders.base.Loader`` used to be defined at
  719. ``django.template.loader.BaseLoader``.
  720. .. versionchanged:: 1.9
  721. In previous versions of Django, custom loaders defined a single method:
  722. ``load_template_source()``.
  723. Loader methods
  724. --------------
  725. .. class:: Loader
  726. Loads templates from a given source, such as the filesystem or a database.
  727. .. method:: get_template_sources(template_name)
  728. A method that takes a ``template_name`` and yields
  729. :class:`~django.template.base.Origin` instances for each possible
  730. source.
  731. For example, the filesystem loader may receive ``'index.html'`` as a
  732. ``template_name`` argument. This method would yield origins for the
  733. full path of ``index.html`` as it appears in each template directory
  734. the loader looks at.
  735. The method doesn't need to verify that the template exists at a given
  736. path, but it should ensure the path is valid. For instance, the
  737. filesystem loader makes sure the path lies under a valid template
  738. directory.
  739. .. method:: get_contents(origin)
  740. Returns the contents for a template given a
  741. :class:`~django.template.base.Origin` instance.
  742. This is where a filesystem loader would read contents from the
  743. filesystem, or a database loader would read from the database. If a
  744. matching template doesn't exist, this should raise a
  745. :exc:`~django.template.TemplateDoesNotExist` error.
  746. .. method:: get_template(template_name, skip=None)
  747. Returns a ``Template`` object for a given ``template_name`` by looping
  748. through results from :meth:`get_template_sources` and calling
  749. :meth:`get_contents`. This returns the first matching template. If no
  750. template is found, :exc:`~django.template.TemplateDoesNotExist` is
  751. raised.
  752. The optional ``skip`` argument is a list of origins to ignore when
  753. extending templates. This allow templates to extend other templates of
  754. the same name. It also used to avoid recursion errors.
  755. In general, it is enough to define :meth:`get_template_sources` and
  756. :meth:`get_contents` for custom template loaders. ``get_template()``
  757. will usually not need to be overridden.
  758. .. method:: load_template_source(template_name, template_dirs=None)
  759. Returns a tuple of (``template_string``, ``template_origin``), where
  760. ``template_string`` is a string containing the template contents,
  761. and ``template_origin`` is a string identifying the template source.
  762. A filesystem-based loader may return the full path to the file as the
  763. ``template_origin``, for example.
  764. ``template_dirs`` is an optional argument used to control which
  765. directories the loader will search.
  766. This method is called automatically by :meth:`load_template` and should
  767. be overridden when writing custom template loaders.
  768. .. deprecated:: 1.9
  769. Custom loaders should use :meth:`get_template` and
  770. :meth:`get_contents` instead.
  771. .. method:: load_template(template_name, template_dirs=None)
  772. Returns a tuple of (``template``, ``template_origin``), where ``template``
  773. is a ``Template`` object and ``template_origin`` is a string identifying
  774. the template source. A filesystem-based loader may return the full
  775. path to the file as the ``template_origin``, for example.
  776. .. deprecated:: 1.9
  777. Custom loaders should use :meth:`get_template` and
  778. :meth:`get_contents` instead.
  779. .. admonition:: Building your own
  780. For examples, `read the source code for Django's built-in loaders`_.
  781. .. _read the source code for Django's built-in loaders: https://github.com/django/django/tree/master/django/template/loaders
  782. .. currentmodule:: django.template.base
  783. Template origin
  784. ===============
  785. Templates have an ``origin`` containing attributes depending on the source
  786. they are loaded from.
  787. .. versionchanged:: 1.9
  788. Django used to create an origin based on
  789. ``django.template.loader.LoaderOrigin`` or
  790. ``django.template.base.StringOrigin``. These have been replaced by
  791. ``django.template.base.Origin``.
  792. .. class:: Origin
  793. .. attribute:: name
  794. The path to the template as returned by the template loader.
  795. For loaders that read from the file system, this is the full
  796. path to the template.
  797. If the template is instantiated directly rather than through a
  798. template loader, this is a string value of ``<unknown_source>``.
  799. .. attribute:: template_name
  800. The relative path to the template as passed into the
  801. template loader.
  802. If the template is instantiated directly rather than through a
  803. template loader, this is ``None``.