Skip to content Skip to sidebar Skip to footer

Django TypeError 'User' Object Is Not Iterable

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 AddMemberForm(Form): user = forms.Cho

Solution 1:

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)

Post a Comment for "Django TypeError 'User' Object Is Not Iterable"