pattern for processing HTML form with multiple rows?

Greg Jorgensen gregj at pobox.com
Sat Feb 17 21:15:56 EST 2001


On Tue, 13 Feb 2001 16:58:38 GMT,
u504516601 at spawnkill.ip-mobilphone.net wrote:

>Architecture: Python, ASP, MsSQL
>
>Want to have a form for inserting records into a database. 
>Would like to offer a grid so that user can enter multiple 
>records at one time. Assume data validation provided through 
>pulldowns for key fields.
>
>What's the "best" approach for looping over the fields 
>and performing the inserts?

You can set up your HTML form "grid" a couple of ways. One way is to
give the fields in each grid row different names. Another way is to
reuse the form field names.

Example 1:

<form method="POST" action="cgi.py">
<input type="hidden" name="numrows" value="10">
<table>
<tr>
    <td><input type="text" name="r1f1"></td>
    <td><input type="text" name="r1f2"></td>
</tr>
<tr>
    <td><input type="text" name="r2f1"></td>
    <td><input type="text" name="r2f2"></td>
</tr>
...
<tr>
    <td><input type="text" name="r10f1"></td>
    <td><input type="text" name="r10f2"></td>
</tr>
</table>
</form>


In your Python CGI program:

import cgi
form = cgi.FieldStorage()
numrows = form["numrows"]     # passed from form
for r in range(1,numrows+1):    # for each row...
    f1 = form["r" + str(r) + "f1"].value    # get field f1
    f2 = form["r" + str(r) + "f2"].value    # get field f2
    # do something with fields f1 & f2
    # note that the fields may be empty


Example 2:

<form method="POST" action="cgi.py">
<table>
<tr>
    <td><input type="text" name="f1"></td>
    <td><input type="text" name="f2"></td>
</tr>
<tr>
    <td><input type="text" name="f1"></td>
    <td><input type="text" name="f2"></td>
</tr>
...
<tr>
    <td><input type="text" name="f1"></td>
    <td><input type="text" name="f2"></td>
</tr>
</table>
</form>

Note that the fields have the same name in each row. The Python code
is:

import cgi
form = cgi.FieldStorage()
rows = len(form["f1"])    # f1, f2 are lists, one entry per row
for i in range(rows):
    f1 = form["f1"][i].value
    f2 = form["f2"][i].value
    # do something with fields f1 & f2
    # note that the fields may be empty


I can't say which method may work best for you. You can only go so far
simulating a grid-type data entry widget in HTML. The main point to
remember is that if an HTML form has more than one field with the same
name, the values are sent to the receiving CGI program in a
comma-separated list.


Greg Jorgensen
Deschooling Society
Portland, Oregon USA



More information about the Python-list mailing list