Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Multiselect Form Field in Flask

Tags:

python

flask

I have a multiselect in html file like this:

<select multiple id="mymultiselect" name="mymultiselect">                  <option value="1">this</option>                <option value="2">that</option>                <option value="3">other thing</option> </select> 

When I access the mymultiselect field in flask/python via:

request.form['mymultiselect'] 

or by using the request.args.get function it only returns one selected item. I've learned that to get all the selected items I have to add [] to the name of the field, like so:

<select multiple id="mymultiselect" name="mymultiselect[]">                <option value="1">this</option>                <option value="2">that</option>                <option value="3">other thing</option> </select> 

I can see by viewing the post data in firebug that this is working, but I anytime I try to access this field in flask/python it comes back as null or None.

How do you access these multiselect form fields that have "[]" at the end of their name? I've tried appending "[]" to the field name in the python code as well but that does not seem to work.

like image 437
kj4ohh Avatar asked Sep 19 '12 20:09

kj4ohh


2 Answers

You want to use the getlist() function to get a list of values:

multiselect = request.form.getlist('mymultiselect') 

You do not need to add [] to the name to make this work; in fact, the [] will not help, don't use it at all.

like image 139
Martijn Pieters Avatar answered Oct 04 '22 04:10

Martijn Pieters


enter image description here> In sometimes, If you are using Ajax POST method then check the parameter name in network tab. Check the image attached that describes how to verify the parameter names.

In Flask view:

you can access the list responce based on parameter name.

request.form.getlist('mymultiselect[]') 

or

request.form.getlist('mymultiselect') 
like image 34
Ramesh Ponnusamy Avatar answered Oct 04 '22 02:10

Ramesh Ponnusamy