diff --git a/physics/views.py b/physics/views.py index 7e4c3085..e08e45ac 100644 --- a/physics/views.py +++ b/physics/views.py @@ -198,11 +198,25 @@ def exam_take(request, pk: int, sk: int, cid: str| None = None, passcode: str| N cid_user_exam = exam.get_or_create_cid_user_exam(cid=cid, user_user=request.user) - question = exam.get_questions()[sk] + # Use a single, canonical list of questions for all indexing/navigation + # operations to avoid mismatches between different querysets or orderings. + questions = list(exam.get_questions()) - exam_length = len(exam.exam_questions.all()) + # Validate sk and select the current question + try: + sk = int(sk) + except Exception: + raise Http404("Invalid question index") - pos = exam.get_question_index(question) + if sk < 0 or sk >= len(questions): + raise Http404("Question not found in exam") + + question = questions[sk] + + exam_length = len(questions) + + # Since we're using the canonical list, the positional index is sk. + pos = sk if cid is not None: answer = question.cid_user_answers.filter(cid=cid, exam=exam).first()