django模板中对象的模型名称 [英] Model name of objects in django templates
问题描述
p> object .__ class __.__ name __
或 object._meta.object_name
应该给你模型类的名字。但是,这个不能在模板中使用,因为属性名称以下划线开头。
没有内置的方式来获取那个模板中的值,所以你必须定义一个返回该属性的模型方法,或者一个更通用/可重用的解决方案,使用模板过滤器:
@ register.filter
def to_class_name(value):
返回值.__ class __.__ name__
您可以在模板中使用以下内容:
{{obj | to_class_name}}
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?
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 }}
这篇关于django模板中对象的模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!