Как добавить результаты в тест в приложении Django quiz?
Я только осваиваю Django и пытаюсь создать тест. Я посмотрел видео на YouTube, но не совсем понял, как добавить результаты теста на страницу. Я создал тест, и в базе данных SQLite я могу создать категории, вопросы, ответы и баллы за ответы. Как я могу снять баллы за ответы после отправки ответов.Я бы хотел, чтобы ответы отображались на странице quiz_detail. В виде правильных/неправильных (под каждым вопросом) или в виде "Общего балла".
Quiz_detail.html
{% extends "base.html" %}
{%block content%}
<div class="parent-div">
<div class="centered-div">
<h3 class="title">{{quiz.title}}</h3>
<form method="post" id="quizform" action="{% url 'quiz_submit' quiz.id %}">
{%csrf_token%}
{%for question in questions%}
<h2> {{question.text}}</h2>
<h2 class="white-container">{{question}}</h2>
<h3 class="grey-container">
{%for choice in question.choices.all%}
<input
type="radio"
id="choice_{{choice.id}}"
name="question_{{question.id}}"
value="{{choice.id}}"
/>
<label for="choice_{{choice.id}}">{{choice.text}}</label>
<br />
{%endfor%}
{%endfor%}
</h3>
<button type="submit">Submit quiz</button>
</form>
{% block title %}Result{% endblock %}
</div>
</div>
{%endblock%}
models.py
class Question(models.Model):
text = models.CharField(max_length=225)
quiz = models.ForeignKey(Quiz, related_name="questions", on_delete = models.CASCADE)
def __str__(self) -> str:
return self.text
class Choice(models.Model):
text = models.CharField(max_length=225)
question = models.ForeignKey(Question, related_name="choices", on_delete = models.CASCADE)
score = models.FloatField(default=0)
is_correct = models.BooleanField('Correct', default=False)
comment = models.CharField('comment', default=False, max_length=225)
def __str__(self) -> str:
return self.text
class UserResponse(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete = models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete = models.CASCADE)
selected_choice = models.ForeignKey(Choice, on_delete = models.CASCADE)
def __str__(self) -> str:
return f"{self.user.username}'s response to {self.question.text} in {self.quiz.title} is {self.choice.text}"
def calculate_score(self):
total_score = sum(choice.score for choice in self.question.choice.all())
return total_score
urls.py
urlpatterns = [path("", views.index, name="index"),
path("quiz/<int:quiz_id>", views.quiz_detail, name="quiz_detail"),
path("quiz/<int:quiz_id>/submit", views.quiz_submit, name="quiz_submit")]
views.py
def index(request):
quizzes = Quiz.objects.filter(is_ready_to_publish = True)
context ={"quizzes":quizzes}
return render(request, "index.html", context=context)
@login_required(login_url='login')
def quiz_detail(request, quiz_id):
quiz = get_object_or_404(Quiz, id=quiz_id)
questions = quiz.questions.all()
context = {"quiz": quiz, "questions":questions}
return render(request, "quiz_detail.html", context)
@login_required(login_url='login')
def quiz_submit(request, quiz_id):
if request.method == "POST":
quiz = get_object_or_404(Quiz, id=quiz_id)
questions = quiz.questions.all()
error_message = None
for question in questions:
choice_id = request.POST.get(f"question_{question.id}", None)
if choice_id:
choice = get_object_or_404(Choice, id=choice_id)
UserResponse.objects.create(
user=request.user,
quiz=quiz,
question=question,
selected_choice=choice
)
else:
error_message = "you need select answers"
if error_message:
messages.error(request, error_message)
context={"quiz":quiz, "questions":questions}
return render(request, "quiz_detail.html", context)
messages.success(request, "Quiz submitted")
return redirect("index")
return redirect("quiz_detail", quiz_id=quiz_id)
здесь моя база данных с ответами