Django Quiz - Results
urlpatterns = [
    ...
    path("api/quizzes/<uuid:uuid>/submit/", QuizSubmitView.as_view()),
]

 

from collections import defaultdict
from django.shortcuts import render
from django.views import View
import json


class QuizSubmitView(View):

    def post(self, request, uuid):
 
        quiz = get_object_or_404(Quiz, uuid=uuid)

        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return render(request, "polls/error.html", { "erro": "JSON inválido" })

        
        scores = defaultdict(int)

        answer_ids = list(data.values())

        ads = AnswerDimension.objects.filter(
            answer_id__in=answer_ids,
            dimension__quiz=quiz
        )

        for ad in ads:
            scores[ad.dimension_id] += ad.weight


        profiles = Profile.objects.filter(quiz=quiz)\
            .order_by("-priority")\
            .prefetch_related("profilerule_set")


        chosen_profile = None

        for profile in profiles:
            valid = True

            for rule in profile.profilerule_set.all():
                value = scores.get(rule.dimension_id, 0)

                if rule.min_value is not None and value < rule.min_value:
                    valid = False
                    break

                if rule.max_value is not None and value > rule.max_value:
                    valid = False
                    break

            if valid:
                chosen_profile = profile
                break


        if chosen_profile is None:
            return render(request, "polls/error.html", { "error": "None of the profiles correspond to the result"})

       
        return render(request, "polls/result.html", { "profile": chosen_profile})

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quiz Result</title>
</head>
<body style="text-align: center; padding-top: 100px;">

  <h2>Quiz Result</h2>

  <p><strong>Profile:</strong></p>
  <p>{{ profile }}</p>

</body>
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quiz Error</title>
</head>
<body style="text-align: center; padding-top: 100px;">

  <h2>Something went wrong</h2>

  <p>
    We were unable to calculate your quiz result.
  </p>

  <p>
    Please try again or contact the administrator if the problem persists.
  </p>

</body>
</html>