6

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?

1
  • What if you just print request.form? Commented Nov 12, 2016 at 19:35

2 Answers 2

14

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!

Sign up to request clarification or add additional context in comments.

1 Comment

i have done this its working but in database "custom_detail" : [ "[object Object]", "[object Object]" ] it is saving like this im using pymongo as databse , how can i get actual data ??
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.