2015-06-05 20 views
0

我有一个Django表单,我想在查看中使用动态选择列表。如何从视图中的查询创建Django表单选择列表?

这里是我想要做的事:

views.py

getdata = MyModel.objects.filter(filter=filter) 

form = MyForm(request.POST or None, 
       mylist=[((getdata.id), (getdata.name)) for choice in getdata] 

,当我跑,我得到'QuerySet' object has no attribute 'id'错误。

我知道我可以使用ModelChoiceField并在我的表单中进行查询,但对于这种特定情况我宁愿使用我的视图中生成的列表。

回答

1

尝试:

form = MyForm(request.POST or None, 
      mylist=[((choice.id), (choice.name)) for choice in getdata] 

,当你重复这样无论是在列表理解,这里还是字典的理解,你需要考虑你做同样的方式,当你写一个for循环:

for choice in getdata: 
    #do something 
+0

感谢您的快速回复!感谢您的帮助! – WayBehind

2

choice是每个迭代中的单个项目,而不是getdata

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

丹尼尔,你的反馈总是有价值的,你是这里Django/Python社区的真正财富。感谢您继续工作和帮助! – WayBehind

相关问题