Refactor exam management: update exam edit form and add exam links partial

This commit is contained in:
Ross
2026-02-16 11:47:49 +00:00
parent b19eefa60d
commit f2eaf6197e
5 changed files with 72 additions and 98 deletions
+34 -6
View File
@@ -30,6 +30,7 @@ from dal import autocomplete
from django.conf import settings
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from .forms import (
@@ -1653,11 +1654,37 @@ def question_add_exam(request, question_id: int):
else:
question.exams.add(exam)
# return updated fragment
form = AddExamForm(user=request.user)
return render(request, "anatomy/partials/exam_edit_fragment.html", {"form": form, "question": question})
# return out-of-band swap: update exam links and remove the editor
links_html = render_to_string("anatomy/partials/exam_links.html", {"question": question}, request=request)
oob_remove = '<div id="exam-list" hx-swap-oob="outerHTML"></div>'
return HttpResponse(mark_safe(links_html + oob_remove))
# else try to process from the search form
# else try to process from the search form or widget-provided values
# The ExamSearchWidget may submit a list; accept first value if present.
exam_vals = request.POST.getlist('exam') if hasattr(request.POST, 'getlist') else []
if not exam_vals:
# also accept single 'exam' param
single = request.POST.get('exam')
if single:
exam_vals = [single]
if exam_vals:
try:
exam = get_object_or_404(Exam, pk=int(exam_vals[0]))
except (ValueError, TypeError):
exam = None
if exam:
if request.POST.get("remove", False) == "true":
question.exams.remove(exam)
else:
question.exams.add(exam)
links_html = render_to_string("anatomy/partials/exam_links.html", {"question": question}, request=request)
oob_remove = '<div id="exam-list" hx-swap-oob="outerHTML"></div>'
return HttpResponse(mark_safe(links_html + oob_remove))
# else try to process via bound form (fallback)
form = AddExamForm(request.POST, user=request.user)
if form.is_valid():
exam = form.cleaned_data.get("exam")
@@ -1666,8 +1693,9 @@ def question_add_exam(request, question_id: int):
else:
question.exams.add(exam)
form = AddExamForm(user=request.user)
return render(request, "anatomy/partials/exam_edit_fragment.html", {"form": form, "question": question})
links_html = render_to_string("anatomy/partials/exam_links.html", {"question": question}, request=request)
oob_remove = '<div id="exam-list" hx-swap-oob="outerHTML"></div>'
return HttpResponse(mark_safe(links_html + oob_remove))
else:
# render form with errors
return render(request, "anatomy/partials/exam_edit_fragment.html", {"form": form, "question": question})