field's verbose_name in templates

前端 未结 3 2137
离开以前
离开以前 2020-12-23 10:18

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\')
         


        
3条回答
  •  醉梦人生
    2020-12-23 11:01

    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.

提交回复
热议问题