Positive Incline Mike Burrows (@asplake) moving on up, positively

November 5, 2009

Nested forms in Pylons

Filed under: Web Integration — Tags: , — Mike @ 1:10 pm

Easy when you know how, but finding that out was struggle – at least it was for me! The crucial piece of information I was lacking was the correspondence between variabledecode.variable_encode() which flattens nested values into an array and variabledecode.NestedVariables which does the reverse.

I have factored these lines below out to my lib/base.py. Now all my form schemas (nested or not) inherit from BaseSchema and I use fill_render() whenever I want to render html with values.

import formencode
from formencode import htmlfill
from formencode import variabledecode

def fill_render(template_name, values):
    Render a template filled with values.  Values may be nested.
    return htmlfill.render(

class BaseSchema(formencode.Schema):
    Base form schema.  Any nested forms will be converted to nested values automatically.
    allow_extra_fields = True
    filter_extra_fields = True
    pre_validators = [variabledecode.NestedVariables()]

It leads to DRYer controller code, reduces the number of imports required and hides some complexity. Can’t understand why it isn’t the default already in Pylons, but hey, it works.

To see nested forms in action, go to the interesting but (at the time of writing) not quite complete Solving the Repeating Fields Problem (Pylons Book v1.1 documentation).

Credit to Ian Wilson for pointing me in the right direction in this thread on pylons-discuss.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress