knoedge knoedge - 1 year ago 86
Python Question

Populate an App Engine NDB entity with data from WTForms

I'm looking for a more elegant way to populate an App Engine Datastore entity from a WTForms model without assigning each property one at a time.

I remember seeing something similar done with


WTForm model for the edit profile page, like this:

class EditProfile(Form):
first_name = StringField('First Name')
last_name = StringField('Last Name')

NDB model for users:

class User(ndb.Model):
first_name = ndb.StringProperty()
last_name = ndb.StringProperty()

Note: all property names of both models identical.

Request handler for the edit profile page:

@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
form = EditProfile()

if request.method == 'POST':
if form.validate_on_submit():
user = User.get_by_id(session.get('user_id'))



Answer Source

Use populate_obj method.

Populates the attributes of the passed obj with data from the form’s fields.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download