[debexpo-devel] Pylons form validation via formencode

Christoph Haas email at christoph-haas.de
Tue Jun 17 11:05:34 CEST 2008


Hi, Jonny...

as per our chat on IRC I wanted to send you some code how I validate forms.
Usually form handling is done through "formencode" and the @validate
decorator provided by Pylons. Search the Pylons Wiki for "form handling"
and you'll see a standard way of handling things.

I didn't like the inflexibility of @validate and rather use this in my code
(my.py):

def validate(schema):
    """Validate a formencode schema. On success returns a dictionary of values
    from request.params. On failure throws a formencode.Invalid exception."""
    return schema.to_python(pylons.request.params)

def htmlfill(html, exception_error=None):
    """Fills a string containing the HTML page with error messages from
    a 'formencode' form validation. 'html' contains the HTML (e.g. returned
    from render()) and exception_error is the formencode.Invalid exception
    thrown earlier."""
    log.debug('my.htmlfill formencode exception: %s' % (exception_error,))
    return formencode.htmlfill.render(
        form=html,
        defaults=pylons.request.params,
        errors=(exception_error and exception_error.unpack_errors()),
        encoding=pylons.response.determine_charset()
    )

Actually my code has a few extra lines where I deal with the infamous "state".
But I think you can ignore that for now.

And this is how I use it in my controller:

        try:
            fields = my.validate(some_validation_schema)
        except formencode.Invalid, e:
            return my.htmlfill(self.some_action_to_display_the_original_page_again, e)

If the validation worked I have the form fields in the "fields" dictionary.
Otherwise an exception gets thrown that my.htmlfill() handles. The original
HTML page is rendered again and formencode.htmlfill.render() fills it with
additional error messages right above each field.

</2¢>

 Christoph
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://workaround.org/pipermail/debexpo-devel/attachments/20080617/1555bb60/attachment.pgp 


More information about the debexpo-devel mailing list