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

后端 未结 2 570
谎友^
谎友^ 2021-02-08 02:52

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:



        
2条回答
  •  渐次进展
    2021-02-08 03:28

    class MatchForm(forms.Form):
      choices = tuple(User.objects.all().values_list())
    
      user1_auto = forms.CharField()
      user1 = forms.ChoiceField(choices=choices)
      user2_auto = forms.CharField()
      user2 = forms.ChoiceField(choices=choices)
    

    This should work.

提交回复
热议问题