How create an array with checkboxes in Flask

Viewed 6770

I'm starting in flask, so i have many questions about it. And one of them is how to create an array based on name of the checkbox input? In other words, python will follow the logic: for each of type "checkbox", which ones were filled?

I have those codes: index.html

{% block content %}


<form method="POST" action="">
<div class="card" style="margin:50px 0">
    <div class="card-header"><b>Letters</b></div>

    <ul class="list-group list-group-flush">
    <li class="list-group-item">A
    <label class="switch ">
    <input type="checkbox" name="A" class="danger">
    <span class="slider round"></span>
    </label>
    </li>
    <li class="list-group-item">B
    <label class="switch ">
    <input type="checkbox" name="B" class="danger">
    <span class="slider round"></span>
    </label>
    </li>
    <li class="list-group-item">C
    <label class="switch ">
    <input type="checkbox" name="C" class="danger">
    <span class="slider round"></span>
    </label>
    </li>
    </ul>
    <button type="submit">Go</button>
</div>
</form>

{% endblock content %}

And funcs.py

from flask import Flask, render_template, url_for, redirect, request

app = Flask(__name__)

app.config['SECRET_KEY'] = '0000'


@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

When the user has checked boxes named "A" and "C", python creates an array and display the array shortly afterwards when the user submit.

checked = ["A", "C"]
2 Answers

Your HTML is heading in the right direction, but a few minor changes for Flask to handle this effectively.

First, set the current value of the name attribute to the value attribute. This will determine values Flask pulls during the form post. Secondly, set the name attribute to have a common value.

<input type="checkbox" value="A" class="danger" name='my_checkbox'>
<input type="checkbox" value="B" class="danger" name='my_checkbox'>
<input type="checkbox" value="C" class="danger" name='my_checkbox'>

After the HTML is configured as such, you can use the getlist method from Flask's request module.

print(request.form.getlist('my_checkbox'))
>>> ['A', 'C']

When a POST request is sent to the flask server you can get form contents from request.form. which is a dictionary based off of the POST request.

With check boxes, if the box is ticked the input name in <input type="checkbox" name="A" class="danger"> would be in this dictionary. Therefore you can check for the check box like so:

if "A" in request.form:
    checked.append("A")  # You can of course append any arbitrary value
Related