Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Template objects access verbose name

I have a Scrib model and a template which gets Scrib.objects.all() stored into scribs

In the template, I'd like to access to the verbose name of the model like:

<h1>{{ scribs.model.verbose_name }}</h1>

Is it possible or do I have to add the Scrib handler to the context ?

like image 754
Pierre de LESPINAY Avatar asked Sep 15 '11 06:09

Pierre de LESPINAY


People also ask

What is verbose name in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

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.

like image 84
WTK Avatar answered Sep 18 '22 19:09

WTK