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