Reputation: 25
I have a Flask app that is a basic quiz app. A user answers a question and in the view I verify if the answer was correct or not. The problem I am having is that the correct response is not being compared correctly with the user's answer. It seems to be looking at the next form's correct answer instead of comparing the current form's correct answer.
I've tried to use an intermediate view to check the correct answer as well as use session variables. It always seems like it's checking the correct answer against the next form's values.
Thank you in advance for your attention.
My Form code:
class QuizForm(FlaskForm):
question = ''
answer = RadioField('Answer',coerce=int,
choices=[],validators=[DataRequired()])
submit = SubmitField('Submit')
correct = HiddenField('Correct')
def validate_answer(self,answer):
if answer is None:
raise ValidationError('Please select an answer')
My Routes code:
@app.route('/quiz', methods=['GET','POST'])
@login_required
def quiz():
form = QuizForm()
#qq = Database entry for questions/choices/correct answer..
form.question = qq.question
form.answer.choices = [(1,qq.choice1), (2, qq.choice2),
(3,qq.choice3), (4, qq.choice4)]
form.correct = qq.answer
if form.validate_on_submit():
if form.answer.data == form.correct:
flash('Correct')
else:
flash('Incorrect!')
return redirect(url_for('quiz'))
return render_template('quiz.html',form=form)
My html:
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.question }}
{{ form.answer }}
{% for error in form.answer.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
Upvotes: 0
Views: 59
Reputation: 36
You must make two separate routes: @app.route ('/quiz', methods=['GET']) @app.route ('/quiz', methods=['POST'])
Upvotes: 2