Open In App

Get the value of a checkbox in Flask

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The checkbox is a typical widget with selected options within a list by a user. They are employed in web forms whereby they are applied in the selection of preferences, settings, or a survey. Here in this article, we will see how to add the checkboxes in the Flask application right from the installation of Flask to the handling of inputs.

Get the value of a checkbox in Flask

Here is the most basic requirement before we start doing the checkboxes, we require a flask application. Flask is a framework for creating web applications based on Python, it is micro, which is why it doesn’t contain a lot of components, but it provides the features needed to start an application. Follow these steps to set up your Flask environment:

Follow these steps to set up your Flask environment:

Step 1: Install Flask

If you haven't already, install Flask using pip. Open your terminal or command prompt and run:

pip install Flask

Step 2: Create a Flask Application

Create a new directory for your project and navigate to it. Inside this directory, create a file named app.py. This file will be the main entry point for our Flask application.

Step 3: Create a Template Directory

Create a folder named templates in the same directory as app.py. Inside the templates folder, create a file named index.html.

Creating Checkboxes

In the index.html file, we will create a form with checkboxes. Each checkbox will allow the user to select an option, and when the form is submitted, the selected options will be sent to the server.

Code Implementation

Here is the complete example code for the Flask application with checkboxes:

index.html

In this example, we have created a form with three checkboxes and a submit button. Each checkbox has a unique id and value attribute. The name attribute for all checkboxes is the same (checkbox), which allows us to handle them as a group on the server side.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Example</title>
</head>
<body>
    <form action="/submit" method="post">
        <label for="option1">Option 1</label>
        <input type="checkbox" id="option1" name="checkbox" value="Option 1"><br>
        <label for="option2">Option 2</label>
        <input type="checkbox" id="option2" name="checkbox" value="Option 2"><br>
        <label for="option3">Option 3</label>
        <input type="checkbox" id="option3" name="checkbox" value="Option 3"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

app.py

Python
from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route('/submit', methods=['POST'])
def submit():
    selected_options = request.form.getlist('checkbox')
    return f'Selected options: {", ".join(selected_options)}'

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

Output

Best Practices to ensure your Application File

When working with checkboxes in Flask, consider the following best practices to ensure your application is robust and user-friendly:

Use Descriptive Labels: Ensure that each checkbox has a clear and descriptive label. This improves the user experience and accessibility, making it easier for users to understand the options available to them.

Validate User Input: Always validate the user input on the server side to ensure that the data received is as expected. This prevents malicious input and ensures data integrity. For example, you can check if the selected options are within the allowed set of values:

Handle Multiple Checkboxes: Use request.form.getlist('checkbox') to handle multiple checkboxes with the same name attribute. This method returns an array of all selected options, which is convenient on selection of multiple options.

Maintain State: If you need to preserve the state of the checkboxes (e.g., when a form submission fails and needs to be corrected), consider passing the selected values back to the template and pre-selecting the checkboxes based on these values. Here’s an example of how you can achieve this:

Use CSRF Protection: When working with form submissions user should take Care against Cross-Site Request Forgery attack. Flask-WTF is an extension that assists Flask applications to add CSRF protection. To use it, install Flask-WTF and configure it in your application:

pip install Flask-WTF
Python
@app.route('/')
def index():
    selected_options = ['Option 1', 'Option 3']  # Example selected options
    return render_template('index.html', selected_options=selected_options)

In index.html:

HTML
<input type="checkbox" id="option1" name="checkbox" value="Option 1" {% if 'Option 1' in selected_options %}checked{% endif %}>
<input type="checkbox" id="option2" name="checkbox" value="Option 2" {% if 'Option 2' in selected_options %}checked{% endif %}>
<input type="checkbox" id="option3" name="checkbox" value="Option 3" {% if 'Option 3' in selected_options %}checked{% endif %}>

2. How can I style checkboxes?

You can style checkboxes using CSS. Here’s an example:

CSS
input[type="checkbox"] {
    width: 20px;
    height: 20px;
    accent-color: #007bff; /* Change the color of the checkbox */
}

Add the CSS to a <style> tag in your HTML file or to a separate CSS file linked in your HTML.

3. How can I handle dynamic checkbox lists?

If you need to generate checkboxes dynamically (e.g., from a database), pass the list of options to the template and loop through them in your HTML. Here’s an example:

In app.py:

Python
@app.route('/')
def index():
    options = ['Option 1', 'Option 2', 'Option 3', 'Option 4']
    return render_template('index.html', options=options)

index.html:

Python
<form action="/submit" method="post">
    {% for option in options %}
        <label for="{{ option }}">{{ option }}</label>
        <input type="checkbox" id="{{ option }}" name="checkbox" value="{{ option }}"><br>
    {% endfor %}
    <input type="submit" value="Submit">
</form>



Next Article
Practice Tags :

Similar Reads