Auto-generated, customizable HTML input form fields from your SQLAlchemy mapped classes.
FormAlchemy greatly speeds development with SQLAlchemy mapped classes (models) in a HTML forms environment.
FormAlchemy eliminates boilerplate by autogenerating HTML input fields from a given model. FormAlchemy will try to figure out what kind of HTML code should be returned by introspecting the model’s properties and generate ready-to-use HTML code that will fit the developer’s application.
Of course, FormAlchemy can’t figure out everything, i.e, the developer might want to display only a few columns from the given model. Thus, FormAlchemy is also highly customizable.
Check out the instructions for InstallingFormAlchemy.
To get started, you only need to know about two classes, FieldSet and Grid, and a handful of methods:
This introduction illustrates these three methods. For full details on customizing FieldSet behavior, see the documentation.
We’ll start with two simple SQLAlchemy models with a one-to-many relationship (each User can have many Orders), and fetch an Order object to edit:
from formalchemy.tests import Session, User, Order session = Session() order1 = session.query(Order).first()
Now, let’s render a form to edit the order we’ve loaded:
from formalchemy import FieldSet, Grid fs = FieldSet(order1) print fs.render()
This results in the following form elements:
Note how the options for the User input were automatically loaded from the database. str() is used on the User objects to get the option descriptions.
To edit a new object, bind your FieldSet to the class rather than a specific instance:
fs = FieldSet(Order)
To edit multiple objects, bind them to a Grid instead:
orders = session.query(Order).all() g = Grid(Order, orders) print g.render()
Which results in:
Saving changes is similarly easy. (Here we’re using Pylons-style request.params; adjust for your framework of choice as necessary):
fs = FieldSet(order1, data=request.params) if fs.validate(): fs.sync() session.commit()
Grid works the same way.
FormAlchemy’s documentation is available here. Some good starting points are
Copyright (C) 2007 Alexandre Conrad, alexandre dot conrad at gmail dot com
FormAlchemy is released under the MIT License.