python - Django:显示选择值

标签 python django django-models django-templates

models.py:

class Person(models.Model):
    name = models.CharField(max_length=200)
    CATEGORY_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
    to_be_listed = models.BooleanField(default=True)
    description = models.CharField(max_length=20000, blank=True)

views.py:

def index(request):
    latest_person_list2 = Person.objects.filter(to_be_listed=True)
    return object_list(request, template_name='polls/schol.html',
                       queryset=latest_person_list, paginate_by=5)

在模板上,当我调用 person.gender 时,我得到的是 'M''F' 而不是 '男''女'

如何显示值('Male''Female')而不是代码('M'/ 'F')?

最佳答案

看来您的方向是正确的 - get_FOO_display()肯定是你想要的:

模板中,您不能在方法名称中包含()。执行以下操作:

{{ person.get_gender_display }}

关于python - Django:显示选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4320679/

相关文章:

python - Django + Postgres : save JSON string directly into model as JSON type

python - Django : Type error at/<User: user1> is not JSON serializable

Django:用多个计数注释模型非常慢

python - 没有该列错误信息

python - Django 模型 : user ID

python - 通过修补 Flask 请求对 Python 包中的装饰器进行单元测试

python - Python 中复数除法的停止近似

python - 如何找到运动物体轨迹中的冗余路径(子路径)?

python - Django新手错误: - TypeError: view must be a callable or a list/tuple in the case of include()

python - django 中的分组依据、不同值、计数