1

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.ChoiceField(choices=User.objects.all(),
                             initial='Choose a User',
    ) 

And I am trying to render it through a template. Corresponding part of views.py below;

class StationHome(View):
    def get(self, request, pk):
        station = Station.objects.get(pk=pk)
        channels = Channel.objects.filter(station=station)
        members = station.members.all()
        form1 = AddMemberForm()
        return render(request, 
                      "home_station.html",
                      {"form1":form1,
                       "station":station,
                       "channels":channels,
                       "members":members,
                   },
                  )

Finally the corresponding part of the corresponding template,

<form method="post" action="{% url 'add_member' station.pk %}">
    {% csrf_token %}
    {{ form1 }}
</form>

But I am unable to access the URL due to this form. I get a TypeError at corresponding URL 'User' object is not iterable error.

Someone please help out.

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

6 Comments

I have post method of a subclass of Django's View class taking the user from the form. And I want the selected user to be added in a ManyToMany relation of a model named Station. station = Station.objects.get(pk=pk) station.members.add(form.cleaned_data['user']) But this doesn't work. Could you tell me what's wrong? I get KeyError at /station/2/addmember 'user' error
careless me! I had written form = Form(request.post) instead of AddMemberForm(request.post) :/
Catavaran could you tell me this; What if I want to be able to change the query set while creating an instance of the form
form1 = AddMemberForm() form1.user.queryset = station.members.all() This doesn't seem to work
Use the form's fields attribute: form1.fields['user'].queryset = .... Also see the update in my answer for another example.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.