Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - field's verbose_name in templates

Suppose I have a model:

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 }}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use following python code for this

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...