簡體   English   中英

具有動態選擇的wtforms SelectField始終為數據返回“無”

[英]wtforms SelectField with dynamic choices always returns “none” for data

我是wtforms的新手。 我必須向用戶提供水果清單和每種水果的成本,如下所示,

截圖

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

以下是我的聲明,

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

即使我選擇了值30的fruit3,我也不知道為什么所選值顯示為none。 我也嘗試在檢索所選值之前顯示所有選擇,它正確顯示了所有選擇。 我幾次更改了代碼,但始終顯示“無”值。 有人可以讓我知道可能是什么問題。

如果您可以提供一些示例,那將非常有幫助。 感謝您的時間和幫助。

我解決了這個問題!

用戶提交表單后,我可以正確接收提交的值,但是在populate_fruits_list()方法中,我可以通過使用pop_entry()從列表中刪除元素來使列表為空。 列表為空后,我將元素再次添加到列表中。 由於刪除了列表元素,因此用戶對此字段的選擇將重置為“無”。

解決方案:提交表單后,如果有任何字段是動態填充的,我們不應該從列表中刪除條目,而是可以使用arr [0] = value之類的索引來重新分配值。

即,替換為以下語句

    arr.popentry()
    arr.append(value)

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

希望這些信息對其他人有幫助。

-Sravan

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM