[mod_python] Submitting a form with unknown number of items

Graham Dumpleton grahamd at dscpl.com.au
Fri May 27 23:33:44 EDT 2005


On 28/05/2005, at 10:22 AM, Jason Lanquist wrote:

> Hi there, I can handle form data when I know how many items are  
> returned.  I use a fixed number of parameters when someone signs up  
> like:
>
> def form_submit1(req,uname,passwd,passwd2,email,city,st,zip,country):
>  ...
>  ...
>  ...
>
> But when I have a varying number of form items (they are generated by  
> data) I'm not sure how many there will be so how is that handled?  I  
> tried to use "FieldStorage" as the only parameter (thinking it would  
> be a list of form items) besides req but that doesn't work:
>
> def buy_fromstore(req,FieldStorage):
>  ...
>  ...
>  ...
>
> How do you handle form data when you don't know how many items will be  
> returned?

Assuming here that you are using mod_python.publisher. If that is the  
case, define
your method to accept a keyword parameter list argument. You can then  
go through
the dictionary keys and look for form parameters:

   def buy_fromstore(req,**params):
     for name in params.keys():
       req.log_error(str((name,params[name])))

You can still have named parameters at the same time:

   def buy_fromstore(req,uname,passwd,**params):
     ...

You obviously need to interpret the names of the form parameters in the  
dictionary.

For a different way of doing this, you might look at Vampire. When  
using its equivalent
to mod_python.publisher, you can have form parameters labeled as:

   item-1
   item-2
   item-3

and they willbe  automatically passed as a single parameter called  
"item" where the
value for each actual form parameter is then stored in a list. One  
could also have:

   entry.a
   entry.b
   entry.c

and the result will be a dictionary instead of a list. One can mix the  
form naming
conventions to get combination of both.

See:

   http://www.dscpl.com.au/projects/vampire/articles/vampire-003.html

for a description of how Vampire treats form parameters. Although the  
documentation
mainly shows use of this mechanism for Vampire's basic content  
handlers, also applies
to vampire:publisher drop in replacement for mod_python.publisher.

This form of automatic conversion of form parameters into structured  
lists and
dictionaries is really useful for example when you have a large list of  
selectable
items in a form. The selected set of items ends up being in one  
parameter which you
just iterate over.

If you want to play with this without getting down Vampire, construct  
some forms
following the conventions and post it to:

    
http://www.dscpl.com.au/projects/vampire/examples/templates/ 
form_values.html

Eg:

    
http://www.dscpl.com.au/projects/vampire/examples/templates/ 
form_values.html?a-1=a1&a-2=a2&b.c=bc&b.d=bd

Graham



More information about the Mod_python mailing list