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

后端 未结 2 556
谎友^
谎友^ 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:09

    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()]
    

提交回复
热议问题