Model name of objects in django templates

爷,独闯天下 提交于 2019-12-28 12:46:55

问题


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?


回答1:


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



回答2:


You cannot access the class name directly. Doing something like this:

{{ object.__class__ }}

will cause a TemplateSyntaxError: Variables and attributes may not begin with underscores. Django doesn't let you access those sorts of attributes - Python conventions means they are hidden implementation details, not part of the object's API.

Create a template filter instead, and then you can use it as follows:

{{ object|model_name_filter }}

Creating filters is very easy: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/




回答3:


Django added a publicly accessible API to model options called _meta, but you still can't access variables with an underscore in the template. Use a template filter:

@register.filter
def verbose_name(instance):
    return instance._meta.verbose_name

In the template:

{{ instance|verbose_name }}

I even like to chain the title filter to capitalize the words in the my template:

{{ instance|verbose_name|title }}



回答4:


Since 1.2 version and may be early Django has an attribute opts into templates. The atribute is link to model._meta For evidence you should look at source code into Github

It used into template very simple: {{opts}} or {{opts.db_table}}



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!