Mirage
Mirage

Reputation: 31548

Getting object not iterable error in django form

IN my form i have this

 mychoices = User.objects.filter(category__name='city')

I get this error

User Object is not iterable. I am new to django

This is the next line

relevance = forms.MultipleChoiceField(choices=mychoices, widget=forms.CheckboxSelectMultiple())

If i comment this line then i don't see any error

EDIT:

I find the error , i had to use this

(choices=[ (o.id, str(o)) for o in User.objects.all()])  Then it works.

Does anyone know whats the problem in previous method

Upvotes: 0

Views: 6157

Answers (1)

Marboni
Marboni

Reputation: 2459

You need to specify only widget class, not calling constructor:

relevance = forms.MultipleChoiceField(choices=mychoices, widget=forms.CheckboxSelectMultiple)

UPDATE Choices must be iterable of 2-tuples. First will be value that will be returned in POST request parameters, second - string representation displayed on UI. May be, it makes sense to do something like this:

choices = User.objects.filter(category__name='city').values_list('id', 'first_name')

You will get:

(1, 'Mark')
(2, 'Jack')
...

When user selects option and post form, you will receive user ID in parameters, so you will be able to retrieve user object by it.

Upvotes: 3

Related Questions