django 模板中对象的模型名称 [英] Model name of objects in django templates

查看:38
本文介绍了django 模板中对象的模型名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以获取django模板中任何对象的模型名称.手动,我们可以通过在模型中定义方法或使用模板标签来尝试......但是有什么内置的方法吗?

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__object._meta.object_name 应该给你模型的名字班级.但是,这不能在模板中使用,因为属性名称以下划线开头.

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__

您可以在模板中用作:

{{ obj | to_class_name }}

这篇关于django 模板中对象的模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆