api.txt 35 KB

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