"Mike Hansen" <[EMAIL PROTECTED]> wrote

> I've got a web form with a lot of form fields. I'd like to be able 
> to map
> the form fields to an object's attributes. I'm having a little 
> trouble
> figuring out how.

John has answered that bit.

> There will be some fields I'll need to validate(boolean or int), but 
> the
> majority are just text fields that can be passed to the object.

One thing you can do is store the validation functions in the
dictionary with the value.

def intValidator(i):
     try: return int(i)
     except: return None

def boolValidator(b):
     try: return b and True or False
     except: return None

mapping = { 'field': (intvalue, intValidator),
                  'another': (boolvalue,boolValidator)...}

You can then access the validator like so:

value = mapping[fieldname][0]
validator = mapping[fieldname][1]
value = validator(value)
if value == None: #ooops!

or more concisely:

value = mapping[fieldname][1](mapping[fieldname]0])

This style of validation has the "benefit" (or side-effect if you 
prefer)
of converting compatible types into true types. eg. validating a 
string
or float representation of an integer returns the actual integer 
value.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to