微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?