获取Flask中的复选框的值 [英] Get the value of a checkbox in Flask

查看:2195
本文介绍了获取Flask中的复选框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取Flask中的复选框的值。我阅读了类似帖子,并尝试使用 request.form.getlist('match')的输出,因为它是一个列表,我使用 [0] ,但似乎我做错了。这是获取输出的正确方法还是有更好的方法?

I want to get the value of a checkbox in Flask. I've read a similar post and tried to use the output of request.form.getlist('match') and since it's a list I use [0], but it seems I'm doing something wrong. Is this the correct way to get the output or is there a better way?

<input type="checkbox" name="match" value="matchwithpairs" checked> Auto Match





if request.form.getlist('match')[0] == 'matchwithpairs':
    # do something


推荐答案

您不需要使用 getlist ,只需 get 如果只有一个输入与给定的名称,虽然它不重要。你显示的是工作。下面是一个简单的可运行的例子:

You don't need to use getlist, just get if there's only one input with the given name, although it shouldn't matter. What you've shown does work. Here's a simple runnable example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        print(request.form.getlist('hello'))

    return '''<form method="post">
<input type="checkbox" name="hello" value="world" checked>
<input type="checkbox" name="hello" value="davidism" checked>
<input type="submit">
</form>'''

app.run()


$ b b

在终端中提交带有两个复选框的表单 ['world','davidism'] 。注意,html表单的方法是 post ,因此数据将在 request.form 中。

Submitting the form with both boxes checked prints ['world', 'davidism'] in the terminal. Note that the html form's method is post so that the data will be in request.form.

虽然有些情况下知道某个字段的实际值或值列表很有用,但看起来你所关心的是检查框。在这种情况下,更常见的是给复选框一个唯一的名称,只检查它是否有任何值。

While there are some cases where knowing the actual value or list of values of an field is useful, it looks like all you care about is whether the box was checked. In this case, it's more common to give the checkbox a unique name and just check if it has any value at all.

<input type="checkbox" name="match-with-pairs"/>
<input type="checkbox" name="match-with-bears"/>





if request.form.get('match-with-pairs'):
    # match with pairs

if request.form.get('match-with-bears'):
    # match with bears (terrifying)

这篇关于获取Flask中的复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆