2015-03-18 86 views
1

我是wtforms新手。我必須提供與水果,每種水果的成本列表中的用戶,如下圖所示,是動態生成wtforms具有動態選擇的SelectField始終返回「無」數據

screenshot

水果的總數,也動態生成每個水果的價格。

下面是我的聲明,

from flask.ext.wtf import Form 
class SelectForm(Form): 
    def __init__(self, csrf_enabled=False, *args, **kwargs): 
     super(SelectForm, self).__init__(csrf_enabled=csrf_enabled, *args, **kwargs) 
    fruits_list = wtforms.FieldList(
      wtforms.SelectField('fruits', 
       validators = [validators.Optional()] 
       ), 
      ) 
fruits_labels = wtforms.RadioField('Fruit', 
      choices = [], 
      ) 

模板包含下面的代碼:

{% for fruit in form.fruits_labels %} 
<tr> 
    <td> 
     {{fruit}} 
     {{fruit.label}} 
    </td> 
    <td> 
     {% set fruitslist = form.fruits_list[loop.index0] %} 
     {% if fruitslist.choices|length %} 
     {{fruitslist(class='form-control')}} 
     {% endif %} 
    </td> 
</tr> 
{% endfor %} 

呈現模板之前,fruits_labels動態填充的選擇和form.fruits_list被動態列表填充,每個列表都有選擇。

用戶可以用價格選擇任何特定的水果,剩下的所有其他選擇輸入將是可選的,然後他可以提交表格。 提交表單後,fruits_labels會動態填充選項,form.fruits_list會動態填充列表,每個列表都有選擇(驗證前),如下所示。

populate_fruits_list() #form.fruits_list is dynamically populated in this function 
if not form.validate_on_submit(): 
    return render_template('new.html', form=form) 

i=0 
while i<len(form.fruits_list): 
    print 'form.fruits_list choices[',i,']: ', form.fruits_list[i].data 
    i=i+1 

print 'selection: ', form.fruits_list[userselection].data # userselection is a variable that contains the index of the fruit user has selected. 

下面是輸出:

form.fruits_list choices[ 0 ]: [('0', '-select-'), (1, '1')] 
form.fruits_list choices[ 1 ]: [('0', '-select-'), (30, '30'), (17, '17'), (16, '16'), (15, '15'), (14, '14'), (7, '7'), (6, '6'), (5, '5'), (4, '4'), (3, '3'), (2, '2'), (1, '1')] 
form.fruits_list choices[ 2 ]: [('0', '-select-'), (30, '30'), (29, '29'), (28, '28'), (19, '19'), (18, '18'), (13, '13'), (3, '3'), (2, '2'), (1, '1')] 
form.fruits_list choices[ 3 ]: [('0', '-select-'), (30, '30'), (29, '29'), (28, '28'), (21, '21'), (20, '20'), (12, '12'), (11, '11'), (10, '10'), (2, '2'), (1, '1')] 
selection: None 

即使我選擇了一個fruit3值爲30,我不知道爲什麼選定的值顯示爲無。此外,我試圖顯示所有的選擇之前檢索選定的值,它正確顯示所有的選擇。有幾次我更改了代碼,但它總是顯示「無」值。有人可以讓我知道可能是什麼問題。

如果你能提供一些例子,這將是非常有益的。感謝您的時間和幫助。

回答

0

我解決了這個問題!

用戶提交表單後,我正確接收提交的值,但在populate_fruits_list()方法中,我通過使用pop_entry()從列表中刪除元素來使列表爲空。一旦列表爲空,我將再次將這些元素添加到列表中。由於刪除了列表元素,用戶對該字段的選擇將重置爲「無」。

解決方案:表單提交後,如果有動態填充的字段,我們不應該從列表中刪除條目,而應該使用像arr [0] = value這樣的索引重新分配值。

即替換下面的語句

arr.popentry() 
    arr.append(value) 

arr[i] = value //where i is an index 

希望這些信息將幫助他人。

- Sravan