Django Quiz - SurveyJS

For the frontend, we’ll use SurveyJS.

SurveyJS is a JavaScript library that gives us a clean, user-friendly interface for rendering quizzes and surveys.

It works with JSON, which fits our Django backend nicely. The backend will send the quiz structure as JSON, SurveyJS will render it in the browser, and when the user completes the quiz, we’ll send the selected answers back to Django for processing.


The flow will be:

Django backend → quiz JSON → SurveyJS frontend → user answers → Django backend → result

Let’s also define the endpoint that will receive the submitted answers:

/api/quizzes/${quizUUID}/submit/

Later, we’ll replicate this path in Django’s urls.py.

 

 

{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>

    <meta charset="utf-8">
    <link rel="icon" href="{% static 'images/logo.png' %}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="https://unpkg.com/survey-core@2.5.8/survey.core.min.js"></script>
    <script src="https://unpkg.com/survey-js-ui@2.5.8/survey-js-ui.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/survey-core@2.5.8/survey-core.min.css">


</head>

    <body>

        <div id="surveyElement"></div>

        {{ survey_json|json_script:"survey-data" }}

        <script>

            const CSRF_TOKEN = "{{ csrf_token }}";
            const quizUUID = "{{ quiz.uuid }}";

            const surveyJson = JSON.parse( document.getElementById("survey-data").textContent );

            const survey = new Survey.Model(surveyJson);

            survey.onComplete.add(sender => {
                fetch(`/api/quizzes/${quizUUID}/submit/`, {
                    method: "POST",
                    headers: { "Content-Type": "application/json", "X-CSRFToken": CSRF_TOKEN },
                    body: JSON.stringify(sender.data)
                })
                .then(res => res.text())
                .then(html => {
                    document.documentElement.innerHTML = html;
                });
            });


            survey.render(document.getElementById("surveyElement"));

        </script>


    </body>
</html>