Table of contents
1.
Introduction
2.
Exploring Key Template Filters
2.1.
add
2.2.
addslashes
2.3.
capfirst
2.4.
center
2.5.
cut
2.6.
date
2.7.
default
2.8.
default_if_none
2.9.
dictsort
2.10.
divisibleby
2.11.
escape
2.12.
filesizeformat
2.13.
first
2.14.
join
2.15.
last
2.16.
length
2.17.
linebreaksbr
2.18.
linenumbers
2.19.
lower
2.20.
make_list
2.21.
random
2.22.
rjust
2.23.
slice
2.24.
slugify
2.25.
time
2.26.
unordered_list
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

Django Template Filters

Author Ranjul Arumadi
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A template in Django is a text document or a Python string marked-up using the Django template language. Django Template Filters are simple functions that modify data before Django renders it. Read more about Django Template here.

 

Syntax

After the variable, add a pipe (|) and the filter name and put filters inside double braces. This is based on how Unix shells allow you to pipe commands to each other.

{{ variable_name | filter_name }}
You can also try this code with Online Python Compiler
Run Code

Exploring Key Template Filters

Let's explore the several Django Template Filters used in a project. Filters transform variable and tag argument values. Let's see some of the most important Django template filters.

add

Adds the argument to the value.

For example:

{{ value|add:"7" }}
You can also try this code with Online Python Compiler
Run Code


This filter is used to increment a variable in Django templates.

The initial step in this filter is to convert both values to integers. If this fails, it will attempt to combine the values anyhow. Some data types (strings, lists, etc.) will work, but others will fail. The result will be an empty string if it fails.

For example:

{{ first|add:second }}
You can also try this code with Online Python Compiler
Run Code


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

addslashes

Before quotes, slashes are added. In CSV, this is useful for escaping strings.

For example:

{{ value|addslashes }}
You can also try this code with Online Python Compiler
Run Code


The output will be "I\'m using Django" if the value is "I'm using Django".

capfirst

The first character of the value is capitalised. This filter has no effect if the first character is not a letter.

For example:

{{ value|capfirst }}
You can also try this code with Online Python Compiler
Run Code


The result will be "Django" if the value is "django."

center

The value is centered in a field of a given width.

For example:

"{{ value|center:"15" }}"
You can also try this code with Online Python Compiler
Run Code


The result will be "     Django    " if the value is " Django ".

cut

Removes all values of arg from the given string.

For example:

{{ value|cut:" " }}
You can also try this code with Online Python Compiler
Run Code


The result will be "CodingNinjas" if the value is "Coding Ninjas".

date

Formats a date in the given format.

For example:

{{ value | date:"D d M Y" }}
You can also try this code with Online Python Compiler
Run Code


The string 'Thu 09 Jan 2020' will be produced if the value is a datetime object (e.g., the result of datetime.datetime.now()).

default

If the value evaluates to False, the default is used. Otherwise, the value is used.

For example:

{{ value | default:"nothing" }}
You can also try this code with Online Python Compiler
Run Code


The result will be nothing if the value is "" (the empty string).

default_if_none

Uses the supplied default if (and only if the) value is None. Otherwise, the value is used.

The default value will not be utilized if an empty string is provided. Use the default filter if we wish to fall back on empty strings.

For example:

{{ value|default_if_none:"nothing" }}
You can also try this code with Online Python Compiler
Run Code


The output will be nothing if the value is None.

dictsort

Returns a list of dictionaries that have been sorted by the key given in the argument.

For example:

{{ value|dictsort:"name" }}
You can also try this code with Online Python Compiler
Run Code

If the value is:

[
   {'name': 'Abi', 'age': 29},
   {'name': 'Sonu', 'age': 25},
   {'name': 'Rahul', 'age': 36},
]
You can also try this code with Online Python Compiler
Run Code

Then the output would be:

[
   {'name': 'Abi', 'age': 29},
   {'name': 'Rahul', 'age': 36},
   {'name': 'Sonu', 'age': 25},
]
You can also try this code with Online Python Compiler
Run Code

divisibleby

Returns True if the value is divisible by the argument.

For example:

{{ value|divisibleby:"3" }}
You can also try this code with Online Python Compiler
Run Code

The output would be True if the value is 21.

escape

The HTML in a string is escaped. It specifically makes the replacements:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to &#x27;
  • " (double quote) is converted to &quot;
  • & is converted to &amp;


When we use escape on a variable that ordinarily has auto-escaping applied to the result, we will only get one round of escaping. As a result, even in auto-escaping contexts, this function is safe to use. We must use the force_escape filter if we want several escaping passes to be applied.

For example, we can apply escape to fields when autoescape is off:

{% autoescape off %}
   {{ title|escape }}
{% endautoescape %}
You can also try this code with Online Python Compiler
Run Code

filesizeformat

Formats the value as a 'human-readable' file size (for example, '13 KB', '4.1 MB', '102 bytes', and so on).

For example:

{{ value|filesizeformat }}
You can also try this code with Online Python Compiler
Run Code

The result will be 117.7 MB if the value is 123456789.

first

Returns the first item in a list.

For example:

{{ value|first }}
You can also try this code with Online Python Compiler
Run Code

The output will be 'c' if the value is the list ['c', ‘n', 'b'].

join

Like Python's str.join(list), this function joins a list with a string.

For example:

{{ value|join:" // " }}
You can also try this code with Online Python Compiler
Run Code

The string "m // n // o" will be output if the value is the list ['m', 'n', 'o'].

last

The last item in the list is returned.

For example:

{{ value|last }}
You can also try this code with Online Python Compiler
Run Code

If the value is the list ['p', 'q', 'r', 's'], the output will be the string "s".

length

The length of the value is returned. This is applicable to both strings and lists.

For example:

{{ value|length }}
You can also try this code with Online Python Compiler
Run Code

The result will be 5 if the value is ['p', 'q', 'r', 's', ‘t’] or "pqrst."

For an undefined variable, the filter returns 0.

linebreaksbr

All new lines in plain text are converted to HTML line breaks (<br>).

For example:

{{ value|linebreaksbr }}
You can also try this code with Online Python Compiler
Run Code

The output will be Joe<br>is a slug if the value is Joe\nis a slug.

linenumbers

Text with line numbers is displayed.

For example:

{{ value|linenumbers }}
You can also try this code with Online Python Compiler
Run Code

If the value is:

Apple
Banana
Orange

The output will be:

1. Apple
2. Banana
3. Orange

lower

Converts a string to lowercase letters.

For example:

{{ value|lower }}
You can also try this code with Online Python Compiler
Run Code

The output will be “apple is good!” if the value is “Apple is Good!”

make_list

Returns the value that has been converted to a list. A string is a collection of characters. Before constructing a list, a numeric argument is converted to a string.

For example:

{{ value|make_list }}
You can also try this code with Online Python Compiler
Run Code

If the value is the string "Joel," the list ['J', 'o', 'e', 'l'] is returned. The output will be a list ['1','2','3'] if the value is 123.

random

Returns a random object from a list of options.

For example:

{{ value|random }}
You can also try this code with Online Python Compiler
Run Code

The output could be "b" if value is the list ['a', 'b', 'c', 'd'].

rjust

The value in a field of a given width is aligned to the right.

For example:

"{{ value|rjust:"10" }}"
You can also try this code with Online Python Compiler
Run Code

The result will be"    Django" if the value is Django.

slice

A slice of the list is returned.

For example:

{{ some_list|slice:":2" }}
You can also try this code with Online Python Compiler
Run Code

The output will be ['a','b'] if some_list is ['a','b','c'].

slugify

It does the following:-

  • Converts to ASCII characters. 
  • Converts hyphens to spaces. 
  • Characters other than alphanumerics, underscores, and hyphens are removed. 
  • Change the case to lowercase. 
  • Leading and trailing whitespace are also removed.


For example:

{{ value|slugify }}
You can also try this code with Online Python Compiler
Run Code

The output will be "Alex-is-a-slug" if the value is "Alex is a slug."

time

It's used to format a time in the specified format.

For example:

{{ value | time:"H:i" }}
You can also try this code with Online Python Compiler
Run Code

If the value is the same as datetime.datetime.now(). The string "11:22" will be returned.

unordered_list

Recursively converts a self-nested list to an HTML unordered list — without using opening and closing <ul> tags.

The format of the list is considered to be correct. If var contains ['States', ['Kerala', ['Kannur', 'Kozhikode'], 'Rajasthan']], then {{ var|unordered_list }} would return:

<li>States
<ul>
       <li>Kerala
       <ul>
               <li>Kannur</li>
               <li>Kozhikode</li>
       </ul>
       </li>
       <li>Rajasthan</li>
</ul>
</li>

Frequently Asked Questions

1. What is the use of the timesince Django template filter?

It formats a date as the time since that date

Syntax:

{{ date_initial|timesince:date_final }} 


If date_initial is a date instance representing midnight on 5 May 2014, and date_final is a date instance for 04:00 on 5 May 2014, then the following would return “4 hours”:.

2. What is the use of the title Django template filter?

It converts a string into a titlecase by making the words start with an uppercase character and making the remaining characters as lowercase.

E.g.: ‘my DJANGO code.’ will become ‘My Django Code.’.

Key Takeaways

Django Template Filters are simple functions that change data before Django renders it. Django template filters provide a powerful technique to create reusable HTML output. To separate the business logic from the display logic, templates are defined in their own language. You can use filters to modify data before presenting it.

Check out this problem - Multiply Strings

If you loved reading this article about Django template filters check out Flask vs Django in 2021: Which Framework to Choose? and Advantages & Disadvantages of Django.

Live masterclass