Model name of objects in django templates

前端 未结 5 1581
遥遥无期
遥遥无期 2020-12-09 07:59

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 b

5条回答
  •  遥遥无期
    2020-12-09 08:29

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

提交回复
热议问题