def edit(id): session = db.session() try: test = session.query(Test).filter(Test.id == id).one() except NoResultFound: return render_template('layout.html', error='No such test') form = TestEditingForm(request.form, test) all_attributes = db.session().query(Attribute).all() if request.method == 'POST' and form.validate(): # length of any of nested lists must be no less than that of respective form's list for i in range(len(form.questions)): if i >= len(test.questions): test.questions.append(Question()) for j in range(len(form.questions[i].choices)): if j >= len(test.questions[i].choices): test.questions[i].choices.append(Choice()) for k in range(len(form.questions[i].choices[j].associations)): if k >= len(test.questions[i].choices[j].associations): test.questions[i].choices[j].associations.append(Association()) form.populate_obj(test) session.add(test) session.commit() flash('Test updated') return redirect(url_for('general.admin')) attr_id_to_name = {a.id: a.name for a in all_attributes} return render_template('edit_test.html', form=form, all_attributes=all_attributes, attr_id_to_name=attr_id_to_name)
def create(): form = TestEditingForm(request.form) if request.method == 'POST' and form.validate(): session = db.session() t = Test(title=form.title.data, description=form.description.data) for qf in form.questions: q = Question(text=qf.text.data) t.questions.append(q) for of in qf.choices: o = Choice(text=of.text.data) q.choices.append(o) for af in of.associations: a = Association(attribute_id=af.attribute_id.data, choice_id=af.choice_id.data) o.associations.append(a) session.add(t) session.commit() flash("Test added") return redirect(url_for('general.admin')) all_attributes = db.session().query(Attribute).all() return render_template('edit_test.html', form=form, all_attributes=all_attributes)