PerryDaPlatypus
PerryDaPlatypus

Reputation: 773

Getting information from HTML Form with checkboxes with Python Flask

I'm trying to dynamically create a web form with checkboxes and populate a list with the user selections. For example if the user were to select test1 and test2 from the form, I would expect to have a list in python of ['test1', 'test2'].

I am using Flask w/ Jinja2 and Python. However, when I submit the form, I receive a 400 Message (Bad Request).

Here is the relevant Python Code.

from flask import Flask, render_template, request, redirect

CASES = ['test1', 'test2', 'test3', 'test4']

@app.route("/")
def template_test():
return render_template('template.html', title="Home")

@app.route("/TestCases")
def TestCases():
    return render_template('testcases.html', cases=CASES, title="Test Cases")

@app.route("/info", methods=['POST'])
def getinfo():
    if request.method == 'POST':
        test = request.form['checks']
        print test
        return redirect('/')
    else:
        return redirect('/')

Here is the relevant html code from the template (testcases.html).

<form action="info" method="post" name="checks">
  {% for c in cases %}
  <input type="checkbox" name={{c}} value='checks'> {{c}}<br>
  {% endfor %}
  <br>
  <input type="submit" value="Submit">

I am not new to python, but this is my first foray using Flask and Jinja2.

Upvotes: 0

Views: 6197

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

There is no checks in the submitted form data, because there is no <input> element named "checks". To see what checkboxes where printed, try:

print request.form.keys()

or

for k,v in request.form.items():
    print k, v

One way to debug form subbmission is to use the services provided by httpbin.org, like so:

<form action="http://httpbin.org/post" method="post" name="checks">

When I select a couple of checkboxes, I get the following result. Note that each <input> element produced a distinct member of form.

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "test1": "checks", 
    "test3": "checks"
  }, 
  "headers": {
    ... # Deleted for brevity
}

One possible solution for you is to modify both your template and your app.

template:

<input type="checkbox" value="{{c}}" name="checks"> {{c}}<br>

app:

    test = request.form.getlist('checks')

Upvotes: 1

Related Questions