api.txt 39 KB

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