过滤器允许您将函数应用于变量。此函数可以使用0或1参数。语法如下:
{{ variable|filter_name }} {{ variable|filter_name:argument }}
过滤器可以链接在一起,因此非常有效:
{{ variable|filter_name:argument|another_filter }}
如果将其翻译成python,上面的代码行将给出以下内容:
print(another_filter(filter_name(variable, argument)))
在此示例中,我们将编写一个verbose_name适用于模型(实例或类)或QuerySet的自定义过滤器。它将返回模型的详细名称,或者如果参数设置为,则返回其详细名称复数形式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