Accessing Model's/Object's Verbose Name in Django Template

07 Dec · by Tim Kamanin · 1 min read

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.

Comments

Required for comment verification