Python Flask选择下拉项提交按钮

时间:2019-07-15 07:48:14

标签: python forms button flask

当用户单击“提交”按钮时,我试图通过下拉列表中的选定项目。

以下是HTML中的代码

  <form action="/switchinfo" method="post">
    <div align="center" id="mainselection">
      <select name="sites" method="GET" action="/">
        <option selected="selected">Select an the site</option>
        {% for site in sites[0:] %}
        <option value="{{site}}">{{site}}</option>
        {% endfor %}
      </select>
    </div>
    <button class="button execute" name="submit" value="submit">Submit</button>
  </form>

这是python代码

@app.route('/', methods=['GET', 'POST'])
def index():
    sites = ['DC1', 'DC2', 'DC3', 'DC4']
    return render_template('index.html', sites=sites)

@app.route('/switchinfo', methods=['POST'])
def switchinfo():
    gather = request.form["site"]
    return render_template("switchinfo.html",gather=gather)

if __name__ == "__main__":
    app.run()

得到错误werkzeug.exceptions.BadRequestKeyError。 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您对<select>标签的定义是错误的。它的名称必须与您查找的键匹配。

<form action="/switchinfo" method="post">
    <div align="center" id="mainselection">
      <select name="site">
        <option selected>Select an the site</option>
        {% for site in sites %}
        <option value="{{site}}">{{site}}</option>
        {% endfor %}
      </select>
    </div>
    <button class="button execute" name="submit" value="submit">Submit</button>
  </form>