api.txt 40 KB

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