'How to get Flask to save user input for radio button?
So I am trying to create an interactive quiz application using Flask. However, the issue I am running into is that I can't seem to save and output what the user selected. I tried to fix the quiz_answers function in the app.py and the quiz_solutions.html jinja2 syntax, but got an output that I did not want.
Example Question: What is 2+2?
Multiple choice: Option 1: 4, Option 2: 5, Option 3: 6, etc.
What I want the html page to show:
User selected: Option 2: 5
Correct Answer: Option 1: 4
Here is a what I currently have for app.py:
from flask import Flask, render_template, request
import random, copy
import questions
app = Flask(__name__)
copy_questions = copy.deepcopy(questions.original_questions)
def shuffle(q):
"""
This function is for shuffling
the dictionary elements.
"""
selected_keys = []
i = 0
while i < len(q):
current_selection = random.choice(list(q.keys()))
#current_selection = list(q.keys())
if current_selection not in selected_keys:
selected_keys.append(current_selection)
i = i+1
return selected_keys
questions_shuffled = shuffle(copy_questions)
@app.route('/')
def quiz():
#questions_shuffled = shuffle(copy_questions)
for i in copy_questions.keys():
random.shuffle(copy_questions[i])
return render_template('main.html', q = questions_shuffled, o = copy_questions)
@app.route('/solution', methods=['POST'])
def quiz_answers():
for i in copy_questions.keys():
answered = request.form[i]
if questions.original_questions[i][0] == answered:
return render_template('quiz_solutions.html',q = questions_shuffled, o = copy_questions)
break
if __name__ == '__main__':
app.run(debug=True)
questions.py:
original_questions = {
'What is 2+2': ['Option 1: 4', 'Option 2: 5', 'Option 3: 6',' etc.']
}
main.html:
<h1>Math Quiz</h1>
<form action='/solution' method='POST'>
<!--<form action='/' method='POST'>-->
<ol>
{% for i in q %}
<li>{{i}}</li>
{% for j in o[i] %}
<input type='radio' value='{{j}}' name='{{i}}' />{{j}}
<br>
{% endfor %}
<br>
{% endfor %}
<br>
<input type="submit" value="Submit" />
</ol>
</form>
quiz_solutions.html:
<h1>Math Quiz</h1>
<form method='POST'>
<ol>
{% for i in q %}
<li>{{i}}</li>
{% for j in o[i] %}
<input type='radio' value='{{j}}' name='{{i}}' />{{j}}
<br>
{% endfor %}
{% for j in o[i] %}
{% if j== o[i][0] %}
Correct answer: {{j}}
{% else %}
{% endif %}
{% endfor %}
<br>
{% endfor %}
</ol>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
