Access Multiselect Form Field in Flask

Question:

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.

Asked By: kj4ohh

||

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.

Answered By: Martijn Pieters

You can create a function to get values as dictionary

def __get_form_data(self, method='POST', compare_with=dict()):
    # Get form MiniFieldStorage items
    form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD' : method })
    # Convert to dictionary
    return { key.rstrip('[]'):form.getlist(key) if key.endswith('[]') else form.getvalue(key) for key in form.keys() if compare_with.get(key)!=form.getvalue(key) }
Answered By: Pablo Luaces

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')
Answered By: Ramesh Ponnusamy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.