填充表单时,object不可迭代

时间:2015-02-10 01:18:28

标签: python flask wtforms flask-wtforms

我想填充选择字段的选项。

我正在尝试此代码,但我收到了:

TypeError: 'Industry' object is not iterable

视图

form = Filter_companies(request.form)

interests = Industry.query.all()
#[<app.companies.models.Industry object at 0xa9afc0c>, <app.companies.models.Industry object at 0xa9afc4c>}

form.industry.choices = interests

形式

class Filter_companies(Form):
    industry = SelectField('Industry')

错误的原因是什么?

编辑:类似这样的东西将填充每个对象的表示。

form.industry.choices = [(x, x) for x in interests]

2 个答案:

答案 0 :(得分:1)

choices必须是包含键值对的可迭代。

interests = Industry.query.all()
form.industry.choices = [(interest.id, str(interest)) for interest in interests]

这将产生valueid匹配且文本与__str__的返回值匹配的选项。

<option value="1">Name 1<option>
<option value="2">Name 2<option>

答案 1 :(得分:0)

你应该填写一个字典

form = Filter_companies(request.form)
interests = {}
industrydata = form.industry.choices
interests.append(andustry.query.all())
industrydata = interests.key('Industry')
print industrydata

没有关于如何生成此数据集的更多信息或其他信息,这是我认为您应该看到的。