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