问题:Django:显示选择值

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'or 'F'而不是'Male'or 'Female'

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

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)

On the template, when I call person.gender, I get 'M' or 'F' instead of 'Male' or 'Female'.

How to display the value ('Male' or 'Female') instead of the code ('M'/'F')?


回答 0

看来您处在正确的轨道上- get_FOO_display()无疑是您想要的:

模板中,您不包括()方法名称。请执行下列操作:

{{ person.get_gender_display }}

It looks like you were on the right track – get_FOO_display() is most certainly what you want:

In templates, you don’t include () in the name of a method. Do the following:

{{ person.get_gender_display }}

回答 1

对于每个设置了选项的字段,该对象将具有get_FOO_display()方法,其中FOO是字段的名称。此方法返回该字段的“人类可读”值。

在视图中

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

在模板中

{{ person.get_gender_display }}

get_FOO_display()的文档

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

In Views

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

In Template

{{ person.get_gender_display }}

Documentation of get_FOO_display()


回答 2

其他人指出,您需要的是get_FOO_display方法。我正在使用这个:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

遍历特定项目的所有选择,直到找到与项目类型匹配的项目

Others have pointed out that a get_FOO_display method is what you need. I’m using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。