【问题标题】:Send form output to an if statement on the same webpage with Flask (python)使用 Flask (python) 将表单输出发送到同一网页上的 if 语句
【发布时间】:2021-11-02 17:21:17
【问题描述】:

我正在尝试使用 Flask 创建一个网页,该网页根据用户选择的单选按钮更改其内容。我不想重定向到一个全新的网页,我只是希望用户能够单击一个选项,然后将该选项显示给他们。我试图使下面的示例尽可能简单。这是来自python app main.py的代码

@app.route('/', methods = ['GET', 'POST'])
def index():
    return render_template("index.html")

def index(choice):
    return render_template('index.html', choice = choice)

def index():
    if request.method == 'POST':
        selection = request.form['options']
        return render_template('index.html', selection)
    else:
        return render_template('index.html')

这是index.html上的代码:

<form action="#" method='POST'>
    <p>Two buttons: </p>
    <p><input type = 'radio' name = 'options' value='YES'/>YES</p>
    <p><input type = 'radio' name = 'options' value='NO'/>NO</p>
    <p><input type= 'submit' value='submit'/></p>
</form>

{% if choice == 'YES' %}
    <h1>it works!</h1>
{% else %}
    <h1>nothing received</h1>
{% endif %}

我遇到的问题是 else 语句总是被执行,所以我从来没有看到网页显示“它有效!”。我也试过让 if 语句说 {% if choice %} 但它永远不会评估为真。 任何了解 Flask 的人都可以看到我在这里做错了什么吗?

【问题讨论】:

    标签: python html flask radio-button


    【解决方案1】:

    我想通了。我需要将choice 的默认值设置为None,并且不需要第一个索引函数(它什么也没做)。我需要指定choice = selection,而不是直接将“选择”变量传递给render_template 函数。 html 代码很好 - 问题只是我错了一些 python 语法。解决方法如下:

    @app.route('/', methods = ['GET', 'POST'])
    def index(choice = None):
        if request.method == 'POST':
            selection = request.form['options']
            return render_template('index.html', choice = selection)
        else:
            return render_template('index.html')
    
    def index(choice):
        return render_template('index.html', choice)
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 2019-02-25
      • 2021-08-18
      • 2019-12-27
      • 2021-07-29
      • 2015-04-27
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多