Introduction

We'll build the Django Quiz Application in this article. In general, The Django Quiz App is an adaptable and dynamic online tool created to transform education and evaluation. It was developed to meet the demand for dynamic and interesting online tests and provides schools, companies, and individuals with an easy-to-use platform to design, administer, and administer tests on a range of topics. With the help of this software, traditional ways of learning and testing will be transformed into something more efficient, fun, and supportive of lifelong learning.

Setting Up the Django Project

To begin, ensure that you have Python and Django installed on your system. You can install Django using pip, the Python package manager. Once installed, create a new Django project by running the following command:

django-admin startproject quiz

Next, navigate to the project directory and create a new Django app -

cd quiz
python manage.py startapp home

Now add this app to the ‘settings.py’

File Structure

File Structure

Then, we register our app in the settings.py file in the installed_apps sections shown below.

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "home",
    "django_extensions",
]

Setting up necessary Files


models.py

The code defines Django models for a quiz application. It includes models for categories, questions, and answers, along with a common base model for shared fields like timestamps. These models are used to organize and store quiz-related data in a Django project.

from django.db import models
import uuid
import random
# Create your models here.

class BaseModel(models.Model):
    uid=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
    created_at=models.DateField(auto_now_add=True)
    updated_at= models.DateField(auto_now_add=True)

    class Meta:
        abstract=True

class Category(BaseModel):
    category_name=models.CharField(max_length=100)

    def __str__(self) -> str:
        return self.category_name

class Question(BaseModel):
    category=models.ForeignKey(Category, related_name='category',on_delete=models.CASCADE)
    question=models.CharField(max_length=100)
    marks=models.IntegerField(default=5)

    def __str__(self) -> str:
        return self.question
    
    def get_answers(self):
        answer_objs=list(Answer.objects.filter(question = self))
        random.shuffle(answer_objs)
        data=[]

        for answer_obj in answer_objs:
            data.append({
                'answer' : answer_obj.answer,
                'is_correct' : answer_obj.is_correct
            })

        return data

class Answer(BaseModel):
    question=models.ForeignKey(Question, related_name='question_answer',on_delete=models.CASCADE)
    answer=models.CharField(max_length=100)
    is_correct=models.BooleanField(default=False)
    
    def __str__(self) -> str:
        return self.answer

Run these commands to apply the migrations.

python3 manage.py makemigrations
python3 manage.py migrate

views.py

The code is a part of a Django web application for quizzes.

admin.py

Here we are registering the models.

from django.contrib import admin
from .models import *

# Register your models here.
admin.site.register(Category)

class AnswerAdmin(admin.StackedInline):
    model=Answer

class QuestionAdmin(admin.ModelAdmin):
    inlines=[AnswerAdmin]
admin.site.register(Question,QuestionAdmin)
admin.site.register(Answer)

Creating GUI


home.html

This HTML template is designed for a Django quiz app, providing a category selection form for users and using Bootstrap for styling and layout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="col-md-6 mx-auto">
            <form method="get">
                <div class="form-group">
                    <label>Select Category</label>
                    <select name="category" class="form-control">
                        <option value="choose">Choose</option>
                        {% for category in categories %}
                        <option value="{{category.category_name}}">{{category.category_name}}</option>
                        {% endfor %}
                        img
                    </select>
                </div>
                <button class="btn btn-danger mt-3">Submit</button>
            </form>
        </div>
    </div>
</body>
</html>

quiz.html

This code integrates Vue.js into an HTML page to create a dynamic quiz interface where users can select answers, check correctness, and receive alerts. It fetches questions from a Django API based on the selected category.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>new</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

</head>

<body>
    <div id="app">
        <div class="container mt-5 pt-5">
            <div class="col-md-6 mx-auto">
                <h3>Give Quiz</h3>
                <div v-for="question in questions">
                    <hr>
                    <p>[[question.question]]</p>
                    <div class="form-check" v-for="answer in question.answers">
                        <input @change="checkAnswer($event, question.uid)" :value="answer.answer"
                            class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
                        <label class="form-check-label" for="flexRadioDefault1">
                            [[answer.answer]]
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

    <script>
        var app = new Vue({
            el: '#app',
            delimiters: ['[[', ']]'],
            data() {
                return {
                    category: "{{category}}",
                    questions: [],
                }
            },
            methods: {
                getQuestions() {
                    var _this = this
                    fetch(`/api/get-quiz?category=${_this.category}`)
                        .then(response => response.json())
                        .then(result => {
                            console.log(result)
                            _this.questions = result.data
                        })
                },
                checkAnswer(event, uid) {
                    this.questions.map(question => {
                        console.log(question.answers)
                        answers = question.answers
                        for (var i = 0; i < answers.length; i++) {
                            if (answers[i].answer == event.target.value) {
                                if (answers[i].is_correct) {
                                    console.log("Your answer is correct")
                                    alert("Hurry your answer is correct")
                                } else {
                                    console.log("your answer is wrong")
                                    alert("Sorry your answer is wrong")
                                }
                            }
                        }

                    })
                    console.log(event.target.value, uid)
                }
            },
            created() {
                this.getQuestions()
            },
        });

    </script>
</body>

</html>

quiz/urls.py

This is the urls.py file of our project quiz in this file we just map the other urls.py file of our home app for performing some operations.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('', include('home.urls')),
    path('admin/', admin.site.urls),
]

home/urls.py

This is the urls.py file this is our app home urls.py.

from django.urls import path
from .import views
urlpatterns = [
    path('',views.home, name="home"),
    path('api/get-quiz',views.get_quiz, name="get_quiz"),
    path('quiz/',views.quiz, name="quiz")    
]

Deployment of the Project

Run the server with the help of the following command.

python3 manage.py runserver

Output

Submit

Select category

Give Quiz

If the selected answer is correct or incorrect alert like this will pop up.

Correct

Wrong

Conclusion

The Quiz Django app represents a sophisticated fusion of cutting-edge technologies aimed at providing users with an intuitive and stimulating quiz-taking experience. The Quiz Django application is a web-based platform crafted to facilitate the creation and management of quizzes. It merges Django, an influential Python web framework, with Vue.js, a JavaScript framework renowned for its capacity to construct dynamic user interfaces. The application enables users to.

To sum up, the Quiz Django application combines the robust capabilities of Django for backend development with the interactive features of Vue.js for frontend user engagement, resulting in an immersive and educational quiz-taking platform.