如何使用django.forms用模型中的行预填充选择字段? [英] How would I use django.forms to prepopulate a choice field with rows from a model?

查看:81
本文介绍了如何使用django.forms用模型中的行预填充选择字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单类中有一个ChoiceField,大概是用户列表。如何用我的用户模型中的用户列表预先填充?

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?

我现在所拥有的是:

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?

为了澄清,当我尝试在模板中呈现此表单时,它只是不输出任何内容,除非我删除ChoiceFields和 __ init __( )方法。

To clarify, when I attempt to render this form in a template, it simply outputs nothing, unless I remove the ChoiceFields and __init__() method.

此外,如果我只想在自己的字段中列出用户的全名怎么办?也就是说,我想控制每个用户对象的显示输出(因此 ModelChoiceField 并不是真正的选择)。

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).

推荐答案

您似乎正在寻找 ModelChoiceField

It looks like you may be looking for ModelChoiceField.

user2 = forms.ModelChoiceField(queryset=User.objects.all())

这不会显示全名,它只会在每个对象上调用 __ unicode __ 来获取显示的值。

This won't show fullnames, though, it'll just call __unicode__ on each object to get the displayed value.

在您不只想显示 __ unicode __ 的地方,我会这样做:

Where you don't just want to display __unicode__, I do something like this:

class MatchForm(forms.Form):
    user1 = forms.ChoiceField(choices = [])

    def __init__(self, *args, **kwargs):
        super(MatchForm, self).__init__(*args, **kwargs)
        self.fields['user1'].choices = [(x.pk, x.get_full_name()) for x in User.objects.all()]

这篇关于如何使用django.forms用模型中的行预填充选择字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆