Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pass Radio Button Data to Python CGI script?
Radio buttons allow users to select exactly one option from a group of choices. When working with CGI (Common Gateway Interface) in Python, you can easily retrieve and process radio button data using the cgi module.
HTML Form with Radio Buttons
Here is example HTML code for a form with two radio buttons ?
<form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank"> <input type = "radio" name = "subject" value = "maths" /> Maths <input type = "radio" name = "subject" value = "physics" /> Physics <input type = "submit" value = "Select Subject" /> </form>
The result of this code is the following form ?
Maths Physics [Select Subject]
Python CGI Script
Below is radiobutton.py script to handle input given by web browser for radio 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('subject'):
subject = form.getvalue('subject')
else:
subject = "Not set"
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Radio Button - CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Selected Subject is %s</h2>" % subject)
print("</body>")
print("</html>")
How It Works
The CGI script processes radio button data through these steps ?
-
cgi.FieldStorage()creates an instance to access form data -
form.getvalue('subject')retrieves the selected radio button value - The script checks if a value exists before processing
- HTML response is generated with the selected value
Key Points
- All radio buttons in a group must have the same
nameattribute - Each radio button has a unique
valueattribute - Only one radio button can be selected at a time
- Use
cgitb.enable()for debugging CGI scripts
Conclusion
Radio button data is passed to CGI scripts through form submission and retrieved using cgi.FieldStorage(). Always validate the data exists before processing to avoid errors in your CGI application.
Advertisements
