Django TypeError 'User' object is not iterable

后端 未结 1 1979
臣服心动
臣服心动 2021-01-15 22:04

Is it not possible to iterate over User objects using User.objects.all()?? I am trying to do the same but to no avail

I have a form;

class AddMemberF         


        
相关标签:
1条回答
  • 2021-01-15 22:36

    Use the ModelChoiceField instead of the simple ChoiceField:

    user = forms.ModelChoiceField(queryset=User.objects.all(),
                                  empty_label="(Choose a User)")
    

    UPDATE: You can change the queryset in the form's constructor. For example if you want to exclude already added members from the form:

    class AddMemberForm(Form):
        ...
        def __init__(self, *args, **kwargs):
            station = kwargs.pop('station')
            super(AddMemberForm, self).__init__(*args, **kwargs)
            if station:
                self.fields['user'].queryset = User.objects.exclude(
                                                 id__in=station.members.all())
    

    And then create the form with the station argument:

    form1 = AddMemberForm(station=station)
    
    0 讨论(0)
提交回复
热议问题