Issue
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?
Solution
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 }}
Answered By - Shawn Chin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.