Debian Codegraph @

docs/ref/templates/api.txt

raw
1 ====================================================
2 The Django template language: for Python programmers
3 ====================================================
4
5 .. currentmodule:: django.template
6
7 This document explains the Django template system from a technical
8 perspective -- how it works and how to extend it. If you're looking for
9 reference on the language syntax, see :doc:`/ref/templates/language`.
10
11 It assumes an understanding of templates, contexts, variables, tags, and
12 rendering. Start with the :ref:`introduction to the Django template language
13 <template-language-intro>` if you aren't familiar with these concepts.
14
15 Overview
16 ========
17
18 Using the template system in Python is a three-step process:
19
20 1. You configure an :class:`Engine`.
21 2. You compile template code into a :class:`Template`.
22 3. You render the template with a :class:`Context`.
23
24 Django projects generally rely on the :ref:`high level, backend agnostic APIs
25 <template-engines>` for each of these steps instead of the template system's
26 lower level APIs:
27
28 1. For each :class:`~django.template.backends.django.DjangoTemplates` backend
29 in the :setting:`TEMPLATES` setting, Django instantiates an
30 :class:`Engine`. :class:`~django.template.backends.django.DjangoTemplates`
31 wraps :class:`Engine` and adapts it to the common template backend API.
32 2. The :mod:`django.template.loader` module provides functions such as
33 :func:`~django.template.loader.get_template` for loading templates. They
34 return a ``django.template.backends.django.Template`` which wraps the
35 actual :class:`django.template.Template`.
36 3. The ``Template`` obtained in the previous step has a
37 :meth:`~django.template.backends.base.Template.render` method which
38 marshals a context and possibly a request into a :class:`Context` and
39 delegates the rendering to the underlying :class:`Template`.
40
41 Configuring an engine
42 =====================
43
44 If you are using the :class:`~django.template.backends.django.DjangoTemplates`
45 backend, this probably isn't the documentation you're looking for. An instance
46 of the ``Engine`` class described below is accessible using the ``engine``
47 attribute of that backend and any attribute defaults mentioned below are
48 overridden by what's passed by
49 :class:`~django.template.backends.django.DjangoTemplates`.
50
51 .. 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)
52
53 When instantiating an ``Engine`` all arguments must be passed as keyword
54 arguments:
55
56 * ``dirs`` is a list of directories where the engine should look for
57 template source files. It is used to configure
58 :class:`filesystem.Loader <django.template.loaders.filesystem.Loader>`.
59
60 It defaults to an empty list.
61
62 * ``app_dirs`` only affects the default value of ``loaders``. See below.
63
64 It defaults to ``False``.
65
66 * ``autoescape`` controls whether HTML autoescaping is enabled.
67
68 It defaults to ``True``.
69
70 .. warning::
71
72 Only set it to ``False`` if you're rendering non-HTML templates!
73
74 * ``context_processors`` is a list of dotted Python paths to callables
75 that are used to populate the context when a template is rendered with a
76 request. These callables take a request object as their argument and
77 return a :class:`dict` of items to be merged into the context.
78
79 It defaults to an empty list.
80
81 See :class:`~django.template.RequestContext` for more information.
82
83 * ``debug`` is a boolean that turns on/off template debug mode. If it is
84 ``True``, the template engine will store additional debug information
85 which can be used to display a detailed report for any exception raised
86 during template rendering.
87
88 It defaults to ``False``.
89
90 * ``loaders`` is a list of template loader classes, specified as strings.
91 Each ``Loader`` class knows how to import templates from a particular
92 source. Optionally, a tuple can be used instead of a string. The first
93 item in the tuple should be the ``Loader`` class name, subsequent items
94 are passed to the ``Loader`` during initialization.
95
96 It defaults to a list containing:
97
98 * ``'django.template.loaders.filesystem.Loader'``
99 * ``'django.template.loaders.app_directories.Loader'`` if and only if
100 ``app_dirs`` is ``True``.
101
102 These loaders are then wrapped in
103 :class:`django.template.loaders.cached.Loader`.
104
105 See :ref:`template-loaders` for details.
106
107 * ``string_if_invalid`` is the output, as a string, that the template
108 system should use for invalid (e.g. misspelled) variables.
109
110 It defaults to the empty string.
111
112 See :ref:`invalid-template-variables` for details.
113
114 * ``file_charset`` is the charset used to read template files on disk.
115
116 It defaults to ``'utf-8'``.
117
118 * ``'libraries'``: A dictionary of labels and dotted Python paths of template
119 tag modules to register with the template engine. This is used to add new
120 libraries or provide alternate labels for existing ones. For example::
121
122 Engine(
123 libraries={
124 "myapp_tags": "path.to.myapp.tags",
125 "admin.urls": "django.contrib.admin.templatetags.admin_urls",
126 },
127 )
128
129 Libraries can be loaded by passing the corresponding dictionary key to
130 the :ttag:`{% load %}<load>` tag.
131
132 * ``'builtins'``: A list of dotted Python paths of template tag modules to
133 add to :doc:`built-ins </ref/templates/builtins>`. For example::
134
135 Engine(
136 builtins=["myapp.builtins"],
137 )
138
139 Tags and filters from built-in libraries can be used without first calling
140 the :ttag:`{% load %}<load>` tag.
141
142 .. staticmethod:: Engine.get_default()
143
144 Returns the underlying :class:`Engine` from the first configured
145 :class:`~django.template.backends.django.DjangoTemplates` engine. Raises
146 :exc:`~django.core.exceptions.ImproperlyConfigured` if no engines are
147 configured.
148
149 It's required for preserving APIs that rely on a globally available,
150 implicitly configured engine. Any other use is strongly discouraged.
151
152 .. method:: Engine.from_string(template_code)
153
154 Compiles the given template code and returns a :class:`Template` object.
155
156 .. method:: Engine.get_template(template_name)
157
158 Loads a template with the given name, compiles it and returns a
159 :class:`Template` object.
160
161 .. method:: Engine.select_template(template_name_list)
162
163 Like :meth:`~Engine.get_template`, except it takes a list of names
164 and returns the first template that was found.
165
166 Loading a template
167 ==================
168
169 The recommended way to create a :class:`Template` is by calling the factory
170 methods of the :class:`Engine`: :meth:`~Engine.get_template`,
171 :meth:`~Engine.select_template` and :meth:`~Engine.from_string`.
172
173 In a Django project where the :setting:`TEMPLATES` setting defines a
174 :class:`~django.template.backends.django.DjangoTemplates` engine, it's
175 possible to instantiate a :class:`Template` directly. If more than one
176 :class:`~django.template.backends.django.DjangoTemplates` engine is defined,
177 the first one will be used.
178
179 .. class:: Template
180
181 This class lives at ``django.template.Template``. The constructor takes
182 one argument — the raw template code::
183
184 from django.template import Template
185
186 template = Template("My name is {{ my_name }}.")
187
188 .. admonition:: Behind the scenes
189
190 The system only parses your raw template code once -- when you create the
191 ``Template`` object. From then on, it's stored internally as a tree
192 structure for performance.
193
194 Even the parsing itself is quite fast. Most of the parsing happens via a
195 single call to a single, short, regular expression.
196
197 Rendering a context
198 ===================
199
200 Once you have a compiled :class:`Template` object, you can render a context
201 with it. You can reuse the same template to render it several times with
202 different contexts.
203
204 .. class:: Context(dict_=None, autoescape=True, use_l10n=None, use_tz=None)
205
206 The constructor of ``django.template.Context`` takes an optional argument —
207 a dictionary mapping variable names to variable values.
208
209 Three optional keyword arguments can also be specified:
210
211 * ``autoescape`` controls whether HTML autoescaping is enabled.
212
213 It defaults to ``True``.
214
215 .. warning::
216
217 Only set it to ``False`` if you're rendering non-HTML templates!
218
219 * ``use_l10n`` overrides whether values will be localized by default. If
220 set to ``True`` numbers and dates will be formatted based on locale.
221
222 It defaults to ``None``.
223
224 See :ref:`topic-l10n-templates` for details.
225
226 * ``use_tz`` overrides whether dates are converted to the local time when
227 rendered in a template. If set to ``True`` all dates will be rendered
228 using the local timezone. This takes precedence over :setting:`USE_TZ`.
229
230 It defaults to ``None``.
231
232 See :ref:`time-zones-in-templates` for details.
233
234 For example usage, see :ref:`playing-with-context` below.
235
236 .. method:: Template.render(context)
237
238 Call the :class:`Template` object's ``render()`` method with a
239 :class:`Context` to "fill" the template:
240
241 .. code-block:: pycon
242
243 >>> from django.template import Context, Template
244 >>> template = Template("My name is {{ my_name }}.")
245
246 >>> context = Context({"my_name": "Adrian"})
247 >>> template.render(context)
248 "My name is Adrian."
249
250 >>> context = Context({"my_name": "Dolores"})
251 >>> template.render(context)
252 "My name is Dolores."
253
254 Variables and lookups
255 ---------------------
256
257 Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
258 (but they must not start with an underscore) or a dot.
259
260 Dots have a special meaning in template rendering. A dot in a variable name
261 signifies a **lookup**. Specifically, when the template system encounters a
262 dot in a variable name, it tries the following lookups, in this order:
263
264 * Dictionary lookup. Example: ``foo["bar"]``
265 * Attribute lookup. Example: ``foo.bar``
266 * List-index lookup. Example: ``foo[bar]``
267
268 Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
269 interpreted as a literal string and not using the value of the variable "bar",
270 if one exists in the template context.
271
272 The template system uses the first lookup type that works. It's short-circuit
273 logic. Here are a few examples:
274
275 .. code-block:: pycon
276
277 >>> from django.template import Context, Template
278 >>> t = Template("My name is {{ person.first_name }}.")
279 >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
280 >>> t.render(Context(d))
281 "My name is Joe."
282
283 >>> class PersonClass:
284 ... pass
285 ...
286 >>> p = PersonClass()
287 >>> p.first_name = "Ron"
288 >>> p.last_name = "Nasty"
289 >>> t.render(Context({"person": p}))
290 "My name is Ron."
291
292 >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
293 >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
294 >>> t.render(c)
295 "The first stooge in the list is Larry."
296
297 If any part of the variable is callable, the template system will try calling
298 it. Example:
299
300 .. code-block:: pycon
301
302 >>> class PersonClass2:
303 ... def name(self):
304 ... return "Samantha"
305 ...
306 >>> t = Template("My name is {{ person.name }}.")
307 >>> t.render(Context({"person": PersonClass2}))
308 "My name is Samantha."
309
310 Callable variables are slightly more complex than variables which only require
311 straight lookups. Here are some things to keep in mind:
312
313 * If the variable raises an exception when called, the exception will be
314 propagated, unless the exception has an attribute
315 ``silent_variable_failure`` whose value is ``True``. If the exception
316 *does* have a ``silent_variable_failure`` attribute whose value is
317 ``True``, the variable will render as the value of the engine's
318 ``string_if_invalid`` configuration option (an empty string, by default).
319 Example:
320
321 .. code-block:: pycon
322
323 >>> t = Template("My name is {{ person.first_name }}.")
324 >>> class PersonClass3:
325 ... def first_name(self):
326 ... raise AssertionError("foo")
327 ...
328 >>> p = PersonClass3()
329 >>> t.render(Context({"person": p}))
330 Traceback (most recent call last):
331 ...
332 AssertionError: foo
333
334 >>> class SilentAssertionError(Exception):
335 ... silent_variable_failure = True
336 ...
337 >>> class PersonClass4:
338 ... def first_name(self):
339 ... raise SilentAssertionError
340 ...
341 >>> p = PersonClass4()
342 >>> t.render(Context({"person": p}))
343 "My name is ."
344
345 Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the
346 base class for all Django database API ``DoesNotExist`` exceptions, has
347 ``silent_variable_failure = True``. So if you're using Django templates
348 with Django model objects, any ``DoesNotExist`` exception will fail
349 silently.
350
351 * A variable can only be called if it has no required arguments. Otherwise,
352 the system will return the value of the engine's ``string_if_invalid``
353 option.
354
355 .. _alters-data-description:
356
357 * There can be side effects when calling some variables, and it'd be either
358 foolish or a security hole to allow the template system to access them.
359
360 A good example is the :meth:`~django.db.models.Model.delete` method on
361 each Django model object. The template system shouldn't be allowed to do
362 something like this:
363
364 .. code-block:: html+django
365
366 I will now delete this valuable data. {{ data.delete }}
367
368 To prevent this, set an ``alters_data`` attribute on the callable
369 variable. The template system won't call a variable if it has
370 ``alters_data=True`` set, and will instead replace the variable with
371 ``string_if_invalid``, unconditionally. The
372 dynamically-generated :meth:`~django.db.models.Model.delete` and
373 :meth:`~django.db.models.Model.save` methods on Django model objects get
374 ``alters_data=True`` automatically. Example::
375
376 def sensitive_function(self):
377 self.database_record.delete()
378
379
380 sensitive_function.alters_data = True
381
382 * Occasionally you may want to turn off this feature for other reasons,
383 and tell the template system to leave a variable uncalled no matter
384 what. To do so, set a ``do_not_call_in_templates`` attribute on the
385 callable with the value ``True``. The template system then will act as
386 if your variable is not callable (allowing you to access attributes of
387 the callable, for example).
388
389 .. _invalid-template-variables:
390
391 How invalid variables are handled
392 ---------------------------------
393
394 Generally, if a variable doesn't exist, the template system inserts the value
395 of the engine's ``string_if_invalid`` configuration option, which is set to
396 ``''`` (the empty string) by default.
397
398 Filters that are applied to an invalid variable will only be applied if
399 ``string_if_invalid`` is set to ``''`` (the empty string). If
400 ``string_if_invalid`` is set to any other value, variable filters will be
401 ignored.
402
403 This behavior is slightly different for the ``if``, ``for`` and ``regroup``
404 template tags. If an invalid variable is provided to one of these template
405 tags, the variable will be interpreted as ``None``. Filters are always
406 applied to invalid variables within these template tags.
407
408 If ``string_if_invalid`` contains a ``'%s'``, the format marker will be
409 replaced with the name of the invalid variable.
410
411 .. admonition:: For debug purposes only!
412
413 While ``string_if_invalid`` can be a useful debugging tool, it is a bad
414 idea to turn it on as a 'development default'.
415
416 Many templates, including some of Django's, rely upon the silence of the
417 template system when a nonexistent variable is encountered. If you assign a
418 value other than ``''`` to ``string_if_invalid``, you will experience
419 rendering problems with these templates and sites.
420
421 Generally, ``string_if_invalid`` should only be enabled in order to debug
422 a specific template problem, then cleared once debugging is complete.
423
424 Built-in variables
425 ------------------
426
427 Every context contains ``True``, ``False`` and ``None``. As you would expect,
428 these variables resolve to the corresponding Python objects.
429
430 Limitations with string literals
431 --------------------------------
432
433 Django's template language has no way to escape the characters used for its own
434 syntax. For example, the :ttag:`templatetag` tag is required if you need to
435 output character sequences like ``{%`` and ``%}``.
436
437 A similar issue exists if you want to include these sequences in template filter
438 or tag arguments. For example, when parsing a block tag, Django's template
439 parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents
440 the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError``
441 will be raised for the following expressions:
442
443 .. code-block:: html+django
444
445 {% include "template.html" tvar="Some string literal with %} in it." %}
446
447 {% with tvar="Some string literal with %} in it." %}{% endwith %}
448
449 The same issue can be triggered by using a reserved sequence in filter
450 arguments:
451
452 .. code-block:: html+django
453
454 {{ some.variable|default:"}}" }}
455
456 If you need to use strings with these sequences, store them in template
457 variables or use a custom template tag or filter to workaround the limitation.
458
459 .. _playing-with-context:
460
461 Playing with ``Context`` objects
462 ================================
463
464 Most of the time, you'll instantiate :class:`Context` objects by passing in a
465 fully-populated dictionary to ``Context()``. But you can add and delete items
466 from a ``Context`` object once it's been instantiated, too, using standard
467 dictionary syntax:
468
469 .. code-block:: pycon
470
471 >>> from django.template import Context
472 >>> c = Context({"foo": "bar"})
473 >>> c["foo"]
474 'bar'
475 >>> del c["foo"]
476 >>> c["foo"]
477 Traceback (most recent call last):
478 ...
479 KeyError: 'foo'
480 >>> c["newvariable"] = "hello"
481 >>> c["newvariable"]
482 'hello'
483
484 .. method:: Context.get(key, otherwise=None)
485
486 Returns the value for ``key`` if ``key`` is in the context, else returns
487 ``otherwise``.
488
489 .. method:: Context.setdefault(key, default=None)
490
491 If ``key`` is in the context, returns its value. Otherwise inserts ``key``
492 with a value of ``default`` and returns ``default``.
493
494 .. method:: Context.pop()
495 .. method:: Context.push()
496 .. exception:: ContextPopException
497
498 A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
499 If you ``pop()`` too much, it'll raise
500 ``django.template.ContextPopException``:
501
502 .. code-block:: pycon
503
504 >>> c = Context()
505 >>> c["foo"] = "first level"
506 >>> c.push()
507 {}
508 >>> c["foo"] = "second level"
509 >>> c["foo"]
510 'second level'
511 >>> c.pop()
512 {'foo': 'second level'}
513 >>> c["foo"]
514 'first level'
515 >>> c["foo"] = "overwritten"
516 >>> c["foo"]
517 'overwritten'
518 >>> c.pop()
519 Traceback (most recent call last):
520 ...
521 ContextPopException
522
523 You can also use ``push()`` as a context manager to ensure a matching ``pop()``
524 is called.
525
526 .. code-block:: pycon
527
528 >>> c = Context()
529 >>> c["foo"] = "first level"
530 >>> with c.push():
531 ... c["foo"] = "second level"
532 ... c["foo"]
533 ...
534 'second level'
535 >>> c["foo"]
536 'first level'
537
538 All arguments passed to ``push()`` will be passed to the ``dict`` constructor
539 used to build the new context level.
540
541 .. code-block:: pycon
542
543 >>> c = Context()
544 >>> c["foo"] = "first level"
545 >>> with c.push(foo="second level"):
546 ... c["foo"]
547 ...
548 'second level'
549 >>> c["foo"]
550 'first level'
551
552 .. method:: Context.update(other_dict)
553
554 In addition to ``push()`` and ``pop()``, the ``Context``
555 object also defines an ``update()`` method. This works like ``push()``
556 but takes a dictionary as an argument and pushes that dictionary onto
557 the stack instead of an empty one.
558
559 .. code-block:: pycon
560
561 >>> c = Context()
562 >>> c["foo"] = "first level"
563 >>> c.update({"foo": "updated"})
564 {'foo': 'updated'}
565 >>> c["foo"]
566 'updated'
567 >>> c.pop()
568 {'foo': 'updated'}
569 >>> c["foo"]
570 'first level'
571
572 Like ``push()``, you can use ``update()`` as a context manager to ensure a
573 matching ``pop()`` is called.
574
575 .. code-block:: pycon
576
577 >>> c = Context()
578 >>> c["foo"] = "first level"
579 >>> with c.update({"foo": "second level"}):
580 ... c["foo"]
581 ...
582 'second level'
583 >>> c["foo"]
584 'first level'
585
586 Using a ``Context`` as a stack comes in handy in :ref:`some custom template
587 tags <howto-writing-custom-template-tags>`.
588
589 .. method:: Context.flatten()
590
591 Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary
592 including builtin variables.
593
594 .. code-block:: pycon
595
596 >>> c = Context()
597 >>> c["foo"] = "first level"
598 >>> c.update({"bar": "second level"})
599 {'bar': 'second level'}
600 >>> c.flatten()
601 {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
602
603 A ``flatten()`` method is also internally used to make ``Context`` objects comparable.
604
605 .. code-block:: pycon
606
607 >>> c1 = Context()
608 >>> c1["foo"] = "first level"
609 >>> c1["bar"] = "second level"
610 >>> c2 = Context()
611 >>> c2.update({"bar": "second level", "foo": "first level"})
612 {'foo': 'first level', 'bar': 'second level'}
613 >>> c1 == c2
614 True
615
616 Result from ``flatten()`` can be useful in unit tests to compare ``Context``
617 against ``dict``::
618
619 class ContextTest(unittest.TestCase):
620 def test_against_dictionary(self):
621 c1 = Context()
622 c1["update"] = "value"
623 self.assertEqual(
624 c1.flatten(),
625 {
626 "True": True,
627 "None": None,
628 "False": False,
629 "update": "value",
630 },
631 )
632
633 .. _subclassing-context-requestcontext:
634
635 Using ``RequestContext``
636 ------------------------
637
638 .. class:: RequestContext(request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True)
639
640 Django comes with a special :class:`~django.template.Context` class,
641 ``django.template.RequestContext``, that acts slightly differently from the
642 normal ``django.template.Context``. The first difference is that it takes an
643 :class:`~django.http.HttpRequest` as its first argument. For example::
644
645 c = RequestContext(
646 request,
647 {
648 "foo": "bar",
649 },
650 )
651
652 The second difference is that it automatically populates the context with a
653 few variables, according to the engine's ``context_processors`` configuration
654 option.
655
656 The ``context_processors`` option is a list of callables -- called **context
657 processors** -- that take a request object as their argument and return a
658 dictionary of items to be merged into the context. In the default generated
659 settings file, the default template engine contains the following context
660 processors::
661
662 [
663 "django.template.context_processors.request",
664 "django.contrib.auth.context_processors.auth",
665 "django.contrib.messages.context_processors.messages",
666 ]
667
668 In addition to these, :class:`RequestContext` always enables
669 ``'django.template.context_processors.csrf'``. This is a security related
670 context processor required by the admin and other contrib apps, and, in case
671 of accidental misconfiguration, it is deliberately hardcoded in and cannot be
672 turned off in the ``context_processors`` option.
673
674 Each processor is applied in order. That means, if one processor adds a
675 variable to the context and a second processor adds a variable with the same
676 name, the second will override the first. The default processors are explained
677 below.
678
679 .. admonition:: When context processors are applied
680
681 Context processors are applied on top of context data. This means that a
682 context processor may overwrite variables you've supplied to your
683 :class:`Context` or :class:`RequestContext`, so take care to avoid
684 variable names that overlap with those supplied by your context
685 processors.
686
687 If you want context data to take priority over context processors, use the
688 following pattern::
689
690 from django.template import RequestContext
691
692 request_context = RequestContext(request)
693 request_context.push({"my_name": "Adrian"})
694
695 Django does this to allow context data to override context processors in
696 APIs such as :func:`~django.shortcuts.render` and
697 :class:`~django.template.response.TemplateResponse`.
698
699 Also, you can give :class:`RequestContext` a list of additional processors,
700 using the optional, third positional argument, ``processors``. In this
701 example, the :class:`RequestContext` instance gets an ``ip_address`` variable::
702
703 from django.http import HttpResponse
704 from django.template import RequestContext, Template
705
706
707 def ip_address_processor(request):
708 return {"ip_address": request.META["REMOTE_ADDR"]}
709
710
711 def client_ip_view(request):
712 template = Template("{{ title }}: {{ ip_address }}")
713 context = RequestContext(
714 request,
715 {
716 "title": "Your IP Address",
717 },
718 [ip_address_processor],
719 )
720 return HttpResponse(template.render(context))
721
722 .. _context-processors:
723
724 Built-in template context processors
725 ------------------------------------
726
727 Here's what each of the built-in processors does:
728
729 .. currentmodule:: django.contrib.auth.context_processors
730
731 ``django.contrib.auth.context_processors.auth``
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733
734 .. function:: auth(request)
735
736 If this processor is enabled, every ``RequestContext`` will contain these
737 variables:
738
739 * ``user`` -- An ``auth.User`` instance representing the currently
740 logged-in user (or an ``AnonymousUser`` instance, if the client isn't
741 logged in).
742
743 * ``perms`` -- An instance of
744 ``django.contrib.auth.context_processors.PermWrapper``, representing the
745 permissions that the currently logged-in user has.
746
747 .. currentmodule:: django.template.context_processors
748
749 ``django.template.context_processors.debug``
750 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
751
752 .. function:: debug(request)
753
754 If this processor is enabled, every ``RequestContext`` will contain these two
755 variables -- but only if your :setting:`DEBUG` setting is set to ``True`` and
756 the request's IP address (``request.META['REMOTE_ADDR']``) is in the
757 :setting:`INTERNAL_IPS` setting:
758
759 * ``debug`` -- ``True``. You can use this in templates to test whether
760 you're in :setting:`DEBUG` mode.
761 * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
762 representing every SQL query that has happened so far during the request
763 and how long it took. The list is in order by database alias and then by
764 query. It's lazily generated on access.
765
766 ``django.template.context_processors.i18n``
767 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
768
769 .. function:: i18n(request)
770
771 If this processor is enabled, every ``RequestContext`` will contain these
772 variables:
773
774 * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
775 * ``LANGUAGE_BIDI`` -- ``True`` if the current language is a right-to-left
776 language, e.g. Hebrew, Arabic. ``False`` if it's a left-to-right language,
777 e.g. English, French, German.
778 * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
779 the value of the :setting:`LANGUAGE_CODE` setting.
780
781 See :ref:`i18n template tags <i18n-template-tags>` for template tags that
782 generate the same values.
783
784 ``django.template.context_processors.media``
785 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
786
787 If this processor is enabled, every ``RequestContext`` will contain a variable
788 ``MEDIA_URL``, providing the value of the :setting:`MEDIA_URL` setting.
789
790 ``django.template.context_processors.static``
791 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
792
793 .. function:: static(request)
794
795 If this processor is enabled, every ``RequestContext`` will contain a variable
796 ``STATIC_URL``, providing the value of the :setting:`STATIC_URL` setting.
797
798 ``django.template.context_processors.csrf``
799 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
800
801 This processor adds a token that is needed by the :ttag:`csrf_token` template
802 tag for protection against :doc:`Cross Site Request Forgeries
803 </ref/csrf>`.
804
805 ``django.template.context_processors.request``
806 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
807
808 If this processor is enabled, every ``RequestContext`` will contain a variable
809 ``request``, which is the current :class:`~django.http.HttpRequest`.
810
811 ``django.template.context_processors.tz``
812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
813
814 .. function:: tz(request)
815
816 If this processor is enabled, every ``RequestContext`` will contain a variable
817 ``TIME_ZONE``, providing the name of the currently active time zone.
818
819 ``django.contrib.messages.context_processors.messages``
820 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
821
822 If this processor is enabled, every ``RequestContext`` will contain these two
823 variables:
824
825 * ``messages`` -- A list of messages (as strings) that have been set
826 via the :doc:`messages framework </ref/contrib/messages>`.
827 * ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to
828 :ref:`their numeric value <message-level-constants>`.
829
830 Writing your own context processors
831 -----------------------------------
832
833 A context processor has a simple interface: It's a Python function that takes
834 one argument, an :class:`~django.http.HttpRequest` object, and returns a
835 dictionary that gets added to the template context.
836
837 For example, to add the :setting:`DEFAULT_FROM_EMAIL` setting to every
838 context::
839
840 from django.conf import settings
841
842
843 def from_email(request):
844 return {
845 "DEFAULT_FROM_EMAIL": settings.DEFAULT_FROM_EMAIL,
846 }
847
848 Custom context processors can live anywhere in your code base. All Django
849 cares about is that your custom context processors are pointed to by the
850 ``'context_processors'`` option in your :setting:`TEMPLATES` setting — or the
851 ``context_processors`` argument of :class:`~django.template.Engine` if you're
852 using it directly.
853
854 Loading templates
855 =================
856
857 Generally, you'll store templates in files on your filesystem rather than
858 using the low-level :class:`~django.template.Template` API yourself. Save
859 templates in a directory specified as a **template directory**.
860
861 Django searches for template directories in a number of places, depending on
862 your template loading settings (see "Loader types" below), but the most basic
863 way of specifying template directories is by using the :setting:`DIRS
864 <TEMPLATES-DIRS>` option.
865
866 The :setting:`DIRS <TEMPLATES-DIRS>` option
867 -------------------------------------------
868
869 Tell Django what your template directories are by using the :setting:`DIRS
870 <TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting in your settings
871 file — or the ``dirs`` argument of :class:`~django.template.Engine`. This
872 should be set to a list of strings that contain full paths to your template
873 directories::
874
875 TEMPLATES = [
876 {
877 "BACKEND": "django.template.backends.django.DjangoTemplates",
878 "DIRS": [
879 "/home/html/templates/lawrence.com",
880 "/home/html/templates/default",
881 ],
882 },
883 ]
884
885 Your templates can go anywhere you want, as long as the directories and
886 templates are readable by the web server. They can have any extension you want,
887 such as ``.html`` or ``.txt``, or they can have no extension at all.
888
889 Note that these paths should use Unix-style forward slashes, even on Windows.
890
891 .. _template-loaders:
892
893 Loader types
894 ------------
895
896 By default, Django uses a filesystem-based template loader, but Django comes
897 with a few other template loaders, which know how to load templates from other
898 sources.
899
900 Some of these other loaders are disabled by default, but you can activate them
901 by adding a ``'loaders'`` option to your ``DjangoTemplates`` backend in the
902 :setting:`TEMPLATES` setting or passing a ``loaders`` argument to
903 :class:`~django.template.Engine`. ``loaders`` should be a list of strings or
904 tuples, where each represents a template loader class. Here are the template
905 loaders that come with Django:
906
907 .. currentmodule:: django.template.loaders
908
909 ``django.template.loaders.filesystem.Loader``
910
911 .. class:: filesystem.Loader
912
913 Loads templates from the filesystem, according to
914 :setting:`DIRS <TEMPLATES-DIRS>`.
915
916 This loader is enabled by default. However it won't find any templates
917 until you set :setting:`DIRS <TEMPLATES-DIRS>` to a non-empty list::
918
919 TEMPLATES = [
920 {
921 "BACKEND": "django.template.backends.django.DjangoTemplates",
922 "DIRS": [BASE_DIR / "templates"],
923 }
924 ]
925
926 You can also override ``'DIRS'`` and specify specific directories for a
927 particular filesystem loader::
928
929 TEMPLATES = [
930 {
931 "BACKEND": "django.template.backends.django.DjangoTemplates",
932 "OPTIONS": {
933 "loaders": [
934 (
935 "django.template.loaders.filesystem.Loader",
936 [BASE_DIR / "templates"],
937 ),
938 ],
939 },
940 }
941 ]
942
943 ``django.template.loaders.app_directories.Loader``
944
945 .. class:: app_directories.Loader
946
947 Loads templates from Django apps on the filesystem. For each app in
948 :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
949 subdirectory. If the directory exists, Django looks for templates in there.
950
951 This means you can store templates with your individual apps. This also
952 helps to distribute Django apps with default templates.
953
954 For example, for this setting::
955
956 INSTALLED_APPS = ["myproject.polls", "myproject.music"]
957
958 ...then ``get_template('foo.html')`` will look for ``foo.html`` in these
959 directories, in this order:
960
961 * ``/path/to/myproject/polls/templates/``
962 * ``/path/to/myproject/music/templates/``
963
964 ... and will use the one it finds first.
965
966 The order of :setting:`INSTALLED_APPS` is significant! For example, if you
967 want to customize the Django admin, you might choose to override the
968 standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
969 with your own ``admin/base_site.html`` in ``myproject.polls``. You must
970 then make sure that your ``myproject.polls`` comes *before*
971 ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
972 ``django.contrib.admin``’s will be loaded first and yours will be ignored.
973
974 Note that the loader performs an optimization when it first runs:
975 it caches a list of which :setting:`INSTALLED_APPS` packages have a
976 ``templates`` subdirectory.
977
978 You can enable this loader by setting :setting:`APP_DIRS
979 <TEMPLATES-APP_DIRS>` to ``True``::
980
981 TEMPLATES = [
982 {
983 "BACKEND": "django.template.backends.django.DjangoTemplates",
984 "APP_DIRS": True,
985 }
986 ]
987
988 ``django.template.loaders.cached.Loader``
989
990 .. class:: cached.Loader
991
992 While the Django template system is quite fast, if it needs to read and
993 compile your templates every time they're rendered, the overhead from that
994 can add up.
995
996 You configure the cached template loader with a list of other loaders that
997 it should wrap. The wrapped loaders are used to locate unknown templates
998 when they're first encountered. The cached loader then stores the compiled
999 ``Template`` in memory. The cached ``Template`` instance is returned for
1000 subsequent requests to load the same template.
1001
1002 This loader is automatically enabled if :setting:`OPTIONS['loaders']
1003 <TEMPLATES-OPTIONS>` isn't specified.
1004
1005 You can manually specify template caching with some custom template loaders
1006 using settings like this::
1007
1008 TEMPLATES = [
1009 {
1010 "BACKEND": "django.template.backends.django.DjangoTemplates",
1011 "DIRS": [BASE_DIR / "templates"],
1012 "OPTIONS": {
1013 "loaders": [
1014 (
1015 "django.template.loaders.cached.Loader",
1016 [
1017 "django.template.loaders.filesystem.Loader",
1018 "django.template.loaders.app_directories.Loader",
1019 "path.to.custom.Loader",
1020 ],
1021 ),
1022 ],
1023 },
1024 }
1025 ]
1026
1027 .. note::
1028
1029 All of the built-in Django template tags are safe to use with the
1030 cached loader, but if you're using custom template tags that come from
1031 third party packages, or that you wrote yourself, you should ensure
1032 that the ``Node`` implementation for each tag is thread-safe. For more
1033 information, see :ref:`template tag thread safety considerations
1034 <template_tag_thread_safety>`.
1035
1036 ``django.template.loaders.locmem.Loader``
1037
1038 .. class:: locmem.Loader
1039
1040 Loads templates from a Python dictionary. This is useful for testing.
1041
1042 This loader takes a dictionary of templates as its first argument::
1043
1044 TEMPLATES = [
1045 {
1046 "BACKEND": "django.template.backends.django.DjangoTemplates",
1047 "OPTIONS": {
1048 "loaders": [
1049 (
1050 "django.template.loaders.locmem.Loader",
1051 {
1052 "index.html": "content here",
1053 },
1054 ),
1055 ],
1056 },
1057 }
1058 ]
1059
1060 This loader is disabled by default.
1061
1062 Django uses the template loaders in order according to the ``'loaders'``
1063 option. It uses each loader until a loader finds a match.
1064
1065 .. _custom-template-loaders:
1066
1067 .. currentmodule:: django.template.loaders.base
1068
1069 Custom loaders
1070 ==============
1071
1072 It's possible to load templates from additional sources using custom template
1073 loaders. Custom ``Loader`` classes should inherit from
1074 ``django.template.loaders.base.Loader`` and define the ``get_contents()`` and
1075 ``get_template_sources()`` methods.
1076
1077 Loader methods
1078 --------------
1079
1080 .. class:: Loader
1081
1082 Loads templates from a given source, such as the filesystem or a database.
1083
1084 .. method:: get_template_sources(template_name)
1085
1086 A method that takes a ``template_name`` and yields
1087 :class:`~django.template.base.Origin` instances for each possible
1088 source.
1089
1090 For example, the filesystem loader may receive ``'index.html'`` as a
1091 ``template_name`` argument. This method would yield origins for the
1092 full path of ``index.html`` as it appears in each template directory
1093 the loader looks at.
1094
1095 The method doesn't need to verify that the template exists at a given
1096 path, but it should ensure the path is valid. For instance, the
1097 filesystem loader makes sure the path lies under a valid template
1098 directory.
1099
1100 .. method:: get_contents(origin)
1101
1102 Returns the contents for a template given a
1103 :class:`~django.template.base.Origin` instance.
1104
1105 This is where a filesystem loader would read contents from the
1106 filesystem, or a database loader would read from the database. If a
1107 matching template doesn't exist, this should raise a
1108 :exc:`~django.template.TemplateDoesNotExist` error.
1109
1110 .. method:: get_template(template_name, skip=None)
1111
1112 Returns a ``Template`` object for a given ``template_name`` by looping
1113 through results from :meth:`get_template_sources` and calling
1114 :meth:`get_contents`. This returns the first matching template. If no
1115 template is found, :exc:`~django.template.TemplateDoesNotExist` is
1116 raised.
1117
1118 The optional ``skip`` argument is a list of origins to ignore when
1119 extending templates. This allow templates to extend other templates of
1120 the same name. It also used to avoid recursion errors.
1121
1122 In general, it is enough to define :meth:`get_template_sources` and
1123 :meth:`get_contents` for custom template loaders. ``get_template()``
1124 will usually not need to be overridden.
1125
1126 .. admonition:: Building your own
1127
1128 For examples, read the :source:`source code for Django's built-in loaders
1129 <django/template/loaders>`.
1130
1131 .. currentmodule:: django.template.base
1132
1133 Template origin
1134 ===============
1135
1136 Templates have an ``origin`` containing attributes depending on the source
1137 they are loaded from.
1138
1139 .. class:: Origin(name, template_name=None, loader=None)
1140
1141 .. attribute:: name
1142
1143 The path to the template as returned by the template loader.
1144 For loaders that read from the file system, this is the full
1145 path to the template.
1146
1147 If the template is instantiated directly rather than through a
1148 template loader, this is a string value of ``<unknown_source>``.
1149
1150 .. attribute:: template_name
1151
1152 The relative path to the template as passed into the
1153 template loader.
1154
1155 If the template is instantiated directly rather than through a
1156 template loader, this is ``None``.
1157
1158 .. attribute:: loader
1159
1160 The template loader instance that constructed this ``Origin``.
1161
1162 If the template is instantiated directly rather than through a
1163 template loader, this is ``None``.
1164
1165 :class:`django.template.loaders.cached.Loader` requires all of its
1166 wrapped loaders to set this attribute, typically by instantiating
1167 the ``Origin`` with ``loader=self``.