I made a simple form in Flask using Flask-WTForms where a parent can register itself and his children. The parent can register as many children as he wants, by clicking on t
For people who want to use the form in the more rudimentary non-RESTful way there is still the challenge of how to persist the form data correctly server side. If you don't do it right updating existing children in the form will append new children in the db rather than update existing ones. Below I provide two flask views, one for registering, and one for updating the registration. My view for updating the registration works but is a little kludgy. If anyone knows how to write it more elegantly I'd be psyched for some feedback:
@app.route('/register', methods=['GET', 'POST'])
def register():
form = ParentForm()
if form.add_child.data:
form.children.append_entry()
return render_template('register.html', form=form)
if form.validate_on_submit():
parentObj = Parent(name=form.name.data)
for child in form.children.data:
childObj = Child(name=child['name'],age=child['age'])
parentObj.children.append(childObj)
db.session.add(parentObj)
db.session.commit()
flash('Parent Added!!')
return redirect(url_for('home_page'))
return render_template('register.html', form=form)
@app.route('/update_registration', methods=['GET', 'POST'])
def update_registration():
parentObj = Parent.query.filter(Parent.id == 1).first()
form = ParentForm(id=parentObj.id, name=parentObj.name, children=parentObj.children)
if form.add_child.data:
form.children.append_entry()
return render_template('update_registration.html', form=form)
if form.validate_on_submit():
parentObj.name=form.name.data
# There should be a way to update the existing children objects rather than deleting and readding them
# But in the below we delete and re-add. Otherwise updated children simply append to existing children list
for i in range(len(parentObj.children)):
db.session.delete(parentObj.children[i])
for child in form.children.data:
childObj = Child(name=child['name'],age=child['age'])
parentObj.children.append(childObj)
db.session.add(parentObj)
db.session.commit()
flash('Parent [and children] Updated!!')
return redirect(url_for('home_page'))
return render_template('update_registration.html', form=form)