I am creating a quiz webapp using Flask and WTForms in which the user is shown a quiz which they can answer. The questions for the quiz come from a DB and hence the form to let the users answer the quiz is dynamic. Here is how the form class looks like:
class QuizForm(FlaskForm):
answers = FieldList(RadioField('Correct Answer', choices=CHOICES,
validators=[DataRequired()]),
min_entries=0)
submit = SubmitField('Submit your answers')
Before I serve the form, I append entries to the field list as follows:
questions = Question.query.all()
form = QuizForm()
for i, question in enumerate(questions):
form.answers.append_entry()
choices = [('1', question.option_a),
('2', question.option_b),
('3', question.option_c),
('4', question.option_d)]
form.answers.entries[i].choices = choices
This works well and creates the form as I would expect. But, I am not able to get validation to work where I want to make sure the user has answered all questions. This is how I am currently validating the form:
questions = Question.query.all()
form = QuizForm(request.form)
if request.method == 'POST':
if form.validate() and len(form.answers.entries) == len(questions):
# use form data
The problems I have are:
- I would ideally want the validation to work just using
form.validate(). - In the current approach, the values for
field.errorsare not set, and thus I can't show the user a message that a field is required right below the radio field containing the options for the question (using WTForms validation).
The full code can be seen at github.
What is a good way to implement validation for this use case?