获取Flask中复选框的值

Jaq*_*cky 14 python checkbox flask

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

<input type="checkbox" name="match" value="matchwithpairs" checked> Auto Match
Run Code Online (Sandbox Code Playgroud)
if request.form.getlist('match')[0] == 'matchwithpairs':
    # do something
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 29

您不需要使用getlist,只要get一个输入具有给定名称,尽管它无关紧要.你所展示的确有效.这是一个简单的可运行示例:

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()
Run Code Online (Sandbox Code Playgroud)

提交带有两个方框的表格,['world', 'davidism']在终端上打印.请注意,html表单的方法是post这样的,数据将在request.form.


虽然在某些情况下,知道字段的实际值或值列表是有用的,但看起来您关心的是该框是否已被选中.在这种情况下,更常见的是给复选框一个唯一的名称,并检查它是否具有任何值.

<input type="checkbox" name="match-with-pairs"/>
<input type="checkbox" name="match-with-bears"/>
Run Code Online (Sandbox Code Playgroud)
if request.form.get('match-with-pairs'):
    # match with pairs

if request.form.get('match-with-bears'):
    # match with bears (terrifying)
Run Code Online (Sandbox Code Playgroud)


Sil*_*ago 13

我找到了4种方法:总结一下:

# first way
op1 = request.form.getlist('opcao1') # [u'Item 1'] []
op2 = request.form.getlist('opcao2') # [u'Item 2'] []
op3 = request.form.getlist('opcao3') # [u'Item 3'] []

# second
op1_checked = request.form.get("opcao1") != None
op2_checked = request.form.get("opcao2") != None
op3_checked = request.form.get("opcao3") != None

# third
if request.form.get("opcao3"):
    op1_checked = True

# fourth
op1_checked, op1_checked, op1_checked = False, False, False
if request.form.get("opcao1"):
    op1_checked = True
if request.form.get("opcao2"):
    op2_checked = True
if request.form.get("opcao3"):
    op3_checked = True

# last way that I found ..
op1_checked = "opcao1" in request.form
op2_checked = "opcao2" in request.form
op3_checked = "opcao3" in request.form
Run Code Online (Sandbox Code Playgroud)