这是html和flask python代码。当用户从下拉菜单中选择奥迪时,我希望它给出完成作为答案。我收到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')
答案 0 :(得分:0)
在路线中使用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>
<强>输出:强>