Django Template Filters: A Comprehensive Overview

March 22, 2023


0
6 min read
569

Django is a popular web framework written in Python that uses a templating engine to generate dynamic HTML pages. Django templates offer a variety of built-in filters that allow developers to manipulate data before displaying it on the web page. In this article, we will provide a comprehensive overview of Django template filters with examples.

What are Django template filters?

Django template filters are functions that can be applied to variables in Django templates. These filters allow developers to manipulate and format data in a more appropriate way for display on a web page. Django template filters can be used to perform a variety of operations, including formatting dates, converting text to uppercase or lowercase, and performing mathematical calculations.

Filters can be used in the following format: {{ variable|filter_name }}. Here, the variable is the value that you want to apply the filter to, and filter_name is the name of the filter you want to apply. Multiple filters can be used to a single variable by chaining them together: {{ variable|filter_name1|filter_name2 }}.

Django provides a wide range of built-in filters that can be used for various purposes. In this article, we will explore the most commonly used filters.

1. String filters

Django provides several filters that can be used to manipulate strings.

lower

The lower filter converts the text to lowercase.

Example:

{{ "HELLO"|lower }}    # Output: hello

upper

The upper filter converts the text to uppercase.

Example:

{{ "hello"|upper }}    # Output: HELLO

title

The title filter capitalizes the first letter of each word in a string.

Example:

{{ "the quick brown fox"|title }}    # Output: The Quick Brown Fox

truncatechars

The truncatechars filter shortens the string to a specified number of characters.

Example:

{{ "This is a very long string."|truncatechars:10 }}    # Output: This is a...

truncatewords

The truncatewords filter shortens the string to a specified number of words.

Example:

{{ "This is a very long string."|truncatewords:3 }}    # Output: This is a...

linebreaks

The linebreaks filter converts line breaks in the string to HTML line breaks (<br>).

Example:

{{ "First line\nSecond line"|linebreaks }}    # Output: First line<br>Second line

linebreaksbr

The linebreaksbr filter converts line breaks in the string to HTML line breaks (<br>), and it also converts double line breaks to paragraphs.

Example:

{{ "First paragraph.\n\nSecond paragraph."|linebreaksbr }}    # Output: <p>First paragraph.</p><p>Second paragraph.</p>

2. Date and time filters

Django provides several filters that can be used to format date and time values.

date

The date filter formats a date according to a specified format string.

Example:

{{ some_date|date:"Y-m-d" }}    # Output: 2022-03-21

time

The time filter formats a time according to a specified format string.

Example:

{{ some_time|time:"H:i:s" }}    # Output: 21:15:30

datetime

The datetime filter formats a datetime value according to a specified format string.

Example:

{{ some_datetime|datetime:"Y-m-d H:i:s" }}    # Output: 2022-03-21 21:15:30

timezone

The timezone filter converts a datetime value to a specified time zone.

Example:

{{ some_datetime|timezone:"America/New_York"|datetime:"Y-m-d H:i:s" }}    # Output: 2022-03-21 16:15:30

naturaltime

The naturaltime filter formats a datetime value as a natural language string (e.g., "2 days ago").

Example:

{{ some_datetime|naturaltime }}    # Output: 2 days ago

3. Numeric filters

Django provides several filters that can be used to manipulate numeric values.

add

The add filter adds a value to a numeric variable.

Example:

{{ count|add:1 }}    # Output: 6 (assuming count is equal to 5)

floatformat

The floatformat filter formats a float value according to a specified number of decimal places.

Example:

{{ some_float|floatformat:2 }}    # Output: 3.14

intcomma

The intcomma filter adds commas to a large integer for readability.

Example:

{{ some_large_number|intcomma }}    # Output: 1,234,567,890

divisibleby

The divisibleby filter checks if a number is divisible by another number.

Example:

{{ some_number|divisibleby:2 }}    # Output: True (if some_number is even)

4. List filters

Django provides several filters that can be used to manipulate lists.

first

The first filter returns the first element in a list.

Example:

{{ my_list|first }}    # Output: "apple"

last

The last filter returns the last element in a list.

Example:

{{ my_list|last }}    # Output: "pear"

length

The length filter returns the number of elements in a list.

Example:

{{ my_list|length }}    # Output: 3

join

The join filter joins the elements in a list with a specified delimiter.

Example:

{{ my_list|join:", " }}    # Output: "apple, banana, pear"

slice

The slice filter returns a slice of a list.

Example:

{{ my_list|slice:"1:2" }}    # Output: ["banana"]

5. Boolean filters

Django provides several filters that can be used to manipulate boolean values.

yesno

The yesno filter returns one of two values depending on whether the input value is true or false.

Example:

{{ some_boolean|yesno:"Yes,No" }}    # Output: "Yes" (if some_boolean is True)

default

The default filter returns a default value if the input value is false or empty.

Example:

{{ some_variable|default:"No value" }}    # Output: "No value" (if some_variable is empty)

Conclusion

Django template filters provide a powerful way to manipulate data before displaying it on a web page. In this article, we have covered the most commonly used filters, including string filters, date and time filters 

numeric filters, list filters, and boolean filters, along with examples to illustrate their usage.

By using filters, you can keep your template code clean and concise, and easily customize the output for your users. With the ability to create your own custom filters, you can extend the functionality of Django's template system to meet your specific needs.

Remember that filters are not a replacement for writing custom template tags or using more complex logic in your views. However, they can be a powerful tool to help you display your data in a more user-friendly and intuitive way.

We hope that this comprehensive overview of Django template filters has been helpful to you and that you can start using them to enhance your web applications today!

django List Template Filter Template Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.