Flask isn't getting the checkbox value

后端 未结 1 844
耶瑟儿~
耶瑟儿~ 2020-12-06 14:20

I am trying to print off the checkbox value in Flask when I hit the submit button.

app.py snippet:

@app.route(\'/test2\', methods=[\         


        
相关标签:
1条回答
  • 2020-12-06 14:51

    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)
    
    0 讨论(0)
提交回复
热议问题