Lesson 19 of 60 – Django Template Filters
32%

Django Template Filters

Django Template Filters are used to modify, format, or transform the value of a template variable before displaying it in an HTML page. Filters are written after a variable using the pipe symbol |.

Note: The basic syntax of a Django template filter is {{ variable|filter }}. Multiple filters can also be chained together.

1. What is a Template Filter?

A template filter changes or formats the value of a variable before it is displayed.

{{ name|upper }}

If name contains rahul, the output becomes RAHUL.

2. Template Filter Syntax

A filter is added to a variable using the pipe symbol |.

{{ variable|filter }}

Example:

{{ name|upper }}

3. The upper Filter

The upper filter converts text to uppercase.

{{ name|upper }}

If the value is rahul, the output is:

RAHUL

4. The lower Filter

The lower filter converts text to lowercase.

{{ name|lower }}

For example, RAHUL becomes:

rahul

5. The title Filter

The title filter converts words so that their first letters are uppercase.

{{ name|title }}

For example:

django web development

becomes:

Django Web Development

6. The capfirst Filter

The capfirst filter capitalizes the first character of a value.

{{ name|capfirst }}

For example, rahul becomes Rahul.

7. The length Filter

The length filter returns the length of a value.

{{ name|length }}

If the name is Rahul, the result is 5. It can also be used with lists.

8. The default Filter

The default filter provides a fallback value when a variable is considered false.

{{ name|default:"Guest" }}

If name is empty, Django displays Guest.

9. The default_if_none Filter

The default_if_none filter provides a value only when the variable is None.

{{ name|default_if_none:"Guest" }}

Unlike default, it specifically checks for None.

10. The truncatechars Filter

The truncatechars filter limits text to a specified number of characters.

{{ description|truncatechars:30 }}

Long text is shortened and Django adds an ellipsis when appropriate.

11. The truncatewords Filter

The truncatewords filter limits text to a specified number of words.

{{ description|truncatewords:10 }}

This is useful for short descriptions, summaries, and previews.

12. The wordcount Filter

The wordcount filter returns the number of words in a string.

{{ description|wordcount }}

This can be useful when displaying information about the size of text.

13. The cut Filter

The cut filter removes all occurrences of a specified string.

{{ value|cut:" " }}

The example removes spaces from the value.

14. The join Filter

The join filter joins items in a list using a specified separator.

{{ subjects|join:", " }}

For a list such as Python, Django, SQL, the output can be displayed as a comma-separated string.

15. The first Filter

The first filter returns the first item of a list.

{{ students|first }}

If the list contains Rahul, Amit, Priya, the result is Rahul.

16. The last Filter

The last filter returns the last item of a list.

{{ students|last }}

For Rahul, Amit, Priya, the result is Priya.

17. The length_is Filter

The length_is filter was used in older Django versions to compare a value's length with a number. It is deprecated in modern Django versions.

{{ value|length_is:"5" }}

For new projects, prefer using the length filter with template logic where appropriate.

18. The divisibleby Filter

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

{{ number|divisibleby:"2" }}

The result is a Boolean value such as True or False.

19. The add Filter

The add filter attempts to add its argument to the value.

{{ number|add:"5" }}

For example, if number is 10, the result can be 15.

20. The floatformat Filter

The floatformat filter is used to format floating-point numbers.

{{ price|floatformat:2 }}

A value such as 499.5 can be displayed as 499.50.

21. The date Filter

The date filter formats date and datetime values.

{{ date|date:"d-m-Y" }}

For example, a date can be displayed in a day-month-year format.

22. The time Filter

The time filter formats a time value.

{{ time|time:"H:i" }}

This can display a time using hours and minutes.

23. The timesince Filter

The timesince filter calculates the time elapsed since a date or datetime.

{{ blog.created_at|timesince }}

It can produce output such as a number of days, hours, or minutes ago.

24. The timeuntil Filter

The timeuntil filter calculates the time remaining until a date or datetime.

{{ event.start_time|timeuntil }}

It can be useful for displaying how much time remains before an event.

25. The safe Filter

The safe filter marks a string as safe for HTML output.

{{ content|safe }}
Important: Use safe carefully. Marking untrusted user input as safe can create security problems such as cross-site scripting.

26. Chaining Multiple Filters

Multiple filters can be applied to the same variable by chaining them with additional pipe symbols.

{{ name|lower|title }}

The value is first converted to lowercase and then formatted using the title filter.

27. Filters with Template Variables

View:

def profile(request):

    data = {
        'name': 'RAHUL',
        'description':
        'Django is a Python web framework.'
    }

    return render(
        request,
        'profile.html',
        data
    )

Template:

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

<p>
{{ description|truncatewords:5 }}
</p>

28. Common Filter Mistakes

  • Forgetting the pipe symbol |
  • Using an incorrect filter name
  • Using the wrong filter argument
  • Confusing filters with template tags
  • Using safe with untrusted content
  • Applying a filter to an incompatible value

Correct:

{{ name|upper }}

Incorrect:

{{ name upper }}

29. Complete Template Filters Example

views.py

from django.shortcuts import render

def product(request):

    data = {
        'name': 'python course',
        'price': 499.5,
        'description':
        'This is a complete Python and Django course.'
    }

    return render(
        request,
        'product.html',
        data
    )

product.html

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

<p>
Price: ₹{{ price|floatformat:2 }}
</p>

<p>
{{ description|truncatewords:6 }}
</p>

30. Summary of Django Template Filters

Django template filters provide a convenient way to modify and format values before displaying them in HTML.

  • upper converts text to uppercase.
  • lower converts text to lowercase.
  • title formats words as titles.
  • capfirst capitalizes the first character.
  • length returns the length of a value.
  • default provides a fallback value.
  • truncatechars limits characters.
  • truncatewords limits words.
  • join combines list items.
  • date and time format date/time values.
  • floatformat formats decimal numbers.
  • Multiple filters can be chained together.

📌 Key Points

  • Django filters use the pipe symbol |.
  • Filters modify or format template variable values.
  • upper, lower, and title work with text.
  • length can find the length of a value.
  • default provides fallback values.
  • truncatechars and truncatewords shorten text.
  • date, time, and floatformat format values.
  • Filters can be chained together.
  • Use safe carefully with untrusted content.

🧠 Quick Quiz

Question: Which symbol is used to apply a filter to a Django template variable?