How would I use django.forms to prepopulate a choice field with rows from a model?

17,573

It looks like you may be looking for ModelChoiceField.

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

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:

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()]
Share:
17,573

Related videos on Youtube

Sri Raghavan
Author by

Sri Raghavan

Updated on February 20, 2020

Comments

  • Sri Raghavan
    Sri Raghavan about 4 years

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

  • Dominic Rodger
    Dominic Rodger about 13 years
    It isn't dynamic though. The first time that code is run, the list of users will be set forever, and any Users added later will not appear in the form.
  • Sri Raghavan
    Sri Raghavan about 13 years
    @Dominic What do you mean by 'not dynamic'? Will this refresh the list of users every time I use the form?
  • Dominic Rodger
    Dominic Rodger about 13 years
    @Sri - no. Per my previous comment - the first time that code is run, the list of Users will be set forever, and any Users added later will not appear in the form, most likely until your webserver is restarted.
  • Sri Raghavan
    Sri Raghavan about 13 years
    what do I do if I need the fullnames rather than __unicode__?
  • Sri Raghavan
    Sri Raghavan about 13 years
    That's exactly what I ended up doing.

Related