在Flask中刷新页面时传递单选按钮值



我正在尝试用Python构建一个简单的Flask应用程序,有两个单选按钮和一个"刷新"按钮,当单击刷新按钮时,页面将重新加载并显示上一页上的单选按钮选择。

Routes.py:

@app.route("/")
def display():
return render_template("index.html", choice=choice)
if request.form['submit'] == 'Refresh':
choice= request.form.get("Choice")
return redirect(url_for('/'))

index . html:

<html>
<head>
<title>Choice</title>
</head>
<body>
<h2>Choice</h2>
<hr>
{{choice}}<br>
<form action="">
<input type="radio" name="Choice" value="Choice1"><span>Choice 1/span><br/>
<input type="radio" name="Choice" value="Choice2"><span>Choice 2</span>
<input type="submit" name="refresh" value="Refresh">
</form><br>
</form> </body>
</html>

应用以下更改并检查是否有效!

使用render_template, request, redirect, url_for,但未导入。尝试导入它们。

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

要检索POST数据,可以使用request.form。要检索GET数据,可以使用request.args

如果您想使用request.args,请尝试以下代码:

@app.route("/")
def display():
choice = request.args.get('Choice','None Selected')
return render_template("index.html", choice=choice)
if request.args.get('refresh') == 'Refresh':
return redirect(url_for('display',Choice=choice))

如果你想使用request.form,试试下面的代码:


@app.route("/",methods = ['POST', 'GET'])
def display():
if request.method == 'GET':
choice = request.args.get('Choice','None Selected')
return render_template("index.html", choice=choice)
if request.method == 'POST':
choice= request.form.get("Choice")
return redirect(url_for('display',Choice=choice))

在index.html中添加<form action="" method="POST">来发送表单数据

最新更新