Flask没有获取复选框值 [英] Flask isn't getting the checkbox value

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

问题描述

我尝试在我按下提交按钮时打印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屋!

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