Getting the name (Verbose Name) of a model or object from a template
Suppose we have an example model like this:
from django.db import models
class Snippet(models.Model):
....
class Meta:
verbose_name = 'Snippet'
verbose_name_plural = 'Snippets'
And there was a need to display a verbose name (Verbose Name) in Django templates.
If you try to do it the same way as in Python code, {{ object._meta.verbose_name }} will fail, because the Django template engine does not give access to the private _meta object.
But to solve the problem, you can make a simple template filter.
Create a templatetags/my_tags.py file that contains the following code:
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 you can display the model name in templates using this filter:
{% load my_tags %}
{{ object|verbose_name }}
{{ object|verbose_name_plural }}
Back to Top