DjangoDjango

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

Dec 07, 2017 · by Tim Kamanin

Let's say you have a model:

python
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:

python
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:

django
{% 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:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓