Reputation: 1697
I have a Django form where I would like to use dynamic choice list from a query in my view.
Here is what I'm trying to do:
views.py
getdata = MyModel.objects.filter(filter=filter)
form = MyForm(request.POST or None,
mylist=[( (getdata.id), (getdata.name) ) for choice in getdata]
when I run that I get 'QuerySet' object has no attribute 'id'
error.
I know I can use ModelChoiceField
and do the query in my form but for this specific case I would rather use the list generated in my view.
Upvotes: 0
Views: 797
Reputation: 490
try:
form = MyForm(request.POST or None,
mylist=[( (choice.id), (choice.name) ) for choice in getdata]
when you iterate like that be it in list comprehension, here or dict comprehension you need to think the same way you do when you write a for loop:
for choice in getdata:
#do something
Upvotes: 1
Reputation: 599470
choice
is the individual item in each iteration, not getdata
.
mylist=[( (choice.id), (choice.name) ) for choice in getdata]
Upvotes: 2