【问题标题】:Get the value of a checkbox in Flask获取 Flask 中复选框的值
【发布时间】:2015-10-29 20:18:33
【问题描述】:
我想获取 Flask 中复选框的值。我读过similar post 并尝试使用request.form.getlist('match') 的输出,因为它是我使用[0] 的列表,但似乎我做错了什么。这是获取输出的正确方法还是有更好的方法?
<input type="checkbox" name="match" value="matchwithpairs" checked> Auto Match
if request.form.getlist('match')[0] == 'matchwithpairs':
# do something
【问题讨论】:
标签:
python
checkbox
flask
【解决方案1】:
您不需要使用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()
在选中两个框的情况下提交表单会在终端中打印['world', 'davidism']。注意html表单的方法是post,所以数据会在request.form中。
虽然在某些情况下知道字段的实际值或值列表很有用,但您似乎只关心该框是否被选中。在这种情况下,更常见的是给复选框一个唯一的名称,然后检查它是否有任何值。
<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)
【解决方案2】:
我找到了 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
【解决方案3】:
在 Flask 中使用复选框时,我选择使用 .get() 方法。这是因为在我的情况下(与复选框一样),返回的复选框的值是“开”或“无”考虑以下情况:
-
在 POST 请求中获取表单数据的常用方法。使用复选框时,以下解决方案失败:
username = request.form["uname"]
-
使用get方法。由于表单的结果是以字典的形式出现的,因此此方法有效。当该值为 None 时,get 方法不会中断(与未选中的复选框一样):
username = request.form.get("uname")