如何使用flask从下拉菜单中获取值

时间:2021-03-14 17:49:13

标签: javascript python html flask

在单击 UI 如下所示的提交按钮后,我试图从下拉菜单中获取值:

以上代码如下:

app.py

from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True


@app.route('/', methods=['GET'])
def dropdown():
    colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
    return render_template('feba.html', colours=colours)

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

index.html 在模板文件夹中

<!DOCTYPE html>
<html lang="en">

<style>
    body {text-align:center}
</style>

<head>
    <meta charset="UTF-8">
</head>

<body>

    <img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
    <h1>KARDFINDER</h1>
    <h2>json file generator for banks</h2>

        <select name="colour" method="GET" action="/">
      <option value="{{colours[0]}}" selected>{{colours[0]}}</option>
      {% for colour in colours[1:] %}
        <option value="{{colour}}">{{colour}}</option>
      {% endfor %}
        </select>

      <input type= "submit" name="submitbutton" value ="Submit"></body>
</html>


logo_1.jpg 在静态文件夹中

我发布此问题的主要目的是获得一个解决方案,借助该解决方案,我可以在单击提交按钮后从下拉菜单中获取值,并且我希望将该值存储在应用程序的变量中。 py文件

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

以下代码适用于我,

from flask import Flask, render_template, request, redirect
app = Flask(__name__)
app.debug = True


@app.route('/', methods=['GET'])
def dropdown():
    colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
    return render_template('feba.html', colours=colours)


@app.route('/dropdown', methods = ['POST'])
def dropp():
    dropdownval = request.form.get('colour')
    print(dropdownval)
    return redirect("/", code=302)
if __name__ == "__main__":
    app.run()

<!DOCTYPE html>
<html lang="en">

<style>
    body {text-align:center}
</style>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
    <h1>KARDFINDER</h1>
    <h2>json file generator for banks</h2>
     <form method="POST" action="/dropdown">
        <select name="colour">
      <option value="{{colours[0]}}" selected>{{colours[0]}}</option>
      {% for colour in colours[1:] %}
        <option value="{{colour}}">{{colour}}</option>
      {% endfor %}
        </select>
      <input type="submit" value ="Submit">
      </form>
</body>
</html>

你应该学习http requestshtml formsajax

答案 1 :(得分:0)

您也可以将索引和下拉页面合二为一:

from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
app.debug = True

@app.route('/', methods=['GET','POST'])
def dropdown():
    colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
    if request.method=='POST':
        var = request.form['var']
    return render_template('feba.html', colours=colours)

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

这个比较简单。您可以使用与 Mert Celik 相同的 html 代码,但将 action="/dropdown" 更改为 action="/"