Flask没有获取复选框值 [英] Flask isn't getting the checkbox value
问题描述
我尝试在我按下提交按钮时打印Flask中的复选框值。
app.py snippet: p>
@ app.route('/ test2',methods = ['GET','POST'])
def test2 ():
if request.method ==POST:
if request.form ['submit'] =='submit':
print(request.args。 get('check'))
return render_template('test.html')
HTML :
< form role =formmethod =post>
< input type =checkboxname =checkvalue =test>
< button type =submitname =submitvalue =submit>提交< / button>
< / form>
< / div>
当我点击提交按钮时返回None。
我也试过request.form.get()
@ app.route('/ test2' ,method = ['GET','POST'])
def test2():
if request.method ==POST:
if request.form [ submit'] =='submit':
print(request.form.get('check'))
return render_template('test.html')
这也会返回None。
解决方案提交HTML表单时,未选中的复选框不会发送任何数据。在Flask的一边,
形式
中不会有键,因为没有接收到值。如果要检查是否选中了单个复选框(具有唯一名称),只需测试其名称是否在表单
中。如果要检查是否选中了多个复选框(同名),请改用getlist
。
一个布尔值:
< input type =checkboxname =check>
'in request.form
多个选项:
< pre class =lang-html prettyprint-override>< input type =checkboxname =checkvalue =1>
< input type =checkboxname =checkvalue =2>
< input type =checkboxname =checkvalue =3>
selected = form.getlist('check')
any_selected = bool(selected)
I am trying to print off the checkbox value in Flask when I hit the submit button.
app.py snippet:
@app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.args.get('check'))
return render_template('test.html')
HTML:
<div class="container"><br>
<form role="form" method="post">
<input type="checkbox" name="check" value="test">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
It returns 'None' when I hit the submit button.
I have also tried request.form.get()
@app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.form.get('check'))
return render_template('test.html')
That also returns 'None'.
When submitting an HTML form, unchecked checkboxes do not send any data. On Flask's side, there will not be a key in form
, since no value was received. If you want to check if a single checkbox (with a unique name) is checked, just test if it's name is in form
. If you want to check which of multiple checkboxes (with the same name) are checked, use getlist
instead.
One boolean:
<input type="checkbox" name="check">
checked = 'check' in request.form
Multiple options:
<input type="checkbox" name="check" value="1">
<input type="checkbox" name="check" value="2">
<input type="checkbox" name="check" value="3">
selected = request.form.getlist('check')
any_selected = bool(selected)
这篇关于Flask没有获取复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!