Files
pecan/docs/source/forms.rst
Doug Hellmann ee74648851 Clean up and update docs
Clean up some formatting issues in doc sources
and smooth out some wording.

Change-Id: I2bb2c9a32d67b71deeb7fcc13fd6a2949b4e195b
Signed-off-by: Doug Hellmann <doug.hellmann@dreamhost.com>
2013-05-03 18:25:20 -04:00

2.5 KiB
Raw Blame History

Generating and Validating Forms

Pecan provides no opinionated support for working with form generation and validation libraries, but its easy to import your library of choice with minimal effort.

This article details best practices for integrating the popular forms library, WTForms, into your Pecan project.

Defining a Form Definition

Let's start by building a basic form with a required first_name field and an optional last_name field.

from wtforms import Form, TextField, validators

class MyForm(Form):
    first_name = TextField(u'First Name', validators=[validators.required()])
    last_name = TextField(u'Last Name', validators=[validators.optional()])

class SomeController(object):
    pass

Rendering a Form in a Template

Next, let's add a controller, and pass a form instance to the template.

from pecan import expose
from wtforms import Form, TextField, validators

class MyForm(Form):
    first_name = TextField(u'First Name', validators=[validators.required()])
    last_name = TextField(u'Last Name', validators=[validators.optional()])

class SomeController(object):

    @expose(template='index.html')
    def index(self):
        return dict(form=MyForm())

Here's the Mako template file:

<form method="post" action="/">
    <div>
        ${form.first_name.label}:
        ${form.first_name}
    </div>
    <div>
        ${form.last_name.label}:
        ${form.last_name}
    </div>
    <input type="submit" value="submit">
</form>

Validating POST Values

Using the same MyForm definition, let's redirect the user if the form is validated, otherwise, render the form again.

from pecan import expose, request
from wtforms import Form, TextField, validators

class MyForm(Form):
    first_name = TextField(u'First Name', validators=[validators.required()])
    last_name = TextField(u'Last Name', validators=[validators.optional()])

class SomeController(object):

    @expose(template='index.html')
    def index(self):
        my_form = MyForm(request.POST)
        if request.method == 'POST' and my_form.validate():
            # save_values()
            redirect('/success')
        else:
            return dict(form=my_form)