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)
@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