api.txt 39 KB

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