模板中字段的verbose_name [英] field's verbose_name in templates

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

问题描述

假设我有一个模型:

from django.db import models

class Test(models.Model):
    name=models.CharField(max_length=255, verbose_name=u'custom name')

如何在模板中获取模型字段的详细名称?以下不起作用:

How do I get my model's field's verbose name in templates? The following doesn't work:

{{ test_instance.name.verbose_name }}

我非常感谢这个解决方案,就像我们在使用表单时所做的那样,在模板中使用标签属性:

I would very much appreciate the solution, something on lines as we do when using forms, using label attribute in template:

{{ form_field.label }}

推荐答案

您可以为此使用以下 python 代码

You can use following python code for this

Test._meta.get_field("name").verbose_name.title()

如果你想在模板中使用它,那么最好为此注册模板标签.在您的应用程序中创建一个 templatetags 文件夹,其中包含两个文件(__init__.pyverbose_names.py).将以下代码放入 verbose_names.py:

If you want to use this in template then it will be best to register template tag for this. Create a templatetags folder inside your app containing two files (__init__.py and verbose_names.py).Put following code in verbose_names.py:

from django import template
register = template.Library()

@register.simple_tag
def get_verbose_field_name(instance, field_name):
    """
    Returns verbose_name for a field.
    """
    return instance._meta.get_field(field_name).verbose_name.title()

现在你可以像这样加载库后在你的模板中使用这个模板标签:

Now you can use this template tag in your template after loading the library like this:

{% load verbose_names %}
{% get_verbose_field_name test_instance "name" %}

您可以阅读自定义模板标签在官方 Django 文档中.

You can read about Custom template tags in official django documentation.

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

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