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

穿精又带淫゛_ 提交于 2021-02-10 15:08:17

问题


I am new to wtforms. I have to provide user with list of fruits and cost of each fruit as shown below,

screenshot

Total number of fruits are dynamically generated and each fruit prices is also dynamically generated.

Below is my declaration,

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 = [],
            )

Template contains the below code:

{% 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 %}

Before rendering the template, fruits_labels is dynamically populated with choices and form.fruits_list is dynamically populated with the lists, each list having choices.

User can select any particular fruit with a price, and remaining all other select inputs will be optional and then he can submit the form. After submitting the form, fruits_labels is dynamically populated with choices and form.fruits_list is dynamically populated with the lists, each list having choices (before validating) as shown below.

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.

Below is the output:

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

Even though I have selected a fruit3 with value 30, I don't know why the selected value is displayed as none. Also I tried displaying all the choices before retrieving the selected value, it displayed all the choices correctly. Several times I changed the code, but it always displays "none" value. Could someone please let me know what may be the issue.

It would be really helpful if you can provide me some example. Thanks for your time and help.


回答1:


I resolved the issue!

After user submits the form, I am receiving the submitted values properly, but in populate_fruits_list() method, I am making the list empty by removing the elements from the list, using pop_entry(). Once the list is empty, I am adding the elements to the list again. Because of the deletion of list elements, user selection to this field is resetting to "None".

Solution: After the form was submitted, if there are any fields which are populated dynamically, we shouldn't delete the entries from the list instead we can reassign the values using index like arr[0] = value.

i.e., replaced below statements

    arr.popentry()
    arr.append(value)

with

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

Hope this information will be helpful to others.

- Sravan



来源:https://stackoverflow.com/questions/29134530/wtforms-selectfield-with-dynamic-choices-always-returns-none-for-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!