alphanumeric alphanumeric - 25 days ago 6
Python Question

How to get multiple selected items from Form in Flask

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>


enter image description here

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?

Answer

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!