Skip to content

Instantly share code, notes, and snippets.

@ja8zyjits
Last active March 4, 2016 18:16
Show Gist options
  • Save ja8zyjits/bd4cd3b1baabdc7c5672 to your computer and use it in GitHub Desktop.
Save ja8zyjits/bd4cd3b1baabdc7c5672 to your computer and use it in GitHub Desktop.
WTForms populate_obj advantage
##Complex Models:
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
reports = db.relationship(
'Report', backref='profile_of_report', lazy='dynamic')
class Report(db.Model):
id = db.Column(db.Integer, primary_key=True)
profile_id = db.Column(db.Integer, db.ForeignKey(Profile.id))
disease_name = db.Column(db.String(50))
reported_date = db.Column(db.DateTime(), default=datetime.now())
##The form:
class ProfileForm(Form):
name = StringField('Name', validators=[validators.Required()])
reports = FieldList(FormField(ReportForm), min_entries=2)
class ReportForm(Form):
disease_name = StringField('Disease Name')
reported_date = DateField('Reported Date', default=date.today())
##The view:
def profile_page():
form = ProfileForm()
if request.method == 'POST':
if form.validate_on_submit():
profile = Profile()
for _ in form.reports #we create the same number of object which we need to populate.
profile.reports.append(Report())
form.populate_obj(profile)
db.session.add(profile)
db.session.commit()
return render_template('profile_page.html', form=form)
@ja8zyjits
Copy link
Author

Have problems with wtforms populate_obj?
Even I had few and this hetsch gist helped me to understand the working. Also this wtform google mailing list support of the same gist helped me realize what was I doing wrong.
I also followed the second link and this statement For that to work, the items must already exist in the list of the original object. In your case, your 'plugins' don't exist in your 'post' object, thus they cannot be updated gave me a better idea. check this out. This new idea was inspired from the gist but has no relation to the problem mentioned in hetsch gist.

Basically populate_obj of the wtfform helps us to dynamicallly populate our model data. But there is a small issue with the FieldList and FormField, the model objects should exist.

Check this out.
Well it was true that you need an object to exist to pass a value, and now you can see how easy data population is with Wtfforms.

@fpilee
Copy link

fpilee commented Mar 4, 2016

Thanks. It seems to work fine. Also, Have you tried https://github.com/kvesteri/wtforms-alchemy ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment