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' 或
'F'
而不是 'Male'
或 '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'
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来您走在正确的轨道上 -
get_FOO_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:在视图中
在模板中
get_FOO_display() 的文档
In Views
In Template
Documentation of get_FOO_display()
我通过以下方式定义常量来实现此目的:
M 和 F 值将存储在数据库中,而 Male 和 Female 值将显示在各处。
I do this by defining constants the following way:
The M and F values will be stored in the database, while the Male and Female values will display everywhere.
其他人指出 get_FOO_display 方法正是您所需要的。
我正在使用这个:
它迭代特定项目的所有选择,直到找到与项目类型匹配的选项
Others have pointed out that a get_FOO_display method is what you need.
I'm using this:
which iterates over all of the choices that a particular item has until it finds the one that matches the items type