March 18, 2008

Formencode example

Filed under: dev, orm, python, web2py — michaelangela @ 9:20 am

A full example, albeit with SQLObject, but the concept is pretty clear. With web2py, the form.validate would be followed with an explicit data insert. From the looks of the **form_result insert, form.validate returns a list of fields that can be directly inserted. The same format should be able to be used with Storm.

Handling Form data with Formencode + SQLObject

Two of my favorite and most often-used Python packges are formencode and sqlobject.
Using these packages together is done fairly often, but I’ve rarely
seen any documentation describing a full form display, validation, and
insert into a database of new data from said form.

In this example, I’ve tried to wean down the code as much as possible
to get a very concise snippet (only 12 lines of web page Controller
code) that will:

  1. Display a new form to the user
  2. Handle form submission
  3. Validate the form
  4. Coerce form values into the proper types for the database
  5. Insert the form data to the database, or
  6. Display the form with error messages, and maintain their values

nice thing about using formencode, is that 3 of the 6 steps I listed
above are handled by it in a fairly automatic way. Formencode will
check the data given a form schema, coerce the values into the Python
types you ask for, fill in errors should they occur, and maintain the
existing values.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: