通过菜单获取下拉菜单上Flask上的数据给出了400错误请求

胡沙里沙阿

这是html和flask的python代码。当用户从下拉菜单中选择Audi时,我希望它给出Done作为答案。我收到400错误的请求错误。

form.html

<!DOCTYPE html>
 <html>
 <body>

<p>Select a new car from the list.</p>
<form id="form1" action="/login" method="GET" enctype="multipart/form-data">
<select id="mySelect" name = "cars">
  <option value="Audi">Audi</option>
  <option value="BMW">BMW</option>
  <option value="Mercedes">Mercedes</option>
  <option value="Volvo">Volvo</option>
</select>
</form>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

</body>
</html>

app.py

from flask import Flask, render_template, redirect, url_for,request
from flask import make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
    c=str((request.form['cars']))
    print(c)
    if(c == "Audi"):
           print("Done")
    return render_template('form.html')
Arsho

print在路由中使用不会影响模板。渲染时,您需要向模板传递变量。

当您打算使用时multipart/form-data,可能需要使用POST方法。

我正在展示一个可以根据您的要求进行修改的方案。

app.py 包含:

from flask import Flask, render_template, request, url_for, redirect

app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    return render_template("dropdown.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == "POST":
        car_brand = request.form.get("cars", None)
        if car_brand!=None:
            return render_template("dropdown.html", car_brand = car_brand)
    return render_template("dropdown.html")

if __name__ == '__main__':
    app.run(debug=True)

dropdown.html 包含一个带有提交按钮的简单选择标签,并显示所选值:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="Ahmedur Rahman Shovon">
    <title>Dropdown Example</title>
</head>
<body>
  <p>Select a new car from the list.</p>
  <form id="form1" action="/login" method="POST" enctype="multipart/form-data">
    <select id="mySelect" name = "cars">
      <option value="Audi">Audi</option>
      <option value="BMW">BMW</option>
      <option value="Mercedes">Mercedes</option>
      <option value="Volvo">Volvo</option>
    </select>
    <input type="submit" value="Submit">
  </form>
  <p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
  <div id="result">
    {% if car_brand is defined %}
        You have selected: {{ car_brand }}
    {% endif %}
  </div>
</body>
</html>

输出:

下拉演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章