Get flag value in Flask

I want to get the flag value in Flask. I read a similar post and tried to use the output of request.form.getlist('match') , and since I use [0] , but it seems like I'm doing something wrong. Is this the right way to get the result, or is there a better way?

 <input type="checkbox" name="match" value="matchwithpairs" checked> Auto Match 
 if request.form.getlist('match')[0] == 'matchwithpairs': # do something 
+4
source share
2 answers

You do not need to use getlist , just get if there is only one input with the given name, although it does not matter. What you showed works. Here is a simple example:

 from flask import Flask, request app = 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 to both check boxes verifies the print ['world', 'davidism'] in the terminal. Please note that the method of the html form is post , so the data will be in request.form .


While there are times when it is useful to know the actual value or list of field values, it seems that all you care about is checking the checkbox. In this case, it’s more common to check the unique name box and just check to see if it has any meaning.

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

I found 4 ways to do this: just to summarize:

 # first way op1 = request.form.getlist('opcao1') # [u'Item 1'] [] op2 = request.form.getlist('opcao2') # [u'Item 2'] [] op3 = request.form.getlist('opcao3') # [u'Item 3'] [] # second op1_checked = request.form.get("opcao1") != None op2_checked = request.form.get("opcao2") != None op3_checked = request.form.get("opcao3") != None # third if request.form.get("opcao3"): op1_checked = True # fourth op1_checked, op1_checked, op1_checked = False, False, False if request.form.get("opcao1"): op1_checked = True if request.form.get("opcao2"): op2_checked = True if request.form.get("opcao3"): op3_checked = True # last way that I found .. op1_checked = "opcao1" in request.form op2_checked = "opcao2" in request.form op3_checked = "opcao3" in request.form 
+7
source

All Articles