api.txt 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. ====================================================
  2. The Django template language: For Python programmers
  3. ====================================================
  4. .. module:: django.template
  5. :synopsis: Django's template system
  6. This document explains the Django template system from a technical
  7. perspective -- how it works and how to extend it. If you're just looking for
  8. reference on the language syntax, see :doc:`/topics/templates`.
  9. If you're looking to use the Django template system as part of another
  10. application -- i.e., without the rest of the framework -- make sure to read
  11. the `configuration`_ section later in this document.
  12. .. _configuration: `configuring the template system in standalone mode`_
  13. Basics
  14. ======
  15. A **template** is a text document, or a normal Python string, that is marked-up
  16. using the Django template language. A template can contain **block tags** or
  17. **variables**.
  18. A **block tag** is a symbol within a template that does something.
  19. This definition is deliberately vague. For example, a block tag can output
  20. content, serve as a control structure (an "if" statement or "for" loop), grab
  21. content from a database or enable access to other template tags.
  22. Block tags are surrounded by ``"{%"`` and ``"%}"``.
  23. Example template with block tags:
  24. .. code-block:: html+django
  25. {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
  26. A **variable** is a symbol within a template that outputs a value.
  27. Variable tags are surrounded by ``"{{"`` and ``"}}"``.
  28. Example template with variables:
  29. .. code-block:: html+django
  30. My first name is {{ first_name }}. My last name is {{ last_name }}.
  31. A **context** is a "variable name" -> "variable value" mapping that is passed
  32. to a template.
  33. A template **renders** a context by replacing the variable "holes" with values
  34. from the context and executing all block tags.
  35. Using the template system
  36. =========================
  37. .. class:: Template
  38. Using the template system in Python is a two-step process:
  39. * First, you compile the raw template code into a ``Template`` object.
  40. * Then, you call the ``render()`` method of the ``Template`` object with a
  41. given context.
  42. Compiling a string
  43. ------------------
  44. The easiest way to create a ``Template`` object is by instantiating it
  45. directly. The class lives at :class:`django.template.Template`. The constructor
  46. takes one argument -- the raw template code::
  47. >>> from django.template import Template
  48. >>> t = Template("My name is {{ my_name }}.")
  49. >>> print(t)
  50. <django.template.Template instance>
  51. .. admonition:: Behind the scenes
  52. The system only parses your raw template code once -- when you create the
  53. ``Template`` object. From then on, it's stored internally as a "node"
  54. structure for performance.
  55. Even the parsing itself is quite fast. Most of the parsing happens via a
  56. single call to a single, short, regular expression.
  57. Rendering a context
  58. -------------------
  59. .. method:: render(context)
  60. Once you have a compiled ``Template`` object, you can render a context -- or
  61. multiple contexts -- with it. The ``Context`` class lives at
  62. :class:`django.template.Context`, and the constructor takes two (optional)
  63. arguments:
  64. * A dictionary mapping variable names to variable values.
  65. * The name of the current application. This application name is used
  66. to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
  67. If you're not using namespaced URLs, you can ignore this argument.
  68. Call the ``Template`` object's ``render()`` method with the context to "fill" the
  69. template::
  70. >>> from django.template import Context, Template
  71. >>> t = Template("My name is {{ my_name }}.")
  72. >>> c = Context({"my_name": "Adrian"})
  73. >>> t.render(c)
  74. "My name is Adrian."
  75. >>> c = Context({"my_name": "Dolores"})
  76. >>> t.render(c)
  77. "My name is Dolores."
  78. Variables and lookups
  79. ~~~~~~~~~~~~~~~~~~~~~
  80. Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
  81. (but they must not start with an underscore) or a dot.
  82. Dots have a special meaning in template rendering. A dot in a variable name
  83. signifies a **lookup**. Specifically, when the template system encounters a
  84. dot in a variable name, it tries the following lookups, in this order:
  85. * Dictionary lookup. Example: ``foo["bar"]``
  86. * Attribute lookup. Example: ``foo.bar``
  87. * List-index lookup. Example: ``foo[bar]``
  88. Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
  89. interpreted as a literal string and not using the value of the variable "bar",
  90. if one exists in the template context.
  91. The template system uses the first lookup type that works. It's short-circuit
  92. logic. Here are a few examples::
  93. >>> from django.template import Context, Template
  94. >>> t = Template("My name is {{ person.first_name }}.")
  95. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  96. >>> t.render(Context(d))
  97. "My name is Joe."
  98. >>> class PersonClass: pass
  99. >>> p = PersonClass()
  100. >>> p.first_name = "Ron"
  101. >>> p.last_name = "Nasty"
  102. >>> t.render(Context({"person": p}))
  103. "My name is Ron."
  104. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  105. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  106. >>> t.render(c)
  107. "The first stooge in the list is Larry."
  108. If any part of the variable is callable, the template system will try calling
  109. it. Example::
  110. >>> class PersonClass2:
  111. ... def name(self):
  112. ... return "Samantha"
  113. >>> t = Template("My name is {{ person.name }}.")
  114. >>> t.render(Context({"person": PersonClass2}))
  115. "My name is Samantha."
  116. Callable variables are slightly more complex than variables which only require
  117. straight lookups. Here are some things to keep in mind:
  118. * If the variable raises an exception when called, the exception will be
  119. propagated, unless the exception has an attribute
  120. ``silent_variable_failure`` whose value is ``True``. If the exception
  121. *does* have a ``silent_variable_failure`` attribute whose value is
  122. ``True``, the variable will render as the value of the
  123. ``string_if_invalid`` configuration option (an empty string, by default).
  124. Example::
  125. >>> t = Template("My name is {{ person.first_name }}.")
  126. >>> class PersonClass3:
  127. ... def first_name(self):
  128. ... raise AssertionError("foo")
  129. >>> p = PersonClass3()
  130. >>> t.render(Context({"person": p}))
  131. Traceback (most recent call last):
  132. ...
  133. AssertionError: foo
  134. >>> class SilentAssertionError(Exception):
  135. ... silent_variable_failure = True
  136. >>> class PersonClass4:
  137. ... def first_name(self):
  138. ... raise SilentAssertionError
  139. >>> p = PersonClass4()
  140. >>> t.render(Context({"person": p}))
  141. "My name is ."
  142. Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the
  143. base class for all Django database API ``DoesNotExist`` exceptions, has
  144. ``silent_variable_failure = True``. So if you're using Django templates
  145. with Django model objects, any ``DoesNotExist`` exception will fail
  146. silently.
  147. * A variable can only be called if it has no required arguments. Otherwise,
  148. the system will return the value of the ``string_if_invalid`` option.
  149. .. _alters-data-description:
  150. * Obviously, there can be side effects when calling some variables, and
  151. it'd be either foolish or a security hole to allow the template system
  152. to access them.
  153. A good example is the :meth:`~django.db.models.Model.delete` method on
  154. each Django model object. The template system shouldn't be allowed to do
  155. something like this::
  156. I will now delete this valuable data. {{ data.delete }}
  157. To prevent this, set an ``alters_data`` attribute on the callable
  158. variable. The template system won't call a variable if it has
  159. ``alters_data=True`` set, and will instead replace the variable with
  160. ``string_if_invalid``, unconditionally. The
  161. dynamically-generated :meth:`~django.db.models.Model.delete` and
  162. :meth:`~django.db.models.Model.save` methods on Django model objects get
  163. ``alters_data=True`` automatically. Example::
  164. def sensitive_function(self):
  165. self.database_record.delete()
  166. sensitive_function.alters_data = True
  167. * Occasionally you may want to turn off this feature for other reasons,
  168. and tell the template system to leave a variable uncalled no matter
  169. what. To do so, set a ``do_not_call_in_templates`` attribute on the
  170. callable with the value ``True``. The template system then will act as
  171. if your variable is not callable (allowing you to access attributes of
  172. the callable, for example).
  173. .. _invalid-template-variables:
  174. How invalid variables are handled
  175. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  176. Generally, if a variable doesn't exist, the template system inserts the
  177. value of the ``string_if_invalid`` configuration option, which is set to
  178. ``''`` (the empty string) by default.
  179. Filters that are applied to an invalid variable will only be applied if
  180. ``string_if_invalid`` is set to ``''`` (the empty string). If
  181. ``string_if_invalid`` is set to any other value, variable filters will be
  182. ignored.
  183. This behavior is slightly different for the ``if``, ``for`` and ``regroup``
  184. template tags. If an invalid variable is provided to one of these template
  185. tags, the variable will be interpreted as ``None``. Filters are always
  186. applied to invalid variables within these template tags.
  187. If ``string_if_invalid`` contains a ``'%s'``, the format marker will be
  188. replaced with the name of the invalid variable.
  189. .. admonition:: For debug purposes only!
  190. While ``string_if_invalid`` can be a useful debugging tool, it is a bad
  191. idea to turn it on as a 'development default'.
  192. Many templates, including those in the Admin site, rely upon the silence
  193. of the template system when a non-existent variable is encountered. If you
  194. assign a value other than ``''`` to ``string_if_invalid``, you will
  195. experience rendering problems with these templates and sites.
  196. Generally, ``string_if_invalid`` should only be enabled in order to debug
  197. a specific template problem, then cleared once debugging is complete.
  198. Builtin variables
  199. ~~~~~~~~~~~~~~~~~
  200. Every context contains ``True``, ``False`` and ``None``. As you would expect,
  201. these variables resolve to the corresponding Python objects.
  202. Limitations with string literals
  203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  204. Django's template language has no way to escape the characters used for its own
  205. syntax. For example, the :ttag:`templatetag` tag is required if you need to
  206. output character sequences like ``{%`` and ``%}``.
  207. A similar issue exists if you want to include these sequences in template filter
  208. or tag arguments. For example, when parsing a block tag, Django's template
  209. parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents
  210. the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError``
  211. will be raised for the following expressions::
  212. {% include "template.html" tvar="Some string literal with %} in it." %}
  213. {% with tvar="Some string literal with %} in it." %}{% endwith %}
  214. The same issue can be triggered by using a reserved sequence in filter
  215. arguments::
  216. {{ some.variable|default:"}}" }}
  217. If you need to use strings with these sequences, store them in template
  218. variables or use a custom template tag or filter to workaround the limitation.
  219. Playing with Context objects
  220. ----------------------------
  221. .. class:: Context
  222. Most of the time, you'll instantiate ``Context`` objects by passing in a
  223. fully-populated dictionary to ``Context()``. But you can add and delete items
  224. from a ``Context`` object once it's been instantiated, too, using standard
  225. dictionary syntax::
  226. >>> from django.template import Context
  227. >>> c = Context({"foo": "bar"})
  228. >>> c['foo']
  229. 'bar'
  230. >>> del c['foo']
  231. >>> c['foo']
  232. ''
  233. >>> c['newvariable'] = 'hello'
  234. >>> c['newvariable']
  235. 'hello'
  236. .. method:: Context.pop()
  237. .. method:: Context.push()
  238. .. exception:: ContextPopException
  239. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  240. If you ``pop()`` too much, it'll raise
  241. ``django.template.ContextPopException``::
  242. >>> c = Context()
  243. >>> c['foo'] = 'first level'
  244. >>> c.push()
  245. {}
  246. >>> c['foo'] = 'second level'
  247. >>> c['foo']
  248. 'second level'
  249. >>> c.pop()
  250. {'foo': 'second level'}
  251. >>> c['foo']
  252. 'first level'
  253. >>> c['foo'] = 'overwritten'
  254. >>> c['foo']
  255. 'overwritten'
  256. >>> c.pop()
  257. Traceback (most recent call last):
  258. ...
  259. ContextPopException
  260. .. versionadded:: 1.7
  261. You can also use ``push()`` as a context manager to ensure a matching ``pop()``
  262. is called.
  263. >>> c = Context()
  264. >>> c['foo'] = 'first level'
  265. >>> with c.push():
  266. >>> c['foo'] = 'second level'
  267. >>> c['foo']
  268. 'second level'
  269. >>> c['foo']
  270. 'first level'
  271. All arguments passed to ``push()`` will be passed to the ``dict`` constructor
  272. used to build the new context level.
  273. >>> c = Context()
  274. >>> c['foo'] = 'first level'
  275. >>> with c.push(foo='second level'):
  276. >>> c['foo']
  277. 'second level'
  278. >>> c['foo']
  279. 'first level'
  280. .. method:: update(other_dict)
  281. In addition to ``push()`` and ``pop()``, the ``Context``
  282. object also defines an ``update()`` method. This works like ``push()``
  283. but takes a dictionary as an argument and pushes that dictionary onto
  284. the stack instead of an empty one.
  285. >>> c = Context()
  286. >>> c['foo'] = 'first level'
  287. >>> c.update({'foo': 'updated'})
  288. {'foo': 'updated'}
  289. >>> c['foo']
  290. 'updated'
  291. >>> c.pop()
  292. {'foo': 'updated'}
  293. >>> c['foo']
  294. 'first level'
  295. Using a ``Context`` as a stack comes in handy in some custom template tags, as
  296. you'll see below.
  297. .. method:: Context.flatten()
  298. .. versionadded:: 1.7
  299. Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary
  300. including builtin variables.
  301. >>> c = Context()
  302. >>> c['foo'] = 'first level'
  303. >>> c.update({'bar': 'second level'})
  304. {'bar': 'second level'}
  305. >>> c.flatten()
  306. {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
  307. A ``flatten()`` method is also internally used to make ``Context`` objects comparable.
  308. >>> c1 = Context()
  309. >>> c1['foo'] = 'first level'
  310. >>> c1['bar'] = 'second level'
  311. >>> c2 = Context()
  312. >>> c2.update({'bar': 'second level', 'foo': 'first level'})
  313. {'foo': 'first level', 'bar': 'second level'}
  314. >>> c1 == c2
  315. True
  316. Result from ``flatten()`` can be useful in unit tests to compare ``Context``
  317. against ``dict``::
  318. class ContextTest(unittest.TestCase):
  319. def test_against_dictionary(self):
  320. c1 = Context()
  321. c1['update'] = 'value'
  322. self.assertEqual(c1.flatten(), {
  323. 'True': True, 'None': None, 'False': False,
  324. 'update': 'value'})
  325. .. _subclassing-context-requestcontext:
  326. Subclassing Context: RequestContext
  327. -----------------------------------
  328. .. class:: RequestContext
  329. Django comes with a special ``Context`` class,
  330. ``django.template.RequestContext``, that acts slightly differently than the
  331. normal ``django.template.Context``. The first difference is that it takes an
  332. :class:`~django.http.HttpRequest` as its first argument. For example::
  333. c = RequestContext(request, {
  334. 'foo': 'bar',
  335. })
  336. The second difference is that it automatically populates the context with a
  337. few variables, according to the ``'context_processors'`` option in the
  338. :setting:`TEMPLATES` setting.
  339. The ``'context_processors'`` option is a list of callables -- called **context
  340. processors** -- that take a request object as their argument and return a
  341. dictionary of items to be merged into the context. In the default generated
  342. settings file, the default template engine contains the following context
  343. processors::
  344. [
  345. 'django.contrib.auth.context_processors.auth',
  346. 'django.template.context_processors.debug',
  347. 'django.template.context_processors.i18n',
  348. 'django.template.context_processors.media',
  349. 'django.template.context_processors.static',
  350. 'django.template.context_processors.tz',
  351. 'django.contrib.messages.context_processors.messages',
  352. ]
  353. .. versionchanged:: 1.8
  354. Built-in template context processors were moved from
  355. ``django.core.context_processors`` to
  356. ``django.template.context_processors`` in Django 1.8.
  357. In addition to these, ``RequestContext`` always uses
  358. ``django.template.context_processors.csrf``. This is a security
  359. related context processor required by the admin and other contrib apps, and,
  360. in case of accidental misconfiguration, it is deliberately hardcoded in and
  361. cannot be turned off in the ``'context_processors'`` option.
  362. Each processor is applied in order. That means, if one processor adds a
  363. variable to the context and a second processor adds a variable with the same
  364. name, the second will override the first. The default processors are explained
  365. below.
  366. .. admonition:: When context processors are applied
  367. Context processors are applied *after* the context itself is processed.
  368. This means that a context processor may overwrite variables you've
  369. supplied to your ``Context`` or ``RequestContext``, so take care
  370. to avoid variable names that overlap with those supplied by your
  371. context processors.
  372. Also, you can give ``RequestContext`` a list of additional processors, using the
  373. optional, third positional argument, ``processors``. In this example, the
  374. ``RequestContext`` instance gets a ``ip_address`` variable::
  375. from django.http import HttpResponse
  376. from django.template import RequestContext
  377. def ip_address_processor(request):
  378. return {'ip_address': request.META['REMOTE_ADDR']}
  379. def some_view(request):
  380. # ...
  381. c = RequestContext(request, {
  382. 'foo': 'bar',
  383. }, [ip_address_processor])
  384. return HttpResponse(t.render(c))
  385. .. note::
  386. If you're using Django's :func:`~django.shortcuts.render_to_response()`
  387. shortcut to populate a template with the contents of a dictionary, your
  388. template will be passed a ``Context`` instance by default (not a
  389. ``RequestContext``). To use a ``RequestContext`` in your template
  390. rendering, use the :meth:`~django.shortcuts.render()` shortcut which is
  391. the same as a call to :func:`~django.shortcuts.render_to_response()` with a
  392. ``context_instance`` argument that forces the use of a ``RequestContext``.
  393. Here's what each of the default processors does:
  394. django.contrib.auth.context_processors.auth
  395. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  396. If this processor is enabled, every ``RequestContext`` will contain these
  397. variables:
  398. * ``user`` -- An ``auth.User`` instance representing the currently
  399. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  400. logged in).
  401. * ``perms`` -- An instance of
  402. ``django.contrib.auth.context_processors.PermWrapper``, representing the
  403. permissions that the currently logged-in user has.
  404. .. currentmodule:: django.template.context_processors
  405. django.template.context_processors.debug
  406. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  407. If this processor is enabled, every ``RequestContext`` will contain these two
  408. variables -- but only if your :setting:`DEBUG` setting is set to ``True`` and
  409. the request's IP address (``request.META['REMOTE_ADDR']``) is in the
  410. :setting:`INTERNAL_IPS` setting:
  411. * ``debug`` -- ``True``. You can use this in templates to test whether
  412. you're in :setting:`DEBUG` mode.
  413. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  414. representing every SQL query that has happened so far during the request
  415. and how long it took. The list is in order by query and lazily generated
  416. on access.
  417. django.template.context_processors.i18n
  418. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  419. If this processor is enabled, every ``RequestContext`` will contain these two
  420. variables:
  421. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  422. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  423. the value of the :setting:`LANGUAGE_CODE` setting.
  424. See :doc:`/topics/i18n/index` for more.
  425. django.template.context_processors.media
  426. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  427. If this processor is enabled, every ``RequestContext`` will contain a variable
  428. ``MEDIA_URL``, providing the value of the :setting:`MEDIA_URL` setting.
  429. django.template.context_processors.static
  430. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  431. .. function:: static
  432. If this processor is enabled, every ``RequestContext`` will contain a variable
  433. ``STATIC_URL``, providing the value of the :setting:`STATIC_URL` setting.
  434. django.template.context_processors.csrf
  435. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  436. This processor adds a token that is needed by the :ttag:`csrf_token` template
  437. tag for protection against :doc:`Cross Site Request Forgeries
  438. </ref/csrf>`.
  439. django.template.context_processors.request
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. If this processor is enabled, every ``RequestContext`` will contain a variable
  442. ``request``, which is the current :class:`~django.http.HttpRequest`. Note that
  443. this processor is not enabled by default; you'll have to activate it.
  444. django.contrib.messages.context_processors.messages
  445. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  446. If this processor is enabled, every ``RequestContext`` will contain these two
  447. variables:
  448. * ``messages`` -- A list of messages (as strings) that have been set
  449. via the :doc:`messages framework </ref/contrib/messages>`.
  450. * ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to
  451. :ref:`their numeric value <message-level-constants>`.
  452. .. versionchanged:: 1.7
  453. The ``DEFAULT_MESSAGE_LEVELS`` variable was added.
  454. Writing your own context processors
  455. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  456. A context processor has a very simple interface: It's just a Python function
  457. that takes one argument, an :class:`~django.http.HttpRequest` object, and
  458. returns a dictionary that gets added to the template context. Each context
  459. processor *must* return a dictionary.
  460. Custom context processors can live anywhere in your code base. All Django
  461. cares about is that your custom context processors are pointed to by the
  462. ``'context_processors'`` option in your :setting:`TEMPLATES` setting.
  463. Loading templates
  464. -----------------
  465. Generally, you'll store templates in files on your filesystem rather than using
  466. the low-level ``Template`` API yourself. Save templates in a directory
  467. specified as a **template directory**.
  468. Django searches for template directories in a number of places, depending on
  469. your template-loader settings (see "Loader types" below), but the most basic
  470. way of specifying template directories is by using the :setting:`DIRS
  471. <TEMPLATES-DIRS>` option.
  472. The DIRS option
  473. ~~~~~~~~~~~~~~~
  474. .. versionchanged:: 1.8
  475. This value used to be defined by the ``TEMPLATE_DIRS`` setting.
  476. Tell Django what your template directories are by using the :setting:`DIRS
  477. <TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting in your settings
  478. file. This should be set to a list of strings that contain full paths to your
  479. template directory(ies). Example::
  480. TEMPLATES = [
  481. {
  482. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  483. 'DIRS': [
  484. '/home/html/templates/lawrence.com',
  485. '/home/html/templates/default',
  486. ],
  487. },
  488. ]
  489. Your templates can go anywhere you want, as long as the directories and
  490. templates are readable by the Web server. They can have any extension you want,
  491. such as ``.html`` or ``.txt``, or they can have no extension at all.
  492. Note that these paths should use Unix-style forward slashes, even on Windows.
  493. .. _ref-templates-api-the-python-api:
  494. The Python API
  495. ~~~~~~~~~~~~~~
  496. .. module:: django.template.loader
  497. ``django.template.loader`` has two functions to load templates from files:
  498. .. function:: get_template(template_name[, dirs])
  499. ``get_template`` returns the compiled template (a ``Template`` object) for
  500. the template with the given name. If the template doesn't exist, it raises
  501. ``django.template.TemplateDoesNotExist``.
  502. .. versionchanged:: 1.7
  503. The ``dirs`` parameter was added.
  504. .. versionchanged:: 1.8
  505. The ``dirs`` parameter was deprecated.
  506. .. function:: select_template(template_name_list[, dirs])
  507. ``select_template`` is just like ``get_template``, except it takes a list
  508. of template names. Of the list, it returns the first template that exists.
  509. .. versionchanged:: 1.7
  510. The ``dirs`` parameter was added.
  511. .. versionchanged:: 1.8
  512. The ``dirs`` parameter was deprecated.
  513. For example, if you call ``get_template('story_detail.html')`` and have the
  514. above :setting:`DIRS <TEMPLATES-DIRS>` option, here are the files Django will
  515. look for, in order:
  516. * ``/home/html/templates/lawrence.com/story_detail.html``
  517. * ``/home/html/templates/default/story_detail.html``
  518. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  519. here's what Django will look for:
  520. * ``/home/html/templates/lawrence.com/story_253_detail.html``
  521. * ``/home/html/templates/default/story_253_detail.html``
  522. * ``/home/html/templates/lawrence.com/story_detail.html``
  523. * ``/home/html/templates/default/story_detail.html``
  524. When Django finds a template that exists, it stops looking.
  525. .. admonition:: Tip
  526. You can use ``select_template()`` for super-flexible "templatability." For
  527. example, if you've written a news story and want some stories to have
  528. custom templates, use something like
  529. ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
  530. That'll allow you to use a custom template for an individual story, with a
  531. fallback template for stories that don't have custom templates.
  532. Using subdirectories
  533. ~~~~~~~~~~~~~~~~~~~~
  534. It's possible -- and preferable -- to organize templates in subdirectories of
  535. the template directory. The convention is to make a subdirectory for each
  536. Django app, with subdirectories within those subdirectories as needed.
  537. Do this for your own sanity. Storing all templates in the root level of a
  538. single directory gets messy.
  539. To load a template that's within a subdirectory, just use a slash, like so::
  540. get_template('news/story_detail.html')
  541. Using the same :setting:`DIRS <TEMPLATES-DIRS>` option from above, this
  542. example ``get_template()`` call will attempt to load the following templates:
  543. * ``/home/html/templates/lawrence.com/news/story_detail.html``
  544. * ``/home/html/templates/default/news/story_detail.html``
  545. .. _template-loaders:
  546. Loader types
  547. ~~~~~~~~~~~~
  548. By default, Django uses a filesystem-based template loader, but Django comes
  549. with a few other template loaders, which know how to load templates from other
  550. sources.
  551. Some of these other loaders are disabled by default, but you can activate them
  552. by adding a ``'loaders'`` option to your ``DjangoTemplates`` backend in the
  553. :setting:`TEMPLATES` setting. ``'loaders'`` should be a list of strings or
  554. tuples, where each represents a template loader class. Here are the template
  555. loaders that come with Django:
  556. .. currentmodule:: django.template.loaders
  557. ``django.template.loaders.filesystem.Loader``
  558. .. class:: filesystem.Loader
  559. Loads templates from the filesystem, according to
  560. :setting:`DIRS <TEMPLATES-DIRS>`.
  561. This loader is enabled by default. However it won't find any templates
  562. until you set :setting:`DIRS <TEMPLATES-DIRS>` to a non-empty list::
  563. TEMPLATES = [{
  564. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  565. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  566. }]
  567. ``django.template.loaders.app_directories.Loader``
  568. .. class:: app_directories.Loader
  569. Loads templates from Django apps on the filesystem. For each app in
  570. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  571. subdirectory. If the directory exists, Django looks for templates in there.
  572. This means you can store templates with your individual apps. This also
  573. makes it easy to distribute Django apps with default templates.
  574. For example, for this setting::
  575. INSTALLED_APPS = ('myproject.polls', 'myproject.music')
  576. ...then ``get_template('foo.html')`` will look for ``foo.html`` in these
  577. directories, in this order:
  578. * ``/path/to/myproject/polls/templates/``
  579. * ``/path/to/myproject/music/templates/``
  580. ... and will use the one it finds first.
  581. The order of :setting:`INSTALLED_APPS` is significant! For example, if you
  582. want to customize the Django admin, you might choose to override the
  583. standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
  584. with your own ``admin/base_site.html`` in ``myproject.polls``. You must
  585. then make sure that your ``myproject.polls`` comes *before*
  586. ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
  587. ``django.contrib.admin``’s will be loaded first and yours will be ignored.
  588. Note that the loader performs an optimization when it first runs:
  589. it caches a list of which :setting:`INSTALLED_APPS` packages have a
  590. ``templates`` subdirectory.
  591. This loader is enabled if and only if :setting:`APP_DIRS
  592. <TEMPLATES-APP_DIRS>` is set::
  593. TEMPLATES = [{
  594. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  595. 'APP_DIRS': True,
  596. }]
  597. ``django.template.loaders.eggs.Loader``
  598. .. class:: eggs.Loader
  599. Just like ``app_directories`` above, but it loads templates from Python
  600. eggs rather than from the filesystem.
  601. This loader is disabled by default.
  602. ``django.template.loaders.cached.Loader``
  603. .. class:: cached.Loader
  604. By default, the templating system will read and compile your templates every
  605. time they need to be rendered. While the Django templating system is quite
  606. fast, the overhead from reading and compiling templates can add up.
  607. The cached template loader is a class-based loader that you configure with
  608. a list of other loaders that it should wrap. The wrapped loaders are used to
  609. locate unknown templates when they are first encountered. The cached loader
  610. then stores the compiled ``Template`` in memory. The cached ``Template``
  611. instance is returned for subsequent requests to load the same template.
  612. For example, to enable template caching with the ``filesystem`` and
  613. ``app_directories`` template loaders you might use the following settings::
  614. TEMPLATES = [{
  615. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  616. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  617. 'OPTIONS': {
  618. 'loaders': [
  619. ('django.template.loaders.cached.Loader', (
  620. 'django.template.loaders.filesystem.Loader',
  621. 'django.template.loaders.app_directories.Loader',
  622. )),
  623. ],
  624. },
  625. }]
  626. .. note::
  627. All of the built-in Django template tags are safe to use with the
  628. cached loader, but if you're using custom template tags that come from
  629. third party packages, or that you wrote yourself, you should ensure
  630. that the ``Node`` implementation for each tag is thread-safe. For more
  631. information, see :ref:`template tag thread safety
  632. considerations<template_tag_thread_safety>`.
  633. This loader is disabled by default.
  634. ``django.template.loaders.locmem.Loader``
  635. .. versionadded:: 1.8
  636. .. class:: locmem.Loader
  637. Loads templates from a Python dictionary. This is useful for testing.
  638. This loader takes a dictionary of templates as its first argument::
  639. TEMPLATES = [{
  640. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  641. 'OPTIONS': {
  642. 'loaders': [
  643. ('django.template.loaders.locmem.Loader', {
  644. 'index.html': 'content here',
  645. }),
  646. ],
  647. },
  648. }]
  649. This loader is disabled by default.
  650. Django uses the template loaders in order according to the ``'loaders'``
  651. option. It uses each loader until a loader finds a match.
  652. .. currentmodule:: django.template
  653. Template origin
  654. ~~~~~~~~~~~~~~~
  655. .. versionadded:: 1.7
  656. When :setting:`TEMPLATE_DEBUG` is ``True`` template objects will have an
  657. ``origin`` attribute depending on the source they are loaded from.
  658. .. class:: loader.LoaderOrigin
  659. Templates created from a template loader will use the
  660. ``django.template.loader.LoaderOrigin`` class.
  661. .. attribute:: name
  662. The path to the template as returned by the template loader.
  663. For loaders that read from the file system, this is the full
  664. path to the template.
  665. .. attribute:: loadname
  666. The relative path to the template as passed into the
  667. template loader.
  668. .. class:: StringOrigin
  669. Templates created from a ``Template`` class will use the
  670. ``django.template.StringOrigin`` class.
  671. .. attribute:: source
  672. The string used to create the template.
  673. The ``render_to_string`` shortcut
  674. ===================================
  675. .. function:: loader.render_to_string(template_name, context=None, context_instance=None)
  676. To cut down on the repetitive nature of loading and rendering
  677. templates, Django provides a shortcut function which largely
  678. automates the process: ``render_to_string()`` in
  679. :mod:`django.template.loader`, which loads a template, renders it and
  680. returns the resulting string::
  681. from django.template.loader import render_to_string
  682. rendered = render_to_string('my_template.html', {'foo': 'bar'})
  683. The ``render_to_string`` shortcut takes one required argument --
  684. ``template_name``, which should be the name of the template to load
  685. and render (or a list of template names, in which case Django will use
  686. the first template in the list that exists) -- and two optional arguments:
  687. ``context``
  688. A dictionary to be used as variables and values for the
  689. template's context. This should be passed as the second
  690. positional argument.
  691. .. versionchanged:: 1.8
  692. The ``context`` argument used to be called ``dictionary``. That name
  693. is deprecated in Django 1.8 and will be removed in Django 2.0.
  694. ``context_instance``
  695. An instance of :class:`~django.template.Context` or a subclass (e.g., an
  696. instance of :class:`~django.template.RequestContext`) to use as the
  697. template's context. This can also be passed as the third positional argument.
  698. .. deprecated:: 1.8
  699. The ``context_instance`` argument is deprecated. Simply use ``context``.
  700. See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
  701. calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse`
  702. suitable for returning directly from a view.
  703. Configuring the template system in standalone mode
  704. ==================================================
  705. .. note::
  706. This section is only of interest to people trying to use the template
  707. system as an output component in another application. If you're using the
  708. template system as part of a Django application, nothing here applies to
  709. you.
  710. Normally, Django will load all the configuration information it needs from its
  711. own default configuration file, combined with the settings in the module given
  712. in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
  713. using the template system independently of the rest of Django, the environment
  714. variable approach isn't very convenient, because you probably want to configure
  715. the template system in line with the rest of your application rather than
  716. dealing with settings files and pointing to them via environment variables.
  717. To solve this problem, you need to use the manual configuration option described
  718. in :ref:`settings-without-django-settings-module`. Simply import the appropriate
  719. pieces of the templating system and then, *before* you call any of the
  720. templating functions, call :func:`django.conf.settings.configure()` with any
  721. settings you wish to specify. You might want to consider setting at least
  722. :setting:`DIRS <TEMPLATES-DIRS>` (if you're going to use template loaders),
  723. :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
  724. and :setting:`TEMPLATE_DEBUG`. If you plan to use the :ttag:`url` template tag,
  725. you will also need to set the :setting:`ROOT_URLCONF` setting. All available
  726. settings are described in the :doc:`settings documentation </ref/settings>`,
  727. and any setting starting with ``TEMPLATE_`` is of obvious interest.
  728. .. _topic-template-alternate-language:
  729. Using an alternative template language
  730. ======================================
  731. The Django ``Template`` and ``Loader`` classes implement a simple API for
  732. loading and rendering templates. By providing some simple wrapper classes that
  733. implement this API we can use third party template systems like `Jinja2
  734. <http://jinja.pocoo.org/docs/>`_. This
  735. allows us to use third-party template libraries without giving up useful Django
  736. features like the Django ``Context`` object and handy shortcuts like
  737. :func:`~django.shortcuts.render_to_response()`.
  738. The core component of the Django templating system is the ``Template`` class.
  739. This class has a very simple interface: it has a constructor that takes a single
  740. positional argument specifying the template string, and a ``render()`` method
  741. that takes a :class:`~django.template.Context` object and returns a string
  742. containing the rendered response.
  743. Suppose we're using a template language that defines a ``Template`` object with
  744. a ``render()`` method that takes a dictionary rather than a ``Context`` object.
  745. We can write a simple wrapper that implements the Django ``Template`` interface::
  746. import some_template_language
  747. class Template(some_template_language.Template):
  748. def render(self, context):
  749. # flatten the Django Context into a single dictionary.
  750. context_dict = {}
  751. for d in context.dicts:
  752. context_dict.update(d)
  753. return super(Template, self).render(context_dict)
  754. That's all that's required to make our fictional ``Template`` class compatible
  755. with the Django loading and rendering system!
  756. The next step is to write a ``Loader`` class that returns instances of our custom
  757. template class instead of the default :class:`~django.template.Template`. Custom ``Loader``
  758. classes should inherit from ``django.template.loaders.base.Loader`` and override
  759. the ``load_template_source()`` method, which takes a ``template_name`` argument,
  760. loads the template from disk (or elsewhere), and returns a tuple:
  761. ``(template_string, template_origin)``.
  762. .. versionchanged:: 1.8
  763. ``django.template.loaders.base.Loader`` used to be defined at
  764. ``django.template.loader.BaseLoader``.
  765. The ``load_template()`` method of the ``Loader`` class retrieves the template
  766. string by calling ``load_template_source()``, instantiates a ``Template`` from
  767. the template source, and returns a tuple: ``(template, template_origin)``. Since
  768. this is the method that actually instantiates the ``Template``, we'll need to
  769. override it to use our custom template class instead. We can inherit from the
  770. builtin :class:`django.template.loaders.app_directories.Loader` to take advantage
  771. of the ``load_template_source()`` method implemented there::
  772. from django.template.loaders import app_directories
  773. class Loader(app_directories.Loader):
  774. is_usable = True
  775. def load_template(self, template_name, template_dirs=None):
  776. source, origin = self.load_template_source(template_name, template_dirs)
  777. template = Template(source)
  778. return template, origin
  779. Finally, we need to modify our project settings, telling Django to use our custom
  780. loader. Now we can write all of our templates in our alternative template
  781. language while continuing to use the rest of the Django templating system.