Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create an array with checkboxes in Flask

Tags:

python

flask

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"]
like image 368
w4g Avatar asked Mar 05 '23 01:03

w4g


1 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']
like image 118
Wondercricket Avatar answered Mar 16 '23 21:03

Wondercricket