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 }}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" }}
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 }}
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 }}
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 }}
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" }}"
The result will be " Django " if the value is " Django ".
cut
Removes all values of arg from the given string.
For example:
{{ value|cut:" " }}
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" }}
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" }}
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" }}
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" }}If the value is:
[
{'name': 'Abi', 'age': 29},
{'name': 'Sonu', 'age': 25},
{'name': 'Rahul', 'age': 36},
]Then the output would be:
[
{'name': 'Abi', 'age': 29},
{'name': 'Rahul', 'age': 36},
{'name': 'Sonu', 'age': 25},
]divisibleby
Returns True if the value is divisible by the argument.
For example:
{{ value|divisibleby:"3" }}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 <
- > is converted to >
- ' (single quote) is converted to '
- " (double quote) is converted to "
- & is converted to &
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 %}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 }}The result will be 117.7 MB if the value is 123456789.
first
Returns the first item in a list.
For example:
{{ value|first }}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:" // " }}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 }}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 }}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 }}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 }}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 }}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 }}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 }}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" }}"The result will be" Django" if the value is Django.
slice
A slice of the list is returned.
For example:
{{ some_list|slice:":2" }}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 }}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" }}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>




