Django Custom Filters


Example

Filters allows you to apply a function to a variable. This function may take 0 or 1 argument. Here is the syntax:

{{ variable|filter_name }} 
{{ variable|filter_name:argument }}

Filters can be chained so this is perfectly valid:

{{ variable|filter_name:argument|another_filter }}

If translated to python the above line would give something like this:

print(another_filter(filter_name(variable, argument)))

In this example, we will write a custom filter verbose_name that applies to a Model (instance or class) or a QuerySet. It will return the verbose name of a model, or its verbose name plural if the argument is set to True.

@register.filter
def verbose_name(model, plural=False):
    """Return the verbose name of a model.
    `model` can be either:
      - a Model class
      - a Model instance
      - a QuerySet
      - any object refering to a model through a `model` attribute.

    Usage:
      - Get the verbose name of an object
          {{ object|verbose_name }}
      - Get the plural verbose name of an object from a QuerySet
          {{ objects_list|verbose_name:True }}
    """
    if not hasattr(model, '_meta'):
        # handle the case of a QuerySet (among others)
        model = model.model
    opts = model._meta
    if plural:
        return opts.verbose_name_plural
    else:
        return opts.verbose_name