[Fixed]-Django – Template objects access verbose name

11πŸ‘

βœ…

You can’t access the verbose_name directly from the template. From what I see you got three options.

Option one (simplest). Assign the verbose name in your controller and then access it from the template:

# in controller
render_to_response('template.html', {'scrib_verbose_name': Scrib._meta.verbose_name})

# in a view template.html
Verbose name of a Scrib model: {{ scrib_verbose_name }}

Option two: write yourself a view helper that will return the verbose_name (or other field from _meta class) for a given class.

Update Third option (a hat tip to Uku Loskit) – define a method on a scrib model that returns the meta object (or any particular field from it).

# method in a Scrib model
def meta(self):
    return self._meta

# later on in a template - scrib is a instance of Scrib model
<h1>{{ scrib.meta.verbose_name }}</h1>

Update2 If you insist on directly accessing verbose name from the scribs (which is a result of Scrib.objects.all()), then you can do stuff like:

scribs = Scrib.objects.all()
scribs.verbose_name = Scrib._meta.verbose_name

# in a template you can now access verbose name from a scribs variable
{{ scribs.verbose_name }}

Update3 Yet another way to go is using model inhertinace to be able to access the verbose name from instance of any model that inherit from our custom one.

# base model (inherits from models.Model)
class CustomModel(models.Model):
    def meta(self):
        return self._meta

    class Meta:
        abstract = True

# Scrib now inherit from CustomModel
class Scrib(CustomModel):
    # do any stuff you want here ...

Scrib now inherit from CustomModel that provides us with property meta. Any model that will inherit from CustomModel class is going to have this property. It’s the cleanest and most flexible solution.

πŸ‘€WTK

8πŸ‘

I want to do that as well, I suppose another solution would be a template filter:

from django import template
register = template.Library()

@register.filter
def verbose_name(value):
    return value._meta.verbose_name

@register.filter
def verbose_name_plural(value):
    return value._meta.verbose_name_plural

Then in the template:

1 {{ object|verbose_name }}, 2 {{ object|verbose_name_plural }}

1 scrib, 2 scribs
πŸ‘€augustomen

6πŸ‘

Alternatively to WTK’s suggestion you could define a method for the Scrib model in your models.py like this:

def get_verbose_name(self):
    return self._meta.verbose_name
# in templates
{{ scrib_instance.get_verbose_name }}
πŸ‘€Uku Loskit

Leave a comment