With the <form>
having two list items selected "Category 01" and "Category 03":
<form>
<div class="form-group">
<div>
<select name='category' multiple class="form-control">
<option> Category 01 </option>
<option> Category 01 </option>
<option> Category 01 </option>
</select>
</div>
</div>
</form>
if request.method == 'POST':
as_dict = request.form.to_dict()
print request
Which prints this output showing it only gets a single "Category 03".
{'category': u'Category 01'}
How to make sure all the selected Categories are listed and not just one?
You will want to use the getlist()
function to get a list of values.
First, change your form as below:
<form>
<div class="form-group">
<div>
<select id="myform" name='category' multiple class="form-control"> // addition here
<option> Category 01 </option>
<option> Category 01 </option>
<option> Category 01 </option>
</select>
</div>
</div>
</form>
And in your flask function:
if request.method == 'POST':
as_dict = request.form.getlist('myform')
print request
Hope this helps!
So problem is that the to_dict()
by default flattens all inputs into a single layer dictionary.
Since the multiple selections are sent with the same key when they are added to the dictionary only the first one succeeds as a dict can not have multiple entries with the same key.
The resolution is to set request.form.to_dict(flat=False)
. flat=false
this means that all fields are returned as lists. So all the single fields will now be a single item in a list. But the multiple select will have all the selections in its list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With