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

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

问题描述

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

解决方案

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屋!

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