The Django template language: for Python programmers¶
This document explains the Django template system from a technical perspective – how it works and how to extend it. If you’re just looking for reference on the language syntax, see The Django template language.
It assumes an understanding of templates, contexts, variables, tags, and rendering. Start with the introduction to the Django template language if you aren’t familiar with these concepts.
Overview¶
Using the template system in Python is a three-step process:
- You configure an
Engine. - You compile template code into a
Template. - You render the template with a
Context.
Django projects generally rely on the high level, backend agnostic APIs for each of these steps instead of the template system’s lower level APIs:
- For each
DjangoTemplatesbackend in theTEMPLATESsetting, Django instantiates anEngine.DjangoTemplateswrapsEngineand adapts it to the common template backend API. - The
django.template.loadermodule provides functions such asget_template()for loading templates. They return adjango.template.backends.django.Templatewhich wraps the actualdjango.template.Template. - The
Templateobtained in the previous step has arender()method which marshals a context and possibly a request into aContextand delegates the rendering to the underlyingTemplate.
Configuring an engine¶
If you are simply using the
DjangoTemplates backend, this
probably isn’t the documentation you’re looking for. An instance of the
Engine class described below is accessible using the engine attribute
of that backend and any attribute defaults mentioned below are overridden by
what’s passed by DjangoTemplates.
-
class
Engine(dirs=None, app_dirs=False, allowed_include_roots=None, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8')[source]¶ - New in Django 1.8.
When instantiating an
Engineall arguments must be passed as keyword arguments:dirsis a list of directories where the engine should look for template source files. It is used to configurefilesystem.Loader.It defaults to an empty list.
app_dirsonly affects the default value ofloaders. See below.It defaults to
False.allowed_include_rootsis a list of strings representing allowed prefixes for the{% ssi %}template tag. This is a security measure, so that template authors can’t access files that they shouldn’t be accessing.For example, if
'allowed_include_roots'is['/home/html', '/var/www'], then{% ssi /home/html/foo.txt %}would work, but{% ssi /etc/passwd %}wouldn’t.It defaults to an empty list.
Deprecated since version 1.8:
allowed_include_rootsis deprecated.context_processorsis a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return adictof items to be merged into the context.It defaults to an empty list.
See
RequestContextfor more information.debugis a boolean that turns on/off template debug mode. If it isTrue, the template engine will store additional debug information which can be used to display a detailed report for any exception raised during template rendering.It defaults to
False.loadersis a list of template loader classes, specified as strings. EachLoaderclass knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be theLoaderclass name, subsequent items are passed to theLoaderduring initialization.It defaults to a list containing:
'django.template.loaders.filesystem.Loader''django.template.loaders.app_directories.Loader'if and only ifapp_dirsisTrue.
See Loader types for details.
string_if_invalidis the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.It defaults to the empty string.
See How invalid variables are handled for details.
file_charsetis the charset used to read template files on disk.It defaults to
'utf-8'.
-
static
Engine.get_default()[source]¶ When a Django project configures one and only one
DjangoTemplatesengine, this method returns the underlyingEngine. In other circumstances it will raiseImproperlyConfigured.It’s required for preserving APIs that rely on a globally available, implicitly configured engine. Any other use is strongly discouraged.
-
Engine.from_string(template_code)[source]¶ Compiles the given template code and returns a
Templateobject.
-
Engine.get_template(template_name)[source]¶ Loads a template with the given name, compiles it and returns a
Templateobject.
-
Engine.select_template(self, template_name_list)[source]¶ Like
get_template(), except it takes a list of names and returns the first template that was found.
Loading a template¶
The recommended way to create a Template is by calling the factory
methods of the Engine: get_template(),
select_template() and from_string().
In a Django project where the TEMPLATES setting defines exactly one
DjangoTemplates engine, it’s
possible to instantiate a Template directly.
-
class
Template[source]¶ This class lives at
django.template.Template. The constructor takes one argument — the raw template code:from django.template import Template template = Template("My name is {{ my_name }}.")
Behind the scenes
The system only parses your raw template code once – when you create the
Template object. From then on, it’s stored internally as a tree
structure for performance.
Even the parsing itself is quite fast. Most of the parsing happens via a single call to a single, short, regular expression.
Rendering a context¶
Once you have a compiled Template object, you can render a context
with it. You can reuse the same template to render it several times with
different contexts.
-
class
Context(dict_=None, current_app=_current_app_undefined)[source]¶ This class lives at
django.template.Context. The constructor takes two optional arguments:A dictionary mapping variable names to variable values.
The name of the current application. This application name is used to help resolve namespaced URLs. If you’re not using namespaced URLs, you can ignore this argument.
Deprecated since version 1.8: The
current_appargument is deprecated. If you need it, you must now use aRequestContextinstead of aContext.
For details, see Playing with Context objects below.
-
Template.render(context)[source]¶ Call the
Templateobject’srender()method with aContextto “fill” the template:>>> from django.template import Context, Template >>> template = Template("My name is {{ my_name }}.") >>> context = Context({"my_name": "Adrian"}) >>> template.render(context) "My name is Adrian." >>> context = Context({"my_name": "Dolores"}) >>> template.render(context) "My name is Dolores."
Variables and lookups¶
Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.
Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
- Dictionary lookup. Example:
foo["bar"] - Attribute lookup. Example:
foo.bar - List-index lookup. Example:
foo[bar]
Note that “bar” in a template expression like {{ foo.bar }} will be
interpreted as a literal string and not using the value of the variable “bar”,
if one exists in the template context.
The template system uses the first lookup type that works. It’s short-circuit logic. Here are a few examples:
>>> from django.template import Context, Template
>>> t = Template("My name is {{ person.first_name }}.")
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
>>> t.render(Context(d))
"My name is Joe."
>>> class PersonClass: pass
>>> p = PersonClass()
>>> p.first_name = "Ron"
>>> p.last_name = "Nasty"
>>> t.render(Context({"person": p}))
"My name is Ron."
>>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
>>> t.render(c)
"The first stooge in the list is Larry."
If any part of the variable is callable, the template system will try calling it. Example:
>>> class PersonClass2:
... def name(self):
... return "Samantha"
>>> t = Template("My name is {{ person.name }}.")
>>> t.render(Context({"person": PersonClass2}))
"My name is Samantha."
Callable variables are slightly more complex than variables which only require straight lookups. Here are some things to keep in mind:
If the variable raises an exception when called, the exception will be propagated, unless the exception has an attribute
silent_variable_failurewhose value isTrue. If the exception does have asilent_variable_failureattribute whose value isTrue, the variable will render as the value of the engine’sstring_if_invalidconfiguration option (an empty string, by default). Example:>>> t = Template("My name is {{ person.first_name }}.") >>> class PersonClass3: ... def first_name(self): ... raise AssertionError("foo") >>> p = PersonClass3() >>> t.render(Context({"person": p})) Traceback (most recent call last): ... AssertionError: foo >>> class SilentAssertionError(Exception): ... silent_variable_failure = True >>> class PersonClass4: ... def first_name(self): ... raise SilentAssertionError >>> p = PersonClass4() >>> t.render(Context({"person": p})) "My name is ."
Note that
django.core.exceptions.ObjectDoesNotExist, which is the base class for all Django database APIDoesNotExistexceptions, hassilent_variable_failure = True. So if you’re using Django templates with Django model objects, anyDoesNotExistexception will fail silently.A variable can only be called if it has no required arguments. Otherwise, the system will return the value of the engine’s
string_if_invalidoption.
Obviously, there can be side effects when calling some variables, and it’d be either foolish or a security hole to allow the template system to access them.
A good example is the
delete()method on each Django model object. The template system shouldn’t be allowed to do something like this:I will now delete this valuable data. {{ data.delete }}
To prevent this, set an
alters_dataattribute on the callable variable. The template system won’t call a variable if it hasalters_data=Trueset, and will instead replace the variable withstring_if_invalid, unconditionally. The dynamically-generateddelete()andsave()methods on Django model objects getalters_data=Trueautomatically. Example:def sensitive_function(self): self.database_record.delete() sensitive_function.alters_data = True
Occasionally you may want to turn off this feature for other reasons, and tell the template system to leave a variable uncalled no matter what. To do so, set a
do_not_call_in_templatesattribute on the callable with the valueTrue. The template system then will act as if your variable is not callable (allowing you to access attributes of the callable, for example).
How invalid variables are handled¶
Generally, if a variable doesn’t exist, the template system inserts the value
of the engine’s string_if_invalid configuration option, which is set to
'' (the empty string) by default.
Filters that are applied to an invalid variable will only be applied if
string_if_invalid is set to '' (the empty string). If
string_if_invalid is set to any other value, variable filters will be
ignored.
This behavior is slightly different for the if, for and regroup
template tags. If an invalid variable is provided to one of these template
tags, the variable will be interpreted as None. Filters are always
applied to invalid variables within these template tags.
If string_if_invalid contains a '%s', the format marker will be
replaced with the name of the invalid variable.
For debug purposes only!
While string_if_invalid can be a useful debugging tool, it is a bad
idea to turn it on as a ‘development default’.
Many templates, including those in the Admin site, rely upon the silence
of the template system when a non-existent variable is encountered. If you
assign a value other than '' to string_if_invalid, you will
experience rendering problems with these templates and sites.
Generally, string_if_invalid should only be enabled in order to debug
a specific template problem, then cleared once debugging is complete.
Built-in variables¶
Every context contains True, False and None. As you would expect,
these variables resolve to the corresponding Python objects.
Limitations with string literals¶
Django’s template language has no way to escape the characters used for its own
syntax. For example, the templatetag tag is required if you need to
output character sequences like {% and %}.
A similar issue exists if you want to include these sequences in template filter
or tag arguments. For example, when parsing a block tag, Django’s template
parser looks for the first occurrence of %} after a {%. This prevents
the use of "%}" as a string literal. For example, a TemplateSyntaxError
will be raised for the following expressions:
{% include "template.html" tvar="Some string literal with %} in it." %}
{% with tvar="Some string literal with %} in it." %}{% endwith %}
The same issue can be triggered by using a reserved sequence in filter arguments:
{{ some.variable|default:"}}" }}
If you need to use strings with these sequences, store them in template variables or use a custom template tag or filter to workaround the limitation.
Playing with Context objects¶
Most of the time, you’ll instantiate Context objects by passing in a
fully-populated dictionary to Context(). But you can add and delete items
from a Context object once it’s been instantiated, too, using standard
dictionary syntax:
>>> from django.template import Context
>>> c = Context({"foo": "bar"})
>>> c['foo']
'bar'
>>> del c['foo']
>>> c['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
>>> c['newvariable'] = 'hello'
>>> c['newvariable']
'hello'
-
Context.get(key, otherwise=None)¶ Returns the value for
keyifkeyis in the context, else returnsotherwise.
-
Context.pop()¶
-
Context.push()¶
A Context object is a stack. That is, you can push() and pop() it.
If you pop() too much, it’ll raise
django.template.ContextPopException:
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.push()
{}
>>> c['foo'] = 'second level'
>>> c['foo']
'second level'
>>> c.pop()
{'foo': 'second level'}
>>> c['foo']
'first level'
>>> c['foo'] = 'overwritten'
>>> c['foo']
'overwritten'
>>> c.pop()
Traceback (most recent call last):
...
ContextPopException
You can also use push() as a context manager to ensure a matching pop()
is called.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.push():
... c['foo'] = 'second level'
... c['foo']
'second level'
>>> c['foo']
'first level'
All arguments passed to push() will be passed to the dict constructor
used to build the new context level.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.push(foo='second level'):
... c['foo']
'second level'
>>> c['foo']
'first level'
In addition to push() and pop(), the Context
object also defines an update() method. This works like push()
but takes a dictionary as an argument and pushes that dictionary onto
the stack instead of an empty one.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'foo': 'updated'})
{'foo': 'updated'}
>>> c['foo']
'updated'
>>> c.pop()
{'foo': 'updated'}
>>> c['foo']
'first level'
Using a Context as a stack comes in handy in some custom template
tags.
-
Context.flatten()¶
Using flatten() method you can get whole Context stack as one dictionary
including builtin variables.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'bar': 'second level'})
{'bar': 'second level'}
>>> c.flatten()
{'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
A flatten() method is also internally used to make Context objects comparable.
>>> c1 = Context()
>>> c1['foo'] = 'first level'
>>> c1['bar'] = 'second level'
>>> c2 = Context()
>>> c2.update({'bar': 'second level', 'foo': 'first level'})
{'foo': 'first level', 'bar': 'second level'}
>>> c1 == c2
True
Result from flatten() can be useful in unit tests to compare Context
against dict:
class ContextTest(unittest.TestCase):
def test_against_dictionary(self):
c1 = Context()
c1['update'] = 'value'
self.assertEqual(c1.flatten(), {
'True': True,
'None': None,
'False': False,
'update': 'value',
})
Subclassing Context: RequestContext¶
Django comes with a special Context class,
django.template.RequestContext, that acts slightly differently from the
normal django.template.Context. The first difference is that it takes an
HttpRequest as its first argument. For example:
c = RequestContext(request, {
'foo': 'bar',
})
The second difference is that it automatically populates the context with a
few variables, according to the engine’s context_processors configuration
option.
The context_processors option is a list of callables – called context
processors – that take a request object as their argument and return a
dictionary of items to be merged into the context. In the default generated
settings file, the default template engine contains the following context
processors:
[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
Built-in template context processors were moved from
django.core.context_processors to
django.template.context_processors in Django 1.8.
In addition to these, RequestContext always enables
'django.template.context_processors.csrf'. This is a security related
context processor required by the admin and other contrib apps, and, in case
of accidental misconfiguration, it is deliberately hardcoded in and cannot be
turned off in the context_processors option.
Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained below.
When context processors are applied
Context processors are applied on top of context data. This means that a
context processor may overwrite variables you’ve supplied to your
Context or RequestContext, so take care to avoid
variable names that overlap with those supplied by your context
processors.
If you want context data to take priority over context processors, use the following pattern:
from django.template import RequestContext
request_context = RequestContext(request)
request_context.push({"my_name": "Adrian"})
Django does this to allow context data to override context processors in
APIs such as render() and
TemplateResponse.
Also, you can give RequestContext a list of additional processors,
using the optional, third positional argument, processors. In this
example, the RequestContext instance gets a ip_address variable:
from django.http import HttpResponse
from django.template import RequestContext
def ip_address_processor(request):
return {'ip_address': request.META['REMOTE_ADDR']}
def some_view(request):
# ...
c = RequestContext(request, {
'foo': 'bar',
}, [ip_address_processor])
return HttpResponse(t.render(c))
Built-in template context processors¶
Here’s what each of the built-in processors does:
django.contrib.auth.context_processors.auth¶
If this processor is enabled, every RequestContext will contain these
variables:
user– Anauth.Userinstance representing the currently logged-in user (or anAnonymousUserinstance, if the client isn’t logged in).perms– An instance ofdjango.contrib.auth.context_processors.PermWrapper, representing the permissions that the currently logged-in user has.
django.template.context_processors.debug¶
If this processor is enabled, every RequestContext will contain these two
variables – but only if your DEBUG setting is set to True and
the request’s IP address (request.META['REMOTE_ADDR']) is in the
INTERNAL_IPS setting:
debug–True. You can use this in templates to test whether you’re inDEBUGmode.sql_queries– A list of{'sql': ..., 'time': ...}dictionaries, representing every SQL query that has happened so far during the request and how long it took. The list is in order by query and lazily generated on access.
django.template.context_processors.i18n¶
If this processor is enabled, every RequestContext will contain these two
variables:
LANGUAGES– The value of theLANGUAGESsetting.LANGUAGE_CODE–request.LANGUAGE_CODE, if it exists. Otherwise, the value of theLANGUAGE_CODEsetting.
See Internationalization and localization for more.
django.template.context_processors.media¶
If this processor is enabled, every RequestContext will contain a variable
MEDIA_URL, providing the value of the MEDIA_URL setting.
django.template.context_processors.static¶
If this processor is enabled, every RequestContext will contain a variable
STATIC_URL, providing the value of the STATIC_URL setting.
django.template.context_processors.csrf¶
This processor adds a token that is needed by the csrf_token template
tag for protection against Cross Site Request Forgeries.
django.template.context_processors.request¶
If this processor is enabled, every RequestContext will contain a variable
request, which is the current HttpRequest.
django.contrib.messages.context_processors.messages¶
If this processor is enabled, every RequestContext will contain these two
variables:
messages– A list of messages (as strings) that have been set via the messages framework.DEFAULT_MESSAGE_LEVELS– A mapping of the message level names to their numeric value.
The DEFAULT_MESSAGE_LEVELS variable was added.
Writing your own context processors¶
A context processor has a very simple interface: It’s just a Python function
that takes one argument, an HttpRequest object, and
returns a dictionary that gets added to the template context. Each context
processor must return a dictionary.
Custom context processors can live anywhere in your code base. All Django
cares about is that your custom context processors are pointed to by the
'context_processors' option in your TEMPLATES setting — or the
context_processors argument of Engine if you’re
using it directly.
Loading templates¶
Generally, you’ll store templates in files on your filesystem rather than
using the low-level Template API yourself. Save
templates in a directory specified as a template directory.
Django searches for template directories in a number of places, depending on
your template loading settings (see “Loader types” below), but the most basic
way of specifying template directories is by using the DIRS option.
The DIRS option¶
This value used to be defined by the TEMPLATE_DIRS setting.
Tell Django what your template directories are by using the DIRS option in the TEMPLATES setting in your settings
file — or the dirs argument of Engine. This
should be set to a list of strings that contain full paths to your template
directories:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/home/html/templates/lawrence.com',
'/home/html/templates/default',
],
},
]
Your templates can go anywhere you want, as long as the directories and
templates are readable by the Web server. They can have any extension you want,
such as .html or .txt, or they can have no extension at all.
Note that these paths should use Unix-style forward slashes, even on Windows.
Loader types¶
By default, Django uses a filesystem-based template loader, but Django comes with a few other template loaders, which know how to load templates from other sources.
Some of these other loaders are disabled by default, but you can activate them
by adding a 'loaders' option to your DjangoTemplates backend in the
TEMPLATES setting or passing a loaders argument to
Engine. loaders should be a list of strings or
tuples, where each represents a template loader class. Here are the template
loaders that come with Django:
django.template.loaders.filesystem.Loader
-
class
filesystem.Loader¶ Loads templates from the filesystem, according to
DIRS.This loader is enabled by default. However it won’t find any templates until you set
DIRSto a non-empty list:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], }]
django.template.loaders.app_directories.Loader
-
class
app_directories.Loader¶ Loads templates from Django apps on the filesystem. For each app in
INSTALLED_APPS, the loader looks for atemplatessubdirectory. If the directory exists, Django looks for templates in there.This means you can store templates with your individual apps. This also makes it easy to distribute Django apps with default templates.
For example, for this setting:
INSTALLED_APPS = ('myproject.polls', 'myproject.music')
…then
get_template('foo.html')will look forfoo.htmlin these directories, in this order:/path/to/myproject/polls/templates//path/to/myproject/music/templates/
… and will use the one it finds first.
The order of
INSTALLED_APPSis significant! For example, if you want to customize the Django admin, you might choose to override the standardadmin/base_site.htmltemplate, fromdjango.contrib.admin, with your ownadmin/base_site.htmlinmyproject.polls. You must then make sure that yourmyproject.pollscomes beforedjango.contrib.admininINSTALLED_APPS, otherwisedjango.contrib.admin’s will be loaded first and yours will be ignored.Note that the loader performs an optimization when it first runs: it caches a list of which
INSTALLED_APPSpackages have atemplatessubdirectory.You can enable this loader simply by setting
APP_DIRStoTrue:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }]
django.template.loaders.eggs.Loader
-
class
eggs.Loader¶ Just like
app_directoriesabove, but it loads templates from Python eggs rather than from the filesystem.This loader is disabled by default.
django.template.loaders.cached.Loader
-
class
cached.Loader¶ By default, the templating system will read and compile your templates every time they need to be rendered. While the Django templating system is quite fast, the overhead from reading and compiling templates can add up.
The cached template loader is a class-based loader that you configure with a list of other loaders that it should wrap. The wrapped loaders are used to locate unknown templates when they are first encountered. The cached loader then stores the compiled
Templatein memory. The cachedTemplateinstance is returned for subsequent requests to load the same template.For example, to enable template caching with the
filesystemandapp_directoriestemplate loaders you might use the following settings:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ], }, }]
Note
All of the built-in Django template tags are safe to use with the cached loader, but if you’re using custom template tags that come from third party packages, or that you wrote yourself, you should ensure that the
Nodeimplementation for each tag is thread-safe. For more information, see template tag thread safety considerations.This loader is disabled by default.
django.template.loaders.locmem.Loader
-
class
locmem.Loader¶ Loads templates from a Python dictionary. This is useful for testing.
This loader takes a dictionary of templates as its first argument:
TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { 'index.html': 'content here', }), ], }, }]
This loader is disabled by default.
Django uses the template loaders in order according to the 'loaders'
option. It uses each loader until a loader finds a match.
Custom loaders¶
Custom Loader classes should inherit from
django.template.loaders.base.Loader and override the
load_template_source() method, which takes a template_name argument,
loads the template from disk (or elsewhere), and returns a tuple:
(template_string, template_origin).
django.template.loaders.base.Loader used to be defined at
django.template.loader.BaseLoader.
The load_template() method of the Loader class retrieves the template
string by calling load_template_source(), instantiates a Template from
the template source, and returns a tuple: (template, template_origin).
Template origin¶
When an Engine is initialized with debug=True,
its templates have an origin attribute depending on the source they are
loaded from. For engines initialized by Django, debug defaults to the
value of DEBUG.
-
class
loader.LoaderOrigin¶ Templates created from a template loader will use the
django.template.loader.LoaderOriginclass.-
name¶ The path to the template as returned by the template loader. For loaders that read from the file system, this is the full path to the template.
-
loadname¶ The relative path to the template as passed into the template loader.
-