Pylons integration¶
Bootstrap your project¶
FormAlchemy come with a subclass of the Pylons template. If you have Pylons and FormAlchemy installed you should see that:
$ paster create --list-templates
Available templates:
basic_package: A basic setuptools-enabled package
paste_deploy: A web application deployed through paste.deploy
pylons: Pylons application template
pylons_fa: Pylons application template with formalchemy support
pylons_minimal: Pylons minimal application template
To bootstrap a new Pylons project with FormAlchemy support enable just run:
$ paster create -t pylons_fa pylonsapp
Using forms in controllers¶
Imagine you have a Foo model in your model/__init__.py then your controller can look like this:
import logging
from pylons import request, response, session, url, tmpl_context as c
from pylons.controllers.util import abort, redirect
from pylonsapp.lib.base import BaseController, render
from pylonsapp.model import meta
from pylonsapp import model
from pylonsapp.forms import FieldSet
log = logging.getLogger(__name__)
Foo = FieldSet(model.Foo)
Foo.configure(options=[Foo.bar.label('This is the bar field')])
class BasicController(BaseController):
def index(self, id=None):
if id:
record = meta.Session.query(model.Foo).filter_by(id=id).first()
else:
record = model.Foo()
assert record is not None, repr(id)
c.fs = Foo.bind(record, data=request.POST or None)
if request.POST and c.fs.validate():
c.fs.sync()
if id:
meta.Session.update(record)
else:
meta.Session.add(record)
meta.Session.commit()
redirect(url.current(id=record.id))
return render('/form.mako')
If you have a lot of fieldset and configuration stuff and want to use them in
different controller, then you can use the forms/ module to put your
fieldsets. This is a standard and allow you to use the
formalchemy.ext.pylons extension
You can also have a look at the RESTful Controller