Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

python - Flask isn't getting the checkbox value

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'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...