问题
I have this flask app:
import os
import random
from flask import Flask, render_template, request
app = Flask(__name__)
quiz_host = os.environ.get('FLASK_HOST')
quiz_port = os.environ.get('FLASK_PORT')
questions = [{'id':1, 'question':'what is 2 + 3','correct':'2','choices':['1','2','3',5']}, {'id':2,'question':'what is 4 + 6',correct':'10','choices':['10','11','12','13']}]
@app.route("/quiz", methods=['POST', 'GET'])
def quiz():
if request.method == 'GET':
return render_template("index.html", data=questions)
else:
result = 0
total = 0
for question in questions:
if request.form[question.get('id')] == question.get('correct'):
result += 1
total += 1
return render_template('results.html', total=total, result=result)
if __name__ == "__main__":
app.run(host=quiz_host, port=quiz_port)
Right now you can see, on the results page, it just prints the total, and the results. I would like the results page to instead print all of the questions on the index.html page, for each MCQ, highlighting the question the student clicked, and the right answer was, so the student can see what they got right and wrong (because right now, the results page just says 'you got 5/11 answers right').
I'm not sure how to do this. I guess (1) i need to edit the 'else' loop in the above script, (2) i need to change what is returned from the function. I'm stuck on how to do it specifically and I can't find anything online about it. Can anyone help?
Edit 1:
I added this to the results.html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Junior Cert Random Question Generator</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='styles/stylesheet_results.css') }}">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<div>
<h1>Your Results!</h1>
<br>
<h2>You scored {{ result }} out of {{ total }}!</h2>
{% for question in data %}
<h3>{{ question.question }}</h3>
{% for answer in question.answers %}
<input type="radio" id="{{ answer }}" name="{{ question.id }}" value="{{ answer }}"> {{ answer }}<br>
{% endfor %}
{% endfor %}
</div>
</body>
</html>
So now the questions are replicated on the results.html page.
回答1:
You can simply do that using jinja syntax in your template.In your else part as you are returning a template only with total and result but you should also add questions as you did in if part and then as you know the right answer, you can highlight that.Then get the response of the user by request.form.get('user_response') where 'user_response' is the name of the input field where he can submit the answer.Then again using jinja highlight that by transferring that to your template using variable like you did with total and result.
来源:https://stackoverflow.com/questions/63320621/python-flask-return-mcq-output-with-right-and-chosen-answers-highlighted