<form name=f1 method=post action=form-submit.py>
<table>
<tr><td>First Name </td><td><input type=text name=f_name><td></tr>
<tr><td>Second Name</td><td> <input type=text name=s_name></td></tr>
<tr><td>Sex</td><td> <input type=radio name=r1 value=male> Male
<input type=radio name=r1 value=female> Female </td></tr>
<tr><td>Class</td><td> <select name=class>
<option value='Three'>Three</option>
<option value='Four'>Four</option>
<option value='Five'>Five</option>
</select>
</td></tr>
<tr><td><input type=submit value=Submit></td><td> </td></tr>
</table>
</form>
The action attribute of above form is submitting to form-submit.py. print("HTTP/1.0 200 OK\n")
import cgi
form = cgi.FieldStorage()
f_name=form["f_name"].value
s_name=form["s_name"].value
r1=form["r1"].value
my_class=form["class"].value
print("<br><b>First Name</b>",f_name)
print("<br><b>Second Name</b>",s_name)
print("<br><b>Sex</b>",r1)
print("<br><b>Class</b>",my_class)
print("<br><br><br><a href=form.htm>Back to Form</a>")
Above code will display all the data submitted through the form. Here if any data is not filled then above code will generate error. We will use try catch error handling to manage the blank data.
print("HTTP/1.0 200 OK\n")
import cgi
form = cgi.FieldStorage()
try:
f_name=form["f_name"].value
except :
f_name=' First name is blank '
try:
s_name=form["s_name"].value
except :
s_name=' Second name is blank '
try:
r1=form["r1"].value
except :
r1=' No selection of Sex'
try:
my_class=form["class"].value
except:
my_class= ' Select Class '
print("<br><b>First Name</b>",f_name)
print("<br><b>Second Name</b>",s_name)
print("<br><b>Sex</b>",r1)
print("<br><b>Class</b>",my_class)
print("<br><br><br><a href=form.htm>Back to Form</a>")
Output is here
First Name First name
Second Name Second name
Sex male
Class Five
29-05-2023 | |
'cgi' is deprecated and slated for removal in Python 3.13 import cgi |
22-07-2023 | |
The FieldStorage class can typically be replaced with urllib.parse.parse_qsl() for GET and HEAD requests. More details are here https://docs.python.org/3.11/library/cgi.html |