Get the value of a checkbox in Flask Get the value of a checkbox in Flask python python

Get the value of a checkbox in Flask


You don't need to use getlist, just get if there's only one input with the given name, although it shouldn't matter. What you've shown does work. Here's a simple runnable example:

from flask import Flask, requestapp = 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()

Submitting the form with both boxes checked prints ['world', 'davidism'] in the terminal. Note that the html form's method is post so that the data will be in request.form.


While there are some cases where knowing the actual value or list of values of an field is useful, it looks like all you care about is whether the box was checked. In this case, it's more common to give the checkbox a unique name and just check if it has any value at all.

<input type="checkbox" name="match-with-pairs"/><input type="checkbox" name="match-with-bears"/>
if request.form.get('match-with-pairs'):    # match with pairsif request.form.get('match-with-bears'):    # match with bears (terrifying)


I found 4 ways to do that: Just to summarize:

# first wayop1 = request.form.getlist('opcao1') # [u'Item 1'] []op2 = request.form.getlist('opcao2') # [u'Item 2'] []op3 = request.form.getlist('opcao3') # [u'Item 3'] []# secondop1_checked = request.form.get("opcao1") != Noneop2_checked = request.form.get("opcao2") != Noneop3_checked = request.form.get("opcao3") != None# thirdif request.form.get("opcao3"):    op1_checked = True# fourthop1_checked, op1_checked, op1_checked = False, False, Falseif request.form.get("opcao1"):    op1_checked = Trueif request.form.get("opcao2"):    op2_checked = Trueif request.form.get("opcao3"):    op3_checked = True# last way that I found ..op1_checked = "opcao1" in request.formop2_checked = "opcao2" in request.formop3_checked = "opcao3" in request.form


When working with checkboxes in Flask, I opt to use the .get() method. This is because in my case (as is the case with checkboxes), the value of the checkbox returned is either 'on' or 'None' Consider the cases below:

  1. A common way of getting form data on POST request. When working with checkboxes, the solution below fails:

    username = request.form["uname"]
  2. Using the get method. This one works since the results from the form are in the form of a dictionary. The get method doesn't break when that value is None (as is the case with an unchecked checkbox):

    username = request.form.get("uname")