如何解决在 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,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">
发送表单数据
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。