Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models?

I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have:

# the model - assumes Flask-SQLAlchemy
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Person(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

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


# the form - assumes Flask-WTF ext.
from flask.ext.wtf import Form, TextField, Required, BooleanField

class PersonForm(Form):
    name = TextField('name')


## the view
@app.route('/person/edit/<id>/', methods=['GET', 'POST'])
def edit_person(id):
    person = Person.query.get(id)
    if person:
        form = PersonForm(person) #<-- raises error
        return render_template('edit_person.html', form=form)

I could assign each field in the form to each field of the model (form.data['name'] = person.name, etc...), but that seems redundant for large models. Is there any shortcut I'm missing?

like image 859
sa125 Avatar asked Oct 03 '10 17:10

sa125


1 Answers

Please refer to the wtforms documentation:

http://wtforms.simplecodes.com/docs/0.6/forms.html#wtforms.form.Form

You pass in the "obj" as argument. This will bind the model properties to the form fields to provide the default values:

@app.route('/person/edit/<id>/', methods=['GET', 'POST'])
def edit_person(id):
    person = Person.query.get_or_404(id)
    form = PersonForm(obj=person)
    if form.validate_on_submit():
        form.populate_obj(person)

Notice also the "populate_obj" method. This is a handy shortcut which will bind the form values to the model properties (only those fields you have defined in your form, so quite safe to use).

like image 63
zeemonkee Avatar answered Sep 21 '22 14:09

zeemonkee