Django Template Filters

  • In Django, filters are functions that can be applied to template variables to modify their values or format them in a desired way. Django provides a set of built-in filters that you can use, and you can also create custom filters.
  • To use filters in a Django template variable, you can chain them together using the pipe character (`|`). The variable is passed through the filters in the order they are specified. Here's an example:

    {{ my_variable|filter1|filter2|filter3 }}

  • In this example, the value of `my_variable` is first processed by `filter1`, then the result is passed to `filter2`, and so on. The final result is then rendered in the template.
  • Example:
  • views.py

    from django.shortcuts import render


    def handleHome(request):
        return render(request, "index.html", {"name": "gagan"})

  • index.html

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>

        <h1>{{ "hello world" | upper}}</h1>

        <h1>{{ name | capfirst}}</h1>
    </body>

    </html>


Here is a list of some commonly used built-in filters in Django:
  • add: Adds the argument to the value.
  • capfirst: Capitalizes the first character of a string.
  • cut: Removes all occurrences of a substring from a string.
  • date: Formats a date or datetime object.
  • default: If the value is false or empty, uses the given default.
  • default_if_none: If the value is None, uses the given default.
  • dictsort: Sorts a dictionary.
  • filesizeformat: Formats the value as a human-readable file size.
  • floatformat: Formats a floating-point number.
  • linebreaks: Converts newlines into HTML line breaks.
  • linebreaksbr: Converts newlines into HTML line breaks and adds "<br />" tags.
  • lower: Converts a string to lowercase.
  • pluralize: Returns a plural suffix if the value is not 1.
  • slugify: Converts a string into a URL-safe slug.
  • stringformat: Formats a string according to the given format specifier.
  • time: Formats a time object.
  • title: Converts a string to titlecase.
  • truncatechars: Truncates a string after a certain number of characters.
  • truncatechars_html: Truncates HTML content after a certain number of characters.
  • upper: Converts a string to uppercase.

  • The type of a filter depends on the specific filter being used. Some filters may return strings, while others may return integers, booleans, or other types based on the input and the filter's functionality. The Django documentation provides detailed information about the behavior and return types of each filter.

No comments:

Post a Comment