Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model name of objects in django templates

Is there any way to get the model name of any objects in django templates. Manually, we can try it by defining methods in models or using template tags... But is there any built-in way?

like image 414
Neo Avatar asked Jul 04 '11 12:07

Neo


People also ask

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What are models views and templates in Django?

It is a collection of three important components Model View and Template. The Model helps to handle database. It is a data access layer which handles the data. The Template is a presentation layer which handles User Interface part completely.

What do Django templates consist of?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.

What is {% include %} in Django?

Usage: {% extends 'parent_template. html' %} . {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it.


1 Answers

object.__class__.__name__ or object._meta.object_name should give you the name of the model class. However, this cannot be used in templates because the attribute names start with an underscore.

There isn't a built in way to get at that value from the templates, so you'll have to define a model method that returns that attribute, or for a more generic/reusable solution, use a template filter:

@register.filter def to_class_name(value):     return value.__class__.__name__ 

which you can use in your template as:

{{ obj | to_class_name }} 
like image 82
Shawn Chin Avatar answered Sep 23 '22 12:09

Shawn Chin