Processing the form data

The form we created on the previous page asks the user to enter their name into the provided text box. The user is then requested to click on the submit button to send the form data to the server. What happens when the submitted form reaches the server is determined by the action attribute.

Our form has the following action attribute:

<form method="post" action="processname.cgi">

This means that the processname.cgi script is supposed to handle the submitted form data. We will need to create the script.

Field storage

To access the data submitted by the form in our script we will need to make use of the FieldStorage() function available in the cgi module of Python.

For example, we would assign the data from the form to a Python variable in the following way:

formData = cgi.FieldStorage()

The variable formData now contains every piece of data submitted by the form.

Getting individual values

Clear we will need to access the individual submitted values - in this case the actual submitted name. Python has a function we can use for this purpose as well. It is called getvalue().

In order to use the getvalue() function you need to know the name of the html form component you wish to retrieve data from. Our form had the following components:

html form showing name attribute

If we know the name of the component we can then use the formData variable in conduction with the getvalue() function to retrieve the data stored:

formData = cgi.fieldStorage()
firstName = formData.getvalue('firstname')

Once the data is in a Python variable you can treat it like any other variable you have created previously.

Creating the processing script

The video below demonstrates how to create the processing script in full:

Task 6a

Create a basic form with help from the above video.

Multiple pieces of data

In the above example we processed a form with only a single text box. As long as you know the name attribute of each form element it is possible to process multiple items from a form.

Task 6b

Extend your form so that you ask for the users surname, date of birth and e-mail address.

Use the new HTML5 form elements for:

  • E-Mail addresses
  • Date pickers

In addition, make sure that all fields are required fields.