2015-02-10 30 views
0

我想填充選擇字段的選項。填充表單時對象不可迭代

我想這個代碼,但我收到:

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] 

回答

1

choices需要是一個包含鍵值對的可重構對象。

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

這將導致選擇其中value匹配id和文本的__str__返回值相匹配。

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

這將填充每個對象的字面意思。不是價值。 – user2990084 2015-02-10 01:35:30

+0

這意味着你還沒有定義「Interest .__ str__」。如果你不想這樣做,你可以使用你想要的任何'Interest'屬性。沒有看到它的定義,我不能使用一個具體的例子。 – dirn 2015-02-10 01:38:54

+0

好的,謝謝。我會接受。 – user2990084 2015-02-10 01:43:18

0

你應該填充的字典

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

,而無需更多的信息或所是如何產生的這組數據,這是什麼,我想你應該看做額外的信息。