api.txt 40 KB

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