vault backup: 2025-12-26 02:09:22
All checks were successful
Deploy Quartz site to GitHub Pages / build (push) Successful in 2m29s
All checks were successful
Deploy Quartz site to GitHub Pages / build (push) Successful in 2m29s
This commit is contained in:
58
stroma/quiz/views/submit_answer_view.py
Normal file
58
stroma/quiz/views/submit_answer_view.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.http import HttpResponse
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from quiz.models import QuizSession, Question, QuizResult
|
||||
from .get_session_questions_view import get_session_questions
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
def submit_answer(request, session_id):
|
||||
session = get_object_or_404(QuizSession, id=session_id, user=request.quiz_user)
|
||||
question_id = request.POST.get('question_id')
|
||||
selected_answer = request.POST.get('answer')
|
||||
|
||||
if not question_id or not selected_answer:
|
||||
return HttpResponse("Invalid submission", status=400)
|
||||
|
||||
try:
|
||||
question = Question.objects.get(id=question_id)
|
||||
except Question.DoesNotExist:
|
||||
return HttpResponse("Question not found", status=404)
|
||||
|
||||
# Normalize answers for comparison (sort comma-separated values)
|
||||
def normalize_answer(ans):
|
||||
if ',' in ans:
|
||||
return ','.join(sorted(ans.split(',')))
|
||||
return ans
|
||||
|
||||
is_correct = normalize_answer(selected_answer) == normalize_answer(question.correct_answer)
|
||||
|
||||
QuizResult.objects.update_or_create(
|
||||
user=request.quiz_user,
|
||||
question=question,
|
||||
quiz_session=session,
|
||||
defaults={
|
||||
'selected_answer': selected_answer,
|
||||
'is_correct': is_correct,
|
||||
}
|
||||
)
|
||||
|
||||
# Return the same question but with answer shown
|
||||
all_questions = get_session_questions(session)
|
||||
all_q_ids = list(all_questions.values_list('id', flat=True))
|
||||
current_index = all_q_ids.index(question.id) if question.id in all_q_ids else 0
|
||||
current_number = current_index + 1 # 1-based numbering
|
||||
|
||||
context = {
|
||||
'question': question,
|
||||
'session': session,
|
||||
'show_answer': True,
|
||||
'is_correct': is_correct,
|
||||
'has_previous': current_index > 0,
|
||||
'has_next': current_index < len(all_q_ids) - 1,
|
||||
'current_number': current_number,
|
||||
'total_questions': len(all_q_ids),
|
||||
}
|
||||
|
||||
return render(request, 'partials/quiz_question.html', context)
|
||||
|
||||
Reference in New Issue
Block a user