我将如何使用 django.forms 用模型中的行预填充选择字段?
我的表单类中有一个 ChoiceField,大概是用户列表。如何使用我的用户模型中的用户列表预先填充此内容?
我现在所拥有的是:
class MatchForm(forms.Form):
choices = []
user1_auto = forms.CharField()
user1 = forms.ChoiceField(choices=choices)
user2_auto = forms.CharField()
user2 = forms.ChoiceField(choices=choices)
def __init__(self):
user_choices = User.objects.all()
for choice in user_choices:
self.choices.append(
(choice.id, choice.get_full_name())
)
这似乎不起作用(否则我就不会在这里)。想法?
澄清一下,当我尝试在模板中呈现此表单时,它不会输出任何内容,除非我删除 ChoiceFields 和 __init__() 方法。
另外,如果我只想要我的字段中的用户全名列表怎么办?也就是说,我想控制每个用户对象的显示输出(因此 ModelChoiceField 并不是真正的选项)。
I have a ChoiceField in my form class, presumably a list of users. How do I prepopulate this with a list of users from my User model?
What I have now is:
class MatchForm(forms.Form):
choices = []
user1_auto = forms.CharField()
user1 = forms.ChoiceField(choices=choices)
user2_auto = forms.CharField()
user2 = forms.ChoiceField(choices=choices)
def __init__(self):
user_choices = User.objects.all()
for choice in user_choices:
self.choices.append(
(choice.id, choice.get_full_name())
)
This doesn't seem to work (otherwise I wouldn't be here). Thoughts?
To clarify, when I attempt to render this form in a template, it simply outputs nothing, unless I remove the ChoiceFields and __init__()
method.
Also, what if I only want a list of the users' full names in my field? That is, I'd like to control the display output of each user object (so ModelChoiceField
isn't really an option).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您可能正在寻找
ModelChoiceField
。不过,这不会显示全名,它只会在每个对象上调用 __unicode__ 来获取显示的值。
如果您不想只显示
__unicode__
,我会这样做:It looks like you may be looking for
ModelChoiceField
.This won't show fullnames, though, it'll just call
__unicode__
on each object to get the displayed value.Where you don't just want to display
__unicode__
, I do something like this:这应该有效。
This should work.