Reputation: 637
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.
Upvotes: 48
Views: 42070
Reputation: 21
Example if you are using FlaskForm with SelectMultipleField:
Form:
options = SelectMultipleField("Choose your option", choices=["Option1", "Option2", "Option3"])
Python code to get the choosen option, if your select option2 for example:
choosen_option= form.options.data
The result will be ['Option2'], just add [0] to get the element inside of list
choosen_option= form.options.data[0]
the result will be
choosen_option = Option2
Upvotes: 1
Reputation: 1807
> 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')
Upvotes: 5
Reputation: 51
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) }
Upvotes: 1
Reputation: 1123970
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.
Upvotes: 96