This document describes Django’s built-in template tags and filters. It is
recommended that you use the automatic documentation, if available, as this will also include
documentation for any custom tags or filters installed.

Controls the current auto-escaping behavior. This tag takes either on or
off as an argument and that determines whether auto-escaping is in effect
inside the block. The block is closed with an endautoescape ending tag.

When auto-escaping is in effect, all variable content has HTML escaping applied
to it before placing the result into the output (but after any filters have
been applied). This is equivalent to manually applying the escape
filter to each variable.

The only exceptions are variables that are already marked as “safe” from
escaping, either by the code that populated the variable, or because it has had
the safe or escape filters applied.

Ignores everything between {%comment%} and {%endcomment%}.
An optional note may be inserted in the first tag. For example, this is
useful when commenting out code for documenting why the code was disabled.

Sample usage:

<p>Rendered text with {{pub_date|date:"c"}}</p>{%comment"Optional note"%}<p>Commented out text with {{create_date|date:"c"}}</p>{%endcomment%}

Produces one of its arguments each time this tag is encountered. The first
argument is produced on the first encounter, the second argument on the second
encounter, and so forth. Once all arguments are exhausted, the tag cycles to
the first argument and produces it again.

Note that the variables included in the cycle will not be escaped. Any HTML or
Javascript code contained in the printed variable will be rendered as-is, which
could potentially lead to security issues. So either make sure that you trust
their values or use explicit escaping like this:

In some cases you might want to refer to the current value of a cycle
without advancing to the next value. To do this,
just give the {%cycle%} tag a name, using “as”, like this:

{%cycle'row1''row2'asrowcolors%}

From then on, you can insert the current value of the cycle wherever you’d like
in your template by referencing the cycle name as a context variable. If you
want to move the cycle to the next value independently of the original
cycle tag, you can use another cycle tag and specify the name of the
variable. So, the following template:

You can use any number of values in a cycle tag, separated by spaces.
Values enclosed in single quotes (') or double quotes (") are treated
as string literals, while values without quotes are treated as template
variables.

By default, when you use the as keyword with the cycle tag, the
usage of {%cycle%} that initiates the cycle will itself produce
the first value in the cycle. This could be a problem if you want to
use the value in a nested loop or an included template. If you only want
to declare the cycle but not produce the first value, you can add a
silent keyword as the last keyword in the tag. For example:

This will output a list of <tr> elements with class
alternating between row1 and row2. The subtemplate will have
access to rowcolors in its context and the value will match the class
of the <tr> that encloses it. If the silent keyword were to be
omitted, row1 and row2 would be emitted as normal text, outside the
<tr> element.

When the silent keyword is used on a cycle definition, the silence
automatically applies to all subsequent uses of that specific cycle tag.
The following template would output nothing, even though the second
call to {%cycle%} doesn’t specify silent:

{%cycle'row1''row2'asrowcolorssilent%}{%cyclerowcolors%}

For backward compatibility, the {%cycle%} tag supports the much inferior
old syntax from previous Django versions. You shouldn’t use this in any new
projects, but for the sake of the people who are still using it, here’s what it
looks like:

{%cyclerow1,row2,row3%}

In this syntax, each value gets interpreted as a literal string, and there’s no
way to specify variable values. Or literal commas. Or spaces. Did we mention
you shouldn’t use this syntax in any new projects?

Changed in Django 1.6.

To improve safety, future versions of cycle will automatically escape
their output. You’re encouraged to activate this behavior by loading
cycle from the future template library:

{%extends"base.html"%} (with quotes) uses the literal value
"base.html" as the name of the parent template to extend.

{%extendsvariable%} uses the value of variable. If the variable
evaluates to a string, Django will use that string as the name of the
parent template. If the variable evaluates to a Template object,
Django will use that object as the parent template.

You can also use a literal string as a fallback value in case all
passed variables are False:

{%firstofvar1var2var3"fallback value"%}

Note that currently the variables included in the firstof tag will not be
escaped. Any HTML or Javascript code contained in the printed variable will be
rendered as-is, which could potentially lead to security issues. If you need
to escape the variables in the firstof tag, you must do so explicitly:

You can loop over a list in reverse by using
{%forobjinlistreversed%}.

If you need to loop over a list of lists, you can unpack the values
in each sublist into individual variables. For example, if your context
contains a list of (x,y) coordinates called points, you could use the
following to output the list of points:

{%forx,yinpoints%}
There is a point at {{x}},{{y}}{%endfor%}

This can also be useful if you need to access the items in a dictionary.
For example, if your context contained a dictionary data, the following
would display the keys and values of the dictionary:

if tags may use and, or or not to test a number of
variables or to negate a given variable:

{%ifathlete_listandcoach_list%}
Both athletes and coaches are available.
{%endif%}{%ifnotathlete_list%}
There are no athletes.
{%endif%}{%ifathlete_listorcoach_list%}
There are some athletes or some coaches.
{%endif%}{%ifnotathlete_listorcoach_list%}
There are no athletes or there are some coaches (OK, so
writing English translations of boolean logic sounds
stupid; it's not our fault).
{%endif%}{%ifathlete_listandnotcoach_list%}
There are some athletes and absolutely no coaches.
{%endif%}

Use of both and and or clauses within the same tag is allowed, with
and having higher precedence than or e.g.:

{%ifathlete_listandcoach_listorcheerleader_list%}

will be interpreted like:

if(athlete_listandcoach_list)orcheerleader_list

Use of actual parentheses in the if tag is invalid syntax. If you need
them to indicate precedence, you should use nested if tags.

if tags may also use the operators ==, !=, <, >,
<=, >= and in which work as follows:

Contained within. This operator is supported by many Python containers to test
whether the given value is in the container. The following are some examples
of how xiny will be interpreted:

{%if"bc"in"abcdef"%}
This appears since "bc" is a substring of "abcdef"
{%endif%}{%if"hello"ingreetings%}
If greetings is a list or set, one element of which is the string
"hello", this will appear.
{%endif%}{%ifuserinusers%}
If users is a QuerySet, this will appear if user is an
instance that belongs to the QuerySet.
{%endif%}

All of the above can be combined to form complex expressions. For such
expressions, it can be important to know how the operators are grouped when the
expression is evaluated - that is, the precedence rules. The precedence of the
operators, from lowest to highest, is as follows:

or

and

not

in

==, !=, <, >, <=, >=

(This follows Python exactly). So, for example, the following complex
if tag:

{%ifa==borc==dande%}

...will be interpreted as:

(a==b)or((c==d)ande)

If you need different precedence, you will need to use nested if tags.
Sometimes that is better for clarity anyway, for the sake of those who do not
know the precedence rules.

The {%ifchanged%} block tag is used within a loop. It has two possible
uses.

Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a list of
days, only displaying the month if it changes:

<h1>Archive for {{year}}</h1>{%fordateindays%}{%ifchanged%}<h3>{{date|date:"F"}}</h3>{%endifchanged%}<ahref="{{date|date:"M/d"|lower}}/">{{date|date:"j"}}</a>{%endfor%}

If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
showing the hour if either the hour or the date has changed:

Loads a template and renders it with the current context. This is a way of
“including” other templates within a template.

The template name can either be a variable or a hard-coded (quoted) string,
in either single or double quotes.

This example includes the contents of the template "foo/bar.html":

{%include"foo/bar.html"%}

This example includes the contents of the template whose name is contained in
the variable template_name:

{%includetemplate_name%}

Changed in Django 1.7:

The variable may also be any object with a render() method that
accepts a context. This allows you to reference a compiled Template in
your context.

An included template is rendered within the context of the template that
includes it. This example produces the output "Hello,John!":

Context: variable person is set to "John" and variable greeting
is set to "Hello".

Template:

{%include"name_snippet.html"%}

The name_snippet.html template:

{{greeting}}, {{person|default:"friend"}}!

You can pass additional context to the template using keyword arguments:

{%include"name_snippet.html"withperson="Jane"greeting="Hello"%}

If you want to render the context only with the variables provided (or even
no variables at all), use the only option. No other variables are
available to the included template:

{%include"name_snippet.html"withgreeting="Hi"only%}

Note

The include tag should be considered as an implementation of
“render this subtemplate and include the HTML”, not as “parse this
subtemplate and include its contents as if it were part of the parent”.
This means that there is no shared state between included templates –
each include is a completely independent rendering process.

Blocks are evaluated before they are included. This means that a template
that includes blocks from another will contain blocks that have already
been evaluated and rendered - not blocks that can be overridden by, for
example, an extending template.

Displays the current date and/or time, using a format according to the given
string. Such string can contain format specifiers characters as described
in the date filter section.

Example:

It is {%now"jS F Y H:i"%}

Note that you can backslash-escape a format string if you want to use the
“raw” value. In this example, both “o” and “f” are backslash-escaped, because
otherwise each is a format string that displays the year and the time,
respectively:

Let’s walk through this example. {%regroup%} takes three arguments: the
list you want to regroup, the attribute to group by, and the name of the
resulting list. Here, we’re regrouping the cities list by the country
attribute and calling the result country_list.

{%regroup%} produces a list (in this case, country_list) of
group objects. Each group object has two attributes:

grouper – the item that was grouped by (e.g., the string “India” or
“Japan”).

list – a list of all items in this group (e.g., a list of all cities
with country=’India’).

Note that {%regroup%} does not order its input! Our example relies on
the fact that the cities list was ordered by country in the first place.
If the cities list did not order its members by country, the
regrouping would naively display more than one group for a single country. For
example, say the cities list was set to this (note that the countries are not
grouped together):

Any valid template lookup is a legal grouping attribute for the regroup
tag, including methods, attributes, dictionary keys and list items. For
example, if the “country” field is a foreign key to a class with
an attribute “description,” you could use:

{%regroupcitiesbycountry.descriptionascountry_list%}

Or, if country is a field with choices, it will have a
get_FOO_display() method available as an
attribute, allowing you to group on the display string rather than the
choices key:

{%regroupcitiesbyget_country_displayascountry_list%}

{{country.grouper}} will now display the value fields from the
choices set rather than the keys.

Like a simple include tag, {%ssi%} includes the contents of
another file – which must be specified using an absolute path – in the
current page:

{%ssi'/home/html/ljworld.com/includes/right_generic.html'%}

The first parameter of ssi can be a quoted literal or any other context
variable.

If the optional parsed parameter is given, the contents of the included
file are evaluated as template code, within the current context:

{%ssi'/home/html/ljworld.com/includes/right_generic.html'parsed%}

Note that if you use {%ssi%}, you’ll need to define
ALLOWED_INCLUDE_ROOTS in your Django settings, as a security
measure.

Note

With the ssi tag and the parsed parameter
there is no shared state between files – each include is a completely
independent rendering process. This means it’s not possible for example to
define blocks or alter the context in the current page using the included
file.

Returns an absolute path reference (a URL without the domain name) matching a
given view function and optional parameters.

Changed in Django 1.6:

Any special characters in the resulting path will be encoded using
iri_to_uri().

This is a way to output links without violating the DRY principle by having to
hard-code URLs in your templates:

{%url'path.to.some_view'v1v2%}

The first argument is a path to a view function in the format
package.package.module.function. It can be a quoted literal or any other
context variable. Additional arguments are optional and
should be space-separated values that will be used as arguments in the URL.
The example above shows passing positional arguments. Alternatively you may
use keyword syntax:

{%url'path.to.some_view'arg1=v1arg2=v2%}

Do not mix both positional and keyword syntax in a single call. All arguments
required by the URLconf should be present.

For example, suppose you have a view, app_views.client, whose URLconf
takes a client ID (here, client() is a method inside the views file
app_views.py). The URLconf line might look like this:

('^client/(\d+)/$','app_views.client')

If this app’s URLconf is included into the project’s URLconf under a path
such as this:

('^clients/',include('project_name.app_name.urls'))

...then, in a template, you can create a link to this view like this:

{%url'app_views.client'client.id%}

The template tag will output the string /clients/client/123/.

If you’re using named URL patterns, you can
refer to the name of the pattern in the url tag instead of using the
path to the view.

Note that if the URL you’re reversing doesn’t exist, you’ll get an
NoReverseMatch exception raised, which will
cause your site to display an error page.

If you’d like to retrieve a URL without displaying it, you can use a slightly
different call:

This filter will first try to coerce both values to integers. If this fails,
it’ll attempt to add the values together anyway. This will work on some data
types (strings, list, etc.) and fail on others. If it fails, the result will
be an empty string.

For example, if we have:

{{first|add:second}}

and first is [1,2,3] and second is [4,5,6], then the
output will be [1,2,3,4,5,6].

Warning

Strings that can be coerced to integers will be summed, not
concatenated, as in the first example above.

Takes a list of dictionaries and returns that list sorted in reverse order by
the key given in the argument. This works exactly the same as the above filter,
but the returned value will be in reverse order.

The escaping is only applied when the string is output, so it does not matter
where in a chained sequence of filters you put escape: it will always be
applied as though it were the last filter. If you want escaping to be applied
immediately, use the force_escape filter.

Applying escape to a variable that would normally have auto-escaping
applied to the result will only result in one round of escaping being done. So
it is safe to use this function even in auto-escaping environments. If you want
multiple escaping passes to be applied, use the force_escape filter.

Strictly speaking, filesizeformat does not conform to the International
System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes
are calculated in powers of 1024 (which is the case here). Instead, Django
uses traditional unit names (KB, MB, GB, etc.) corresponding to names that
are more commonly used.

This is rarely useful as ampersands are automatically escaped. See
escape for more information.

Deprecated since version 1.7: This filter has been deprecated and will be removed in Django 1.8.

Replaces ampersands with &amp; entities.

For example:

{{value|fix_ampersands}}

If value is Tom&Jerry, the output will be Tom&amp;Jerry.

However, ampersands used in named entities and numeric character references
will not be replaced. For example, if value is Caf&eacute;, the output
will not be Caf&amp;eacute; but remain Caf&eacute;. This means that
in some edge cases, such as acronyms followed by semicolons, this filter will
not replace ampersands that need replacing. For example, if value is
ContacttheR&D;, the output will remain unchanged because &D;
resembles a named entity.

Applies HTML escaping to a string (see the escape filter for
details). This filter is applied immediately and returns a new, escaped
string. This is useful in the rare cases where you need multiple escaping or
want to apply other filters to the escaped results. Normally, you want to use
the escape filter.

For example, if you want to catch the <p> HTML elements created by
the linebreaks filter:

Given a whole number, returns the requested digit, where 1 is the right-most
digit, 2 is the second-right-most digit, etc. Returns the original value for
invalid input (if input or argument is not an integer, or if argument is less
than 1). Otherwise, output is always an integer.

If value is "<b>Joel</b><button>is</button>a<span>slug</span>" the
unescaped output will be "Joel<button>is</button>aslug".

Note that this filter is case-sensitive.

If value is "<B>Joel</B><button>is</button>a<span>slug</span>" the
unescaped output will be "<B>Joel</B><button>is</button>aslug".

No safety guarantee

Note that removetags doesn’t give any guarantee about its output being
HTML safe. In particular, it doesn’t work recursively, so an input like
"<sc<script>ript>alert('XSS')</sc</script>ript>" won’t be safe even if
you apply |removetags:"script". So if the input is user provided,
NEVER apply the safe filter to a removetags output. If you are
looking for something more robust, you can use the bleach Python
library, notably its clean method.

If value is "<b>Joel</b><button>is</button>a<span>slug</span>", the
output will be "Joelisaslug".

No safety guarantee

Note that striptags doesn’t give any guarantee about its output being
HTML safe, particularly with non valid HTML input. So NEVER apply the
safe filter to a striptags output. If you are looking for something
more robust, you can use the bleach Python library, notably its
clean method.

the output will be the string "01:23:00" (The "TIME_FORMAT" format
specifier for the de locale as shipped with Django is "H:i:s").

The time filter will only accept parameters in the format string that
relate to the time of day, not the date (for obvious reasons). If you need to
format a date value, use the date filter instead (or along
time if you need to render a full datetime value).

There is one exception the above rule: When passed a datetime value with
attached timezone information (a time-zone-awaredatetime instance) the time filter will
accept the timezone-related format specifiers'e', 'O' , 'T' and 'Z'.

When used without a format string:

{{value|time}}

...the formatting string defined in the TIME_FORMAT setting will be
used, without applying any localization.

Changed in Django 1.7:

The ability to receive and act on values with attached timezone
information was added in Django 1.7.

Takes an optional argument that is a variable containing the date to use as
the comparison point (without the argument, the comparison point is now).
For example, if blog_date is a date instance representing midnight on 1
June 2006, and comment_date is a date instance for 08:00 on 1 June 2006,
then the following would return “8 hours”:

{{blog_date|timesince:comment_date}}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any
date that is in the future relative to the comparison point.

Similar to timesince, except that it measures the time from now until the
given date or datetime. For example, if today is 1 June 2006 and
conference_date is a date instance holding 29 June 2006, then
{{conference_date|timeuntil}} will return “4 weeks”.

Takes an optional argument that is a variable containing the date to use as
the comparison point (instead of now). If from_date contains 22 June
2006, then the following will return “1 week”:

{{conference_date|timeuntil:from_date}}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any
date that is in the past relative to the comparison point.

This template tag works on links prefixed with http://, https://, or
www.. For example, http://goo.gl/aia1t will get converted but
goo.gl/aia1t won’t.

It also supports domain-only links ending in one of the original top level
domains (.com, .edu, .gov, .int, .mil, .net, and
.org). For example, djangoproject.com gets converted.

Links can have trailing punctuation (periods, commas, close-parens) and leading
punctuation (opening parens), and urlize will still do the right thing.

Links generated by urlize have a rel="nofollow" attribute added
to them.

For example:

{{value|urlize}}

If value is "Checkoutwww.djangoproject.com", the output will be
"Checkout<ahref="http://www.djangoproject.com"rel="nofollow">www.djangoproject.com</a>".

In addition to web links, urlize also converts email addresses into
mailto: links. If value is
"Sendquestionstofoo@example.com", the output will be
"Sendquestionsto<ahref="mailto:foo@example.com">foo@example.com</a>".

The urlize filter also takes an optional parameter autoescape. If
autoescape is True, the link text and URLs will be escaped using
Django’s built-in escape filter. The default value for
autoescape is True.

Note

If urlize is applied to text that already contains HTML markup,
things won’t work as expected. Apply this filter only to plain text.

This library provides control over the localization of values in templates.
You only need to load the library using {%loadl10n%}, but you’ll often
set USE_L10N to True so that localization is active by default.

This library provides control over time zone conversions in templates.
Like l10n, you only need to load the library using {%loadtz%},
but you’ll usually also set USE_TZ to True so that conversion
to local time happens by default.