Multiple Field NamesΒΆ

If there is more than one field with the same name like in HTML input check boxes then the method to be used is cgi.FieldStorage.getlist(). It will return a list containing as many items (the values) as checked boxes. If no check box was checked the list will be empty.

Sample HTML with check boxes:

<form method="post" action="">
Red<input type="checkbox" name="color" value="red">
Green<input type="checkbox" name="color" value="green">
<input type="submit" value="Submit">

And the corresponding script:

#!/usr/bin/env python
import cgi
form = cgi.FieldStorage()

# getlist() returns a list containing the
# values of the fields with the given name
colors = form.getlist('color')

print "Content-Type: text/html\n"
print '<html><body>'
print 'The colors list:', colors
for color in colors:
    print '<p>', cgi.escape(color), '</p>'
print '</body></html>'