Django Template Tags and Filters Custom Filters

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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.

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.

      - 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
        return opts.verbose_name

Got any Django Question?