Template filters in Django

Django filters are used to modify the value of the variable before they are rendered as HTML code. To use a filter, type pipe character (|) followed by the filter name after the variable name.

{{ variable|filter_name }}

In the examples given in the subsequent sections assume that our context contains variable name whose value is "Tom Sawyer"

lower filter

lower filter when applied to a variable converts all the uppercase characters in the variable to lowercase equivalent. For example:

<p>{{ name|lower }}</p>

If value of the name variable is "Tom Sawyer" then the above code would produce the following HTML.

<p>tom sawyer</p>

upper filter

upper filter is exactly the opposite of lower filter. It converts all the characters in the variable to uppercase equivalent. For example:

<p>{{ name|upper }}</p>

If value of the name variable is "tom sawyer" then the above code would produce the following HTML.

<p>TOM SAWYER</p>

capfirst filter

capfirst filter converts only the first character in the variable to it's uppercase equivalent. For example:

<p>{{ name|capfirst }}</p>

If variable name contains "tom sawyer" then the above code would produce the following HTML.

<p>Tom sawyer</p>

You can also chain filters. For example:

<p>{{ name|lower|capfirst }}</p>

Here the name variable is first converted to lower case characters then capfirst filter is applied on the result.

title filter

title filter capitalizes the first letter of every word. For example:

<p>{{ name|title }}</p>

If variable name contains "tom sawyer" then the above code would produce the following HTML.

<p>Tom Sawyer</p>

length filter

length filter determines the length of the value. It works with string, list, dictionary and tuples. For example:

<p>The length variable name is {{ name|length }}</p>

If variable name contains "tom sawyer" then the above code would produce the following HTML.

<p>The length variable name is 10</p>

truncatewords fitler

truncatewords truncates (shorten) a string after certain number of words. truncatewords is one of those filters to which you can pass an argument. To pass an argument to a filter type colon (:) followed by argument inside double quotes ("") . truncatewords accepts a single argument. To pass multiple arguments to a filter separate then using a comma (,). For example, To output only the first 10 words of a blog post do this:

<p>{{ post|truncatewords:"10" }}</p>

If post variabled is defined as:

post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu lectus ut lacus posuere fringilla id eu turpis."

The above code will produce the following HTML

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu ...</p>

truncatechars filter

truncatechars filter is similar to truncatewords but instead of truncating by words it truncates by characters. It truncates a string if it is larger than the specified number of characters. After truncating string Django appends "..." (also known as ellipsis) to the truncated string. For example:

{{ long_text|truncatechars:"10" }}

This will truncate the string and appends "..." to the end, if it is larger than 10 characters.

If long_text contains "Lorem ipsum dolor sit amet, consectetur adipiscing elit" then the above code will producde the following HTML.

<p>Lorem i...</p>

pluralize filter

pluralize filter is used to handle suffixes. Lets take an example:

<p>You have {{ num }} products in your cart</p>

If n is 1 then then we would like to display.

<p>You have 1 product in your cart</p>

On the other and if n is 10 then we would like to display

<p>You have 10 products in your cart</p>

Notice the 's' in the products.

We can use pluralize filter to handle these conditions very easily.

<p>You have {{ num }} product {{ num|pluralize }} in your cart</p>

Now, if num is 1 the output will be:

<p>You have 1 product in your cart</p>

If the value if num is 100, then the output will be:

<p>You have 100 products in your cart</p>

By default pluralize filter appends "s" to the string. However, not all plural words ends with "s", some also end with "es" like tomatoes. For example:

<p>I have {{ num }} tomato{{ num|pluralize }}</p>

If num equals to 5 then the above code will output:

<p>I have 5 tomatos</p>

which is certainly wrong. To provide an alternative suffix you can pass a parameter to the pluralize filter. For example:

<p>I have {{ num }} tomato{{ num|pluralize:"es" }}</p>

If num equals to 5 the the output will be:

<p>I have 5 tomatoes</p>

There are still some words which don't pluralize by simple suffix like diary and diaries, cherry and cherries etc. To handle such special cases you have to provide both singular and plural suffixes as parameters to the pluralize filter. For example:

<p>I have {{ num }} diar{{ num|pluralize:"y,ies" }}</p>

If the num is 1 output will be:

<p>I have 1 diary</p>

If the num is 5 output will be:

<p>I have 5 diaries</p>

date filter

We use date filter to format date and datetime objects. The date filter uses some special format characters to format a date and datetime object. To format a date pass a string of format characters as parameter to date filter. For example: Lets say our context has a datetime object named now defined as:

now = datetime.datetime.now()

And our template contains the following code:

<p>Today is {{ now }}</p>

By default a datetime object would be printed in the following format:

<p>Today is Jan. 27, 2017, 4:28 p.m.</p>

The following are some commonly used format strings available for you to use with date filter:

Character What it does ? Example
d Day of month using 2 digit numbers "01" to "31"
D Day of week using three letter "Mon" for Monday, "Tue" for Tuessay
and so on
m Print month using 2 digits numbers "01" for Janurary, "02" for February and so on
M Print month using three letters numbers "Jan" for Janurary, "Feb" for February and so on
i Print minutes "00" to "59"
h Print hours in 12 hour format "01" to "12"
H Print hours in 24 hour format "00" to "23"
s Print seconds "00" to "59"
a Prints "a.m." or "p.m." "a.m.", "p.m."
Y Print year using full 4 digits '2001', '2014'

To see full list of date format characters click here.

Lets add some format character to the date filter as follows:

<p>Today is {{ now|date:"D d M Y" }}</p>

This will output something like this:

<p>Today is Fri 27 Jan 2017</p>

linebreak filter

linebreak filter converts line breaks in strings to appropriate HTML. If a string has newline it will be converted to <br/> and newline followed by a blank line will be converted to </p>.

{{ text|linebreak }}

Conside the following examples:

Example 1:

content = '''\
this is
a content
'''

{{ content|linebreaks }}

Then the output will be <p>this is<br />a test<br /></p>. In the variable content there are two newline characters first one is after word is and the second one is after word content. The linebreaks filter replaces these newline characters with <br />. tag

Example 2:

content = '''\
this is

a test
'''

{{ content|linebreaks }}

Then the output will be:

<p>this is</p>

<p>a test<br /></p>

In this case variable content has newline character (after word "is" ) followed by a blank line, as a result linebreaks filter will replace the newline followed by blank line with </p> tag.  The important thing to note is that the linebreak filter encapsulates entire string in p tags. If you just want to put <br/> at the newline use linebreakbr filter.

{{ text|linebreakbr }}

Now if text contains "Filter string\n using linebreak" the output will be Filter string<br /> using linebreak.

autoescape tag

Because of security concerns, Django template system automatically does the escaping for you. Conside the following example:

Suppose variable my_code contains "<p>this is short para </p>" and the code in the template is:

{{ my_code }}

The above code would produce the following HTML code:

&lt;p&gt;THIS IS TEST&lt;/p&gt;

There are two ways to turn off escaping:

1) safe filter
2) autoescape filter

safe filter

{{ my_code|safe }}

This code would produce the following HTML output:

<p>this is short para </p>

safe filter tells Django Template system that my_code variable is safe does not require escaping.

Another way to turn off escaping is to use autoescape tag

autoescape tag

autoescape tag lets you to escape/unescape contents of a large section within the template. It accepts either on or off as a argument, which indicates whether auto-escaping is in effect within the block or not.

For example:

{% autoescape on %}
    {{ code_snippet }}
{% endautoescape %}

As Django template system automatically escapes everything by default you would probably never need to use the above code. Instead, we generally use autoescape tag to turn off escaping for large section of the content. For example:

{% autoescape off %}
    {{ heading }}
    {{ main_content }}
    {{ footer }}
{% endautoescape %}

escape filter

The escape filter converts the following character to its HTML entities.

" is replaced with &quot;
' is replaced with &#39;
& is replaced with &amp;
< is replaced with &lt;
> is replaced with &gt;

But Since Django template system automatically escapes everything, you would never probably never use escape filter: For example:

my_code = "<p>this is short para</p>"

{{ my_code }}

is same as

{{ my_code|escape }}

The utility of this filter comes into play when we want to escape content when autoescape is turned off. For example:

{% autoescape off %}
    {{ heading }}
    {{ main_content }}
    {{ footer }}
    {{ comments }}
{% endautoescape %}

Here It's fine to assume that contents of variables heading, main_content and footer are safe. But this is not the case with comments. That's why it not a good idea to turn-off escapeing for the comments variable. To escape comments variable in template you could do the following:

{% autoescape off %}
    {{ heading }}
    {{ main_content }}
    {{ footer }}
    {{ comments|escape }}
{% endautoescape %}

That's enough filters to begin with. To view a full list of filters checkout this page in Django documentation.