将多选选项从Flask发送到MongoDB并返回

问题描述 投票:0回答:1

我正在使用前端CSS库Materialize而后端是Flask来构建在线食谱。因此,我在表单上有一个多选下拉列表,用于列出“过敏原”。

     <select name="allergens" multiple>
       <option value="" disabled selected>Select</option>
       <option>Wheat</option>
       <option>Soy</option>
       <option>Nuts</option>
     </select>
    <label>Allergens</label>
  </div>

我想在MongoDB中发送和存储多个选项,因为可能会有多个选项。目前,它仅向MongoDB发送一个选项。例如:

allergens: "Soy"

这是脚本:

@app.route('/edit_recipe/<recipe_id>')
def edit_recipe(recipe_id):
    one_recipe = mongo.db.recipe.find_one({"_id": ObjectId(recipe_id)})
    return render_template('editrecipe.html', item=one_recipe)


@app.route('/update_recipe/<recipe_id>', methods=['POST'])
def update_recipe(recipe_id):
    recipe = mongo.db.recipe
    recipe.update_one({'_id': ObjectId(recipe_id)}, {'$set': {
        'recipe_name': request.form['recipe_name'],
        'prep_time': request.form['prep_time'],
        'cook_time': request.form['cook_time'],
        'serves': request.form['serves'],
        'ingredients': request.form['ingredients'],
        'method': request.form['method'],
        'allergens': request.form['allergens']
        }})

    return redirect(url_for('get_recipes'))

所以问题是如何向数据库发送多个选项?目前,它只收到一个。另外,我需要将其返回给Flask模板,并让用户能够编辑其选项选择。

python mongodb flask pymongo
1个回答
0
投票

您可以在下拉菜单中使用复选框,请参见this。或者,您甚至可以将复选框保留在面板中,而不是放在下拉菜单中。

然后查看此answer以获取javascript中选定选项的数组。

然后,您可以执行ajax POST请求或普通POST请求,以将其发送到后端服务器,您可以在其中相应地在数据库中进行更改/更新

© www.soinside.com 2019 - 2024. All rights reserved.