Dec 07, 2017 · Updated: Jul 12, 2021 · by Tim Kamanin
Let's say you have a model:
from django.db import models
class Snippet(models.Model):
class Meta:
verbose_name = "Snippet"
verbose_name_plural = "Snippets"
And you want to print model's verbose name in a Django template.
Try to do it as {{ object._meta.verbose_name }}
and you will fail - Django template won't allow you to access "private" _meta.
Luckily, we can create template filters that'll solve this problem.
Create a file templatetags/my_tags.py that contains:
from django import template
register = template.Library()
@register.filter
def verbose_name(obj):
return obj._meta.verbose_name
@register.filter
def verbose_name_plural(obj):
return obj._meta.verbose_name_plural
Now, in your template, you can print verbose names as easy as:
{% load my_tags %}
{{ object|verbose_name }}
{{ object|verbose_name_plural }}
Hope this helps.
Hey, if you've found this useful, please share the post to help other folks find it: