Get the value of a checkbox in Flask
Last Updated :
02 Aug, 2024
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>
Similar Reads
How to get all checked values of checkbox in JavaScript ?
A checkbox is a selection box that enables users to pick true or false in a binary manner by checking or unchecking it. When a checkbox is checked, it shows that the value has been chosen by the user, and when a checkbox is not checked indicates false which denotes that the user has not chosen the v
2 min read
How to Add Checkbox in HTML Table ?
Adding checkboxes to an HTML table can be useful for various purposes, such as selecting multiple rows for batch processing or toggling the state of individual items. In this article, we will explore two methods to add checkboxes to an HTML table i.e. using basic HTML and JavaScript for dynamic inte
2 min read
How To Get Multiple Checkbox Values In ReactJS?
Handling checkboxes in ReactJS becomes important when creating forms or managing user input. If you need to select multiple options, we can do it by implementing multiple checkboxes. In this article, we'll explore how to get the values of multiple checkboxes in ReactJS, manage the state, and display
4 min read
How to get the total number of checkboxes in a page using Selenium?
In the world of automated testing, Selenium is a powerful tool that helps automate web browsers. One common task during web testing is determining the number of specific elements on a page, such as checkboxes. This can be useful for validating the presence and quantity of checkboxes on a form or any
3 min read
How to change the checkbox value using jQuery ?
The Checkboxes are used to let a user select one or more options for a limited number of choices. The :checkbox selector selects input elements with type checkbox.Syntax: $('#textboxID').val($("#checkboxID").is(':checked')); In the above syntax, basically the return value of the checked or unchecked
2 min read
session._get_current_object() in Flask
The session._get_current_object() method returns a session object for the current request that is made. It stores the information on the client's computer as it works on the client side. The exact object returned by the session._get_current_object() method completely depends on the implementation of
3 min read
How to Create a Checkbox in HTML?
The checkbox is the HTML form element that lets users select one or more options from predefined choices. It can often be used when a user selects multiple items in the list. Checkboxes can be checked or unchecked, and they are created using the <input> tag with the type attributes set to the
3 min read
How to Use CSS in Python Flask
Flask is a popular web framework for Python that makes it easy to build web applications. One of the key elements of any web application is styling, which is where CSS (Cascading Style Sheets) comes in. CSS allows us to control the look and feel of our web pages, making them more attractive and user
3 min read
PyQt5 â Set Skin to unchecked CheckBox when pressed
In this article we will see how to set skin to check box when it is already in unchecked state and when it get pressed. By default there is no skin associated to the check box, skin is basically background image that can adjust it self according to the size of check box. In order to do add skin to t
2 min read
PyQt5 â Set skin to unchecked CheckBox when pressed
In this article we will see how we can set skin to the indicator of the check box who is in unchecked state and get pressed. This skin only appear when check box get pressed and its state was unchecked. In order to add skin to the indicator when check box is in unchecked state and get pressed we hav
2 min read