Add exam review question responses and summary views with HTMX support

This commit is contained in:
Ross
2025-11-10 12:49:10 +00:00
parent eaf8a38fe2
commit bd81fdcf41
6 changed files with 245 additions and 2 deletions
@@ -23,7 +23,7 @@
<pre>{{ans}}</pre>
</span>
{% if exam.publish_results or view_all_results%}
<span class="answer-score">{{score}}</span>
Marks: <span class="answer-score">{{score}}</span>
{% endif %}
</span>
<span class="view-question-link" data-qn={{forloop.counter0}}>View</span>
@@ -1,4 +1,4 @@
{% extends 'generic/examcollection_base.html' %}
{% extends exam.app_name|add:'/exams.html' %}
{% block content %}
<div class="container my-4">
@@ -0,0 +1,50 @@
{# Responses partial for physics question within an exam. HTMX-loadable. #}
<div id="physics-responses-container">
<h6>Responses in this exam</h6>
<div class="d-flex justify-content-between align-items-center mb-2">
<div class="small text-muted">List of candidate answers recorded for this question in the current exam.</div>
<div>
{% if reveal_respondents %}
<button class="btn btn-sm btn-outline-secondary" hx-get="{% url 'physics:exam_review_question_responses' exam.pk q_index %}" hx-target="#physics-responses-container" hx-swap="outerHTML">Hide respondents</button>
{% else %}
<button class="btn btn-sm btn-outline-primary" hx-get="{% url 'physics:exam_review_question_responses' exam.pk q_index %}?reveal=1" hx-target="#physics-responses-container" hx-swap="outerHTML">Show respondents</button>
{% endif %}
</div>
</div>
<ul class="list-group">
{% for ua in exam_user_answers %}
<li class="list-group-item d-flex justify-content-between align-items-start">
<div>
{% if reveal_respondents %}
{% if ua.user %}
<strong>{{ ua.user.get_full_name|default:ua.user.username }}</strong>
{% else %}
<strong>Anonymous</strong>
{% endif %}
{% else %}
<strong>Respondent {{ forloop.counter }}</strong>
{% endif %}
<div>Answer: <strong>{{ ua.answer }}</strong></div>
{% if ua.created_date %}
<div class="small text-muted">Answered: {{ ua.created_date }}</div>
{% endif %}
</div>
<div>
{# Physics scoring may be numeric; show a simple badge if fully correct according to score field where present #}
{% if ua.score %}
{% if ua.score|stringformat:'s' == '5' %}
<span class="badge bg-success">Correct</span>
{% else %}
<span class="badge bg-secondary">Score: {{ ua.score }}</span>
{% endif %}
{% else %}
<span class="badge bg-light text-muted">Unmarked</span>
{% endif %}
</div>
</li>
{% empty %}
<li class="list-group-item">No responses recorded for this exam.</li>
{% endfor %}
</ul>
</div>
@@ -0,0 +1,52 @@
{# Aggregated response summary partial for physics questions (HTMX-loadable) #}
<div id="physics-response-summary-content">
{% if exam_response_total %}
<div class="small text-muted mb-2">Total responses: {{ exam_response_total }}</div>
<div class="row mb-2">
<div class="col-auto">Correct:</div>
<div class="col">
{% if exam_response_correct_count is not None %}
<strong>{{ exam_response_correct_count }}</strong>
{% if exam_response_correct_pct is not None %}
<span class="text-muted">({{ exam_response_correct_pct }}%)</span>
{% endif %}
{% else %}
<span class="text-muted">N/A</span>
{% endif %}
</div>
</div>
<div class="list-group mb-2">
{# Render top-level answer breakdown from exam_response_counts and pcts #}
{% for key, count in exam_response_counts.items %}
<div class="list-group-item">
<div class="d-flex w-100 justify-content-between align-items-center">
<div>{{ key }}</div>
<div class="text-end"><strong>{{ count }}</strong> <small class="text-muted">{{ exam_response_pcts|get_item:key|default:0 }}%</small></div>
</div>
<div class="progress mt-2" style="height:12px;">
<div class="progress-bar bg-primary" role="progressbar" style="width: {{ exam_response_pcts|get_item:key|default:0 }}%;" aria-valuenow="{{ exam_response_pcts|get_item:key|default:0 }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
{% endfor %}
</div>
<div>
<div class="d-flex justify-content-between align-items-center">
<h6 class="mb-1">Correct answer</h6>
<button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#correct-answer-{{ q_index }}" aria-expanded="false" aria-controls="correct-answer-{{ q_index }}">
Show
</button>
</div>
<div class="collapse mt-2" id="correct-answer-{{ q_index }}">
{% if correct_answer %}
<div class="small">{{ correct_answer }}</div>
{% else %}
<div class="small text-muted">No correct answer available.</div>
{% endif %}
</div>
</div>
{% else %}
<div class="small text-muted">No responses recorded for this question in the exam yet.</div>
{% endif %}
</div>
+10
View File
@@ -71,6 +71,16 @@ urlpatterns.extend(
views.UserAnswerDelete.as_view(),
name="user_answer_delete",
),
path(
"exam/<int:pk>/review/<int:q_index>/responses",
views.exam_review_question_responses,
name="exam_review_question_responses",
),
path(
"exam/<int:pk>/review/<int:q_index>/summary",
views.exam_review_question_summary,
name="exam_review_question_summary",
),
# TODO: consider merging with generic...
#path(
# "exam/<int:pk>/scores/<int:cid>/<str:passcode>/",
+131
View File
@@ -414,3 +414,134 @@ class UserAnswerDelete(SuperuserRequiredMixin, DeleteView):
model = UserAnswer
template_name = "user_answer_delete.html"
success_url = reverse_lazy("physics:user_answer_table_view")
@login_required
def exam_review_question_responses(request, pk: int, q_index: int):
"""Return the responses partial for a given exam question (HTMX-friendly)."""
exam = get_object_or_404(Exam, pk=pk)
questions = exam.get_questions()
try:
question = questions[q_index]
except Exception:
raise Http404("Question not found in exam")
context = {
"exam": exam,
"question": question,
"q_index": q_index,
"app_name": "physics",
}
# Prefilter user answers for this exam to avoid template-side filtering
try:
exam_user_answers = question.cid_user_answers.filter(exam=exam).select_related("user")
except Exception:
exam_user_answers = question.cid_user_answers.all()
# Default: anonymise unless reveal=1 is provided
reveal_flag = str(request.GET.get("reveal", "")).lower() in ("1", "true", "on")
context["reveal_respondents"] = reveal_flag
context["exam_user_answers"] = exam_user_answers
return render(request, "physics/partials/exam_review_question_responses_fragment.html", context)
@login_required
def exam_review_question_summary(request, pk: int, q_index: int):
"""Return the aggregated response summary partial for a given exam question (HTMX-friendly)."""
exam = get_object_or_404(Exam, pk=pk)
questions = exam.get_questions()
try:
question = questions[q_index]
except Exception:
raise Http404("Question not found in exam")
# Aggregate user answers for this question & exam
ua_qs = question.cid_user_answers.filter(exam=exam)
total_responses = ua_qs.count()
# Physics answers may be stored as tuples/lists or named fields; attempt to aggregate
counts = defaultdict(int)
other_count = 0
for ans in ua_qs.values_list("answer", flat=True):
if not ans:
other_count += 1
continue
# normalize iterable answers to a string key
if isinstance(ans, (list, tuple)):
key = ", ".join([str(x) for x in ans])
else:
key = str(ans)
counts[key] += 1
counts["unanswered"] = other_count
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
# Compute percent correct using per-answer scoring
correct_count = None
correct_pct = None
try:
# per-question max for physics is 5 (see generic.get_max_score mapping)
per_question_max = 5
if total_responses:
cnt = 0
for ua in ua_qs:
try:
score = ua.get_answer_score()
except Exception:
continue
if isinstance(score, (list, tuple)):
try:
ssum = sum([s for s in score if isinstance(s, (int, float))])
except Exception:
continue
if ssum == per_question_max:
cnt += 1
else:
if isinstance(score, (int, float)) and score == per_question_max:
cnt += 1
correct_count = cnt
correct_pct = round(100.0 * correct_count / total_responses, 1) if total_responses else 0.0
else:
correct_count = 0
correct_pct = 0.0
except Exception:
correct_count = None
correct_pct = None
# Provide a best-effort correct answer display
correct_answer = None
try:
correct_answer = question.get_answers()
if isinstance(correct_answer, (list, tuple)):
correct_answer = ", ".join([str(x) for x in correct_answer])
else:
correct_answer = str(correct_answer)
except Exception:
correct_answer = None
context = {
"exam": exam,
"question": question,
"q_index": q_index,
"app_name": "physics",
"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,
"exam_response_texts": {},
"correct_answer": correct_answer,
}
return render(request, "physics/partials/exam_review_question_summary_fragment.html", context)