capitalg
capitalg

Reputation: 663

Flask: request.form.getlist won't return any entries

for some reason I can't get this thing I worked 4 weeks ago working :/ I have a site where I add a checkbutton via jQuery and I need Flask to read out if it's checked or not. I made a minmial example, but it still doesn not work.

Heres the code:

post.htm

<html>
<body>
<form name="formular" action='http://127.0.0.1:5000/formtest' method="post">
<input type="checkbox" value="test1">
<INPUT type ="submit" id="send" value="Do it"/>
</form>
</body>
</html>

webserver.py

@app.route('/formtest', methods=['POST'])
def formtest():
    checklist = request.form.getlist('test1')
    if checklist:
        check = True
    else:
        check = False
    if check:
        return("checked")
    else:
        return("not checked")

It always returns "not checked", but I don't get why. Checklist is always an empty list. Where's the error?

Thanks in advance!

Upvotes: 2

Views: 11837

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121168

Your checkbox has no name attribute; it'll never be sent as part of the POST. Give it a name attribute as well as a value:

<input type="checkbox" name="test1" value="true">

Don't use MultiDict.getlist() here; you can use MultiDict.get() with a default and type conversion instead:

@app.route('/formtest', methods=['POST'])
def formtest():
    check = request.form.get('test1', default=False, type=bool)
    return 'checked' if check else 'not checked'

Upvotes: 3

Related Questions