'How to get all checked items in SelectMultipleField in WTForms + Flask
I have a SelectMultipleField but when I try to access checked items, thought form.fields.data I only get the first of them.
More over, by trying to get answers directly from request.form.data through
for key in request.form.keys():
print(str(key) + '=' + str(request.form.getlist(key)))
I can see an array of all checked items there.
Where have I made a mistake, so WTForms can't pass all checked items to form.fields.data?
My route:
form = ListForm()
if request.method == "GET":
form.add_items(bank.get_items())
elif request.method == "POST":
print(form.fields.data) # and in needed field i only see 'A' even if 'A', 'B' and 'C' checked
form itself:
class Item(FlaskForm):
pass
class ListForm(FlaskForm):
fields = FieldList(FormField(Item))
submit = SubmitField('Submit')
def add_items(self, items):
for item in items:
Item.choices_field = SelectMultipleField(
choices=item.get_choices()
) # lets just assume get_choices() returned ['A', 'B', 'C', 'D'] for an element
self.fields.append_entry()
and my template for it:
{{ form.hidden_tag() }}
<form method="post" novalidate>
{% for field in form.fields %}
<fieldset>
{{ field.choices_field }}
</fieldset>
{% endfor %}
{{ form.submit }}
</form>
I tried using tuples instead of list of options but had the same issue
Solution 1:[1]
So the answer is in getting answers from request.form instead of form.data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | username |
