Quiz Application using Django
Last Updated : 30 Apr, 2025
In this article, we will create the Django Quiz Application generally the Django Quiz App is a versatile and interactive web application designed to revolutionize learning and assessment. Created to address the need for engaging and adaptable online quizzes, it offers educators, businesses, and individuals a user-friendly platform to create, manage, and take quizzes on various subjects. This app is set to transform traditional learning and testing methods, making the process more enjoyable, efficient, and conducive to continuous learning.
Quiz Application using Django
To install Django follow these steps.
Starting the Project Folder
To start the project use this command
django-admin startproject quiz
cd quiz
To start the app use this command
python manage.py startapp home
Now add this app to the 'settings.py'
File Structure
File Structurethen we register our app in settings.py file in the installed_apps sections like 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.
Python from django.db import models import uuid import random class BaseModel(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable = True) created_at = models.DateField(auto_now_add = True) updated_at = models.DateField(auto_now = True) class Meta: abstract = True class Types(BaseModel): gfg_name = models.CharField(max_length=100) def __str__(self) -> str: return self.gfg_name class Question(BaseModel): gfg = models.ForeignKey(Types, related_name='gfg',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)) data = [] random.shuffle(answer_objs) 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
views.py
The code is a part of a Django web application for quizzes:
home
Function: Displays a list of quiz categories. Redirects to the quiz page for a selected category.quiz
Function: Displays a quiz page for a specific category.get_quiz
Function: Retrieves random quiz questions, optionally filtered by category. Returns them as JSON. Handles exceptions with a "Something went wrong" response.
Python from django.shortcuts import render, redirect from django.http import JsonResponse from .models import * import random def home(request): context = {'catgories': Types.objects.all()} if request.GET.get('gfg'): return redirect(f"/quiz/?gfg={request.GET.get('gfg')}") return render(request, 'home.html', context) def quiz(request): context = {'gfg': request.GET.get('gfg')} return render(request, 'quiz.html', context) def get_quiz(request): try: question_objs = Question.objects.all() if request.GET.get('gfg'): question_objs = question_objs.filter(gfg__gfg_name__icontains = request.GET.get('gfg')) question_objs = list(question_objs) data = [] random.shuffle(question_objs) for question_obj in question_objs: data.append({ "uid" : question_obj.uid, "gfg": question_obj.gfg.gfg_name, "question": question_obj.question, "marks": question_obj.marks, "answer" : question_obj.get_answers(), }) payload = {'status': True, 'data': data} return JsonResponse(payload) # Return JsonResponse except Exception as e: print(e) return HttpResponse("Something went wrong")
admin.py
Here we are registering the models.
Python from django.contrib import admin from .models import * # Register your models here. class AnswerAdmin(admin.StackedInline): model = Answer class QuestionAdmin(admin.ModelAdmin): inlines = [AnswerAdmin] admin.site.register(Types) 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.
HTML <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>Django Quiz App</title> </head> <body> <div class="container mt-5 pt-5"> <!-- Added the Geeksforgeeks heading here --> <h1 style="color: green; text-align: center;">Geeksforgeeks</h1> <div class="col-md-6 mx-auto"> <form action=""> <div class="form-group"> <label for="">Select Types</label> <select name="gfg" id="" class="form-control" value="gfg"> <option value="Choose">Choose</option> {% for type in catgories %} <option value="{{type.gfg_name}}">{{type.gfg_name}}</option> {% endfor %} </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.
HTML <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>Django Quiz App</title> </head> <body> <script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script> <div id="app"> <ul> <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.answer"> <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> <!-- <li v-for="task in tasks">[[task]]</li> --> </ul> </div> <script> const app = Vue.createApp({ el: '#app', delimiters: ['[[', ']]'], data() { return { gfg: '{{gfg}}', questions :[] } }, methods : { getQuestions(){ var _this = this fetch(`/api/get-quiz/?gfg=${this.gfg}`) .then(response => response.json()) .then(result =>{ console.log(result) _this.questions = result.data }) }, checkAnswer(event, uid){ this.questions.map(question =>{ answer = question.answer for(var i=0; i<answer.length; i++){ if(answer[i].answer==event.target.value){ if(answer[i].is_correct){ console.log('Your answer is correct!') alert("Hurray ypur answer is correct !????") }else{ console.log('Your answer is wrong!') alert("Better luck next time !????") } } } }) console.log(event.target.value , uid) } }, created() { this.getQuestions( ) }, }); app.mount('#app') </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 the some operations
Python 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
Python from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('', views.home , name = 'home'), path('quiz/', views.quiz, name= 'quiz'), path('api/get-quiz/', views.get_quiz, name='get_quiz') ]
Deployement of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Run the server with the help of following command:
python3 manage.py runserver
Output


Creating a quiz application in Django can be a fun learning experience. To build more complex applications with enhanced features, the Complete Django Web Development Course will equip you with the necessary skills
Conclusion
In conclusion, the Quiz Django app is a web application designed for creating and administering quizzes. It combines Django, a powerful Python web framework, with Vue.js, a JavaScript framework for building dynamic user interfaces. The app allows users to:
- Select a Category: Users can choose a quiz category from a dropdown menu.
- Answer Questions: The app presents users with a list of questions within the selected category. Users can select answers to these questions.
- Check Correctness: Upon selecting an answer, the app checks if it's correct and provides immediate feedback through alerts.
- Dynamic UI: Vue.js is used to create a dynamic user interface that updates in real-time as users interact with the quiz.
- API Integration: The app fetches quiz questions from a Django API based on the selected category.
Overall, the Quiz Django app combines the power of Django for backend development and Vue.js for frontend interactivity to create an engaging and educational quiz-taking experience.
Similar Reads
Realtime chat app using Django
Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line
11 min read
Create a Quiz Application Using JavaScript
In this article, we will learn how to create a quiz application using JavaScript. The quiz application will contain questions followed by a total score shown at the end of the quiz. The score will increase based on the correct answers given. Initially, there are only three questions, but you can inc
4 min read
User Authentication System using Django
In this article, we will explore the process of creating a secure and efficient user authentication system in Django, a high-level Python web framework. Building upon Django's built-in capabilities, we will cover user registration, login, and more, providing you with the knowledge and tools necessar
10 min read
Build Calculator App Using Django
In this article, we will guide you through the process of creating a calculator app using Django. Our goal is to develop a versatile application capable of performing fundamental mathematical operations such as addition, subtraction, multiplication, and more. By the end of this tutorial, you will ha
3 min read
Flask NEWS Application Using Newsapi
In this article, we will create a News Web Application using Flask and NewsAPI. The web page will display top headlines and a search bar where the user can enter a query, after processing the query, the webpage will display all relevant articles (up to a max of 100 headlines). We will create a simpl
7 min read
Online Auction System Using Django
In this article, I am Going to Build an Online auction system Using Django. Physical auctions are limited by location but online auctions are accessible globally. It opens a broader range of buyers. It Can Connect the Seller, Buyer, and admin. Tools & Technologies Used in this Project : Python D
9 min read
Joke Application Project Using Django Framework
Django is a high-level Python-based Web Framework that allows rapid development and clean, pragmatic design. Â It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. Today we will create
2 min read
Tip Calculator Project Using Django
In this article, we will guide you through the process of creating a Tip Calculator Project using Django. This interactive project requires users to input the bill amount, the desired percentage for the tip, and the number of people splitting the bill. The application will then compute and display t
6 min read
Python - Quiz Application Project
Python provides us with many libraries to create GUI(Graphical User Interface), and Tkinter is one of them. Creating GUI with Tkinter is very easy and it is the most commonly used library for GUI development. In this article, we will create a Quiz application using Tkinter. A Quiz application has a
4 min read
Note-taking App using Django
In this article, we will explore a note-making app. In this article, we will create a note-making app using Django. We will also use the Django authentication system. Users need to create an account on the web to access the note-making app. After that, users will have access to the note-making app.
8 min read