Last active
March 4, 2016 18:16
-
-
Save ja8zyjits/bd4cd3b1baabdc7c5672 to your computer and use it in GitHub Desktop.
WTForms populate_obj advantage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. It seems to work fine. Also, Have you tried https://github.com/kvesteri/wtforms-alchemy ?