rablentain
rablentain

Reputation: 6715

Pass form data directly to SQLalchemy object?

I am using Flask with WTForms and SQLAlchemy. I currently have this set up:

A SQLAlchemy class:

class User(Base):
    __tablename__ = 'user'
    name = db.Column(db.String)
    last_name = db.Column(db.String)

    __init__(name, last_name):
        self.name = name
        self.last_name = last_name

The corresponding form:

class CreateUserForm(Form):
    name = StringField('Name')
    last_name = StringField('Last name')

And the route:

@user.route('/', methods=['POST'])
def create():
    form = CreateUserForm(request.form)

    if form.validate():
        user = User(form.name.data, form.last_name.data)
        ...

This is just a simplified example but what I wonder is if I could just in some way just pass the form variable to the User constructor and all the way to the User class in SQLAlchemy? Since there will be the same fields in the form as in the constructor as in the user database table it would be nice.

I want my route to look like this instead:

@user.route('/', methods=['POST'])
def create():
    form = CreateUserForm(request.form)

    if form.validate():
        user = User(form)
        ...

So I don't have to deal with form.name and form.last_name in each part.

Upvotes: 1

Views: 3419

Answers (1)

pjcunningham
pjcunningham

Reputation: 8046

To set a form's data from an existing model use the following:

my_model = # ...

form = CreateUserForm(obj=my_model)

To set a model from a populated form, e.g. after a post back, use the following:

form = CreateUserForm(request.form)
if form.validate_on_submit():
    user = User()
    form.populate_obj(user) # Copies matching attributes from form onto user

See the documentation at WTForms. Also consider using Flask-WTF and WTForms-Alchemy.

Upvotes: 10

Related Questions