Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple selected items from Form in Flask

Tags:

python

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?

like image 460
alphanumeric Avatar asked Nov 12 '16 19:11

alphanumeric


Video Answer


2 Answers

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!

like image 151
Rohin Gopalakrishnan Avatar answered Oct 17 '22 18:10

Rohin Gopalakrishnan


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.

like image 31
Sean D Avatar answered Oct 17 '22 17:10

Sean D