pythonsqlalchemyformalchemy

Adding SQLAlchemy records with Formalchemy


I am trying to use Formalchemy to add a new record to my SQLAlchemy table DataTBL.

fs = FieldSet(DataTBL)
fs.bind(DataTBL, request=requestobject)

if fs.validate():
    fs.sync()
    session.commit()

This gives me a validation error because the DataTable object is still empty...

ValidationError: Cannot validate without binding data

How do I use Formalchemy to start with an empty form that has the DataTBL structure, fill the form and validate/submit it?


Solution

  • You need a request.POST to use .validate()

    Try:

    fs = FieldSet(DataTBL)
    fs = fs.bind(DataTBL, request=requestobject)
    
    if requestobject.POST and fs.validate():
        fs.sync()
        session.add(fs.model)
        session.commit()