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
363 views
in Technique[技术] by (71.8m points)

python - Get the value of a checkbox in Flask

I want to get the value of a checkbox in Flask. I've read a similar post and tried to use the output of request.form.getlist('match') and since it's a list I use [0], but it seems I'm doing something wrong. Is this the correct way to get the output 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
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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, 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 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 pairs

if request.form.get('match-with-bears'):
    # match with bears (terrifying)

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

...