Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/6571649/model-name-of-objects-in-django-templates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...