api.txt 39 KB

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