api.txt 41 KB

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