Add aggregated response summary and user answer filtering in exam review
This commit is contained in:
@@ -1216,6 +1216,53 @@ class ExamViews(View, LoginRequiredMixin):
|
||||
"can_edit": self.check_user_edit_access(request.user, exam_id=pk),
|
||||
}
|
||||
|
||||
# Compute aggregated response summary for this question within the current exam.
|
||||
# Add counts and percentages to the context so fragments (e.g. SBAS) can display them.
|
||||
try:
|
||||
if hasattr(question, "cid_user_answers"):
|
||||
ua_qs = question.cid_user_answers.filter(exam=exam)
|
||||
total_responses = ua_qs.count()
|
||||
counts = {}
|
||||
for ans in ua_qs.values_list("answer", flat=True):
|
||||
counts[ans] = counts.get(ans, 0) + 1
|
||||
|
||||
# Compute percentages per answer key
|
||||
pcts = {}
|
||||
if total_responses:
|
||||
for k, v in counts.items():
|
||||
pcts[k] = round(100.0 * v / total_responses, 1)
|
||||
else:
|
||||
for k in counts.keys():
|
||||
pcts[k] = 0.0
|
||||
|
||||
# If the question exposes a best_answer, compute correct count
|
||||
correct_count = None
|
||||
if hasattr(question, "best_answer") and question.best_answer:
|
||||
correct_count = ua_qs.filter(answer=question.best_answer).count()
|
||||
else:
|
||||
correct_count = None
|
||||
|
||||
# percent correct
|
||||
correct_pct = None
|
||||
if correct_count is not None and total_responses:
|
||||
try:
|
||||
correct_pct = round(100.0 * correct_count / total_responses, 1)
|
||||
except Exception:
|
||||
correct_pct = None
|
||||
|
||||
context.update(
|
||||
{
|
||||
"exam_response_counts": counts,
|
||||
"exam_response_pcts": pcts,
|
||||
"exam_response_total": total_responses,
|
||||
"exam_response_correct_count": correct_count,
|
||||
"exam_response_correct_pct": correct_pct,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
# Best-effort: don't fail the review page if aggregation errors occur
|
||||
pass
|
||||
|
||||
# Choose an app-specific fragment if present, otherwise fall back to
|
||||
# the generic fragment. Expose the chosen fragment name in the
|
||||
# context so the full-page render can include it; return the fragment
|
||||
|
||||
Reference in New Issue
Block a user