Skip to content Skip to sidebar Skip to footer

How To Create Django Form Choice List From Query In View?

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)

Solution 1:

choice is the individual item in each iteration, not getdata.

mylist=[( (choice.id), (choice.name) ) for choice in getdata]

Solution 2:

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:

forchoicein getdata:
    #do something

Post a Comment for "How To Create Django Form Choice List From Query In View?"