Custom filters in Django Templates

Django Custom filters are just Python functions that take one or two arguments, an optional argument, process those values and return a value to be displayed on the page.

  • The value of the variable (input) – not necessarily a string.
  • The value of the argument – this can have a default value, or be left out altogether.



For example, in the filter {{ var|foo:"bar" }}, the filter foo would be passed the variable var and the argument "bar".

Your custom tags and filters will live in a module inside the templatetags directory in your app where models.py and views.py exist.

Your directory structure would be:

  • my-project
    • my-app
      • views.py
      • models.py
      • templatetags
        • __init__.py
        • custom_tags.py

Write your custom filter that convert seconds to minute format. Once you’ve written your filter definition, you need to register it with your Library instance, to make it available to Django’s template language:

In Your custom_tags.py

from datetime import timedelta

from django import template

register = template.Library()

@register.filter(name='mysectotime')

def mysectotime(value):
    return str(timedelta(seconds=value))

register = template.Library() This refers that you need to make sure, your templates are added to the existing library of tags and filters that Django knows about. This statement gives an instance of the library so you can register your filters.

The above our custom template filter can be used in template after enabling by using “{% load custom_tags %}”.

In your template it would be:

{% load custom_filter %}

.....

<label>{{ object.second|mysectotime }}</label>

That it. Your custom template filter is ready. There is no limit to create custom filter and tags under templatetags directory in your app.

Custom filters in Django Templates
Tagged on:     
Show Buttons
Hide Buttons