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.
choice
是每次迭代中的单个项目,而不是getdata
。
mylist=[( (choice.id), (choice.name) ) for choice in getdata]
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.