1

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.

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I will try that! Just for curiosity, why does it exist special packages for Flask in most cases? What is better with Flask-WTF instead of the original package?
@theva - Flask-WTF and WTForms-Alchemy both help with cutting out boilerplate coding - especially as your Flask projects grow in complexity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.