Django Quiz - Quiz View

Time to create a view that will transform this quiz into json that can be handled by SurveJS.

 

from django.views.generic import TemplateView
from django.shortcuts import get_object_or_404
from .models import *

class QuizPageView(TemplateView):
    template_name = "polls/quiz.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        quiz = get_object_or_404(
            Quiz.objects.prefetch_related("question_set__answer_set"),
            uuid=kwargs.get("uuid")
        )

        context["quiz"] = quiz


        context["survey_json"] = {
            "title": quiz.name,
            "showProgressBar": "bottom",
            "pages": [
                {
                    "elements": [
                        {
                            "type": "radiogroup",
                            "name": f"q_{question.id}",
                            "title": question.text,
                            "isRequired": True,
                            "choices": [
                                {
                                    "value": answer.id,
                                    "text": answer.text
                                }
                                for answer in question.answer_set.all()
                            ]
                        }
                    ]
                }
                for question in quiz.question_set.all()
            ]
        }

        return context

 


from django.urls import path
from .views import *

urlpatterns = [
    
    ...
    path("q/<uuid:uuid>/", QuizPageView.as_view(), name="quiz-page"),
    



]