Passing Checkbox Data to CGI Program in Python

Checkboxes are used when more than one option is required to be selected. In web forms, checkbox data is sent to CGI programs where it can be processed using Python's cgi module.

HTML Form with Checkboxes

Here is example HTML code for a form with two checkboxes −

<form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>

Form Output

The result of this code is the following form −

Maths Physics Select Subject

CGI Script to Handle Checkbox Data

Below is the checkbox.cgi script to handle input given by web browser for checkbox button −

#!/usr/bin/python3

# Import modules for CGI handling
import cgi
import cgitb

# Enable CGI error reporting
cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
if form.getvalue('maths'):
    math_flag = "ON"
else:
    math_flag = "OFF"

if form.getvalue('physics'):
    physics_flag = "ON"
else:
    physics_flag = "OFF"

# Print content type header
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Checkbox - Third CGI Program</title>")
print("</head>")
print("<body>")
print("<h2> CheckBox Maths is : %s</h2>" % math_flag)
print("<h2> CheckBox Physics is : %s</h2>" % physics_flag)
print("</body>")
print("</html>")

How It Works

The CGI script uses cgi.FieldStorage() to retrieve form data. The getvalue() method returns the checkbox value if selected, or None if unchecked. Based on this, we set appropriate flags to display the checkbox status.

Conclusion

CGI programs can easily handle checkbox data using Python's cgi module. Use getvalue() to check if checkboxes are selected and process the data accordingly.

Updated on: 2026-03-25T07:51:17+05:30

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements