1

I need to capture multiple select form vlaue (generated from a MongoDB collection ) and POST via a Flask route to another MongoDB collection: recipes

Below is the relevant form div:

<form action="{{ url_for('insert_recipe') }}" method="POST" class="col s12">
    ...

        <div class="input-field col s6 l6">
            <i class="material-icons prefix">warning</i>
            <select multiple id="allergen_name" name="allergenlist">
                <option value="" disabled selected>Choose allergens</option>
                {% for allergen in allergens %}
                <option value="{{allergen.allergen_name}}">{{allergen.allergen_name}}</option>
                {% endfor %}
            </select>
        </div>
    </div>

    ...

</form>

I want to capture the selected options and POST them via Flask:

# Get all recipes
@app.route('/get_recipes')
def get_recipes():
    return render_template("recipes.html", 
    recipes=mongo.db.recipes.find())

# Render HTML form
@app.route('/add_recipe')
def add_recipe():
    return render_template('addrecipe.html',
    users=mongo.db.users.find(),
    allergens=mongo.db.allergens.find(),
    cuisines=mongo.db.cuisine.find(),)

# Send the form    
@app.route('/insert_recipe', methods=['POST'])
def insert_recipe():
    recipes =  mongo.db.recipes
    recipes.insert(request.form.to_dict())
    return redirect(url_for('get_recipes'))

However, only the first selected option is being captured and sent.

Any help would be appreciated.

EDIT: When looking at: http://werkzeug.pocoo.org/docs/0.12/datastructures/#werkzeug.datastructures.MultiDict.to_dict

... relaised that I need to set to_dict(flat=false) in order to have all values of dict returned.

Kuyashii
  • 360
  • 1
  • 4
  • 21

1 Answers1

1

See EDIT above, the correct way is to:

# Send the form     
@app.route('/insert_recipe', methods=['POST'])
def insert_recipe():
    recipes =  mongo.db.recipes
    recipes.insert_one(request.form.to_dict(flat=False))
    return redirect(url_for('get_recipes'))

Also, just found a duplicate as notified by @davidism : Converting Flask form data to JSON only gets first value

Kuyashii
  • 360
  • 1
  • 4
  • 21