Django Interview Questions
Master your Django interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.
I. Beginner Level
1. What is Django and why is it used?
Django is a high-level Python web framework that helps developers create secure, scalable, and maintainable web applications quickly. Django is based on the MVT (Model-View-Template) pattern and supports rapid development with clean and reusable code.
Django is used for developing web applications such as blogs, e-commerce sites, content management systems, and REST APIs. Django comes with many built-in features such as authentication, ORM (Object-Relational Mapping), admin interface, URL routing, and robust security measures against common attacks such as SQL injection and CSRF.
2. What are the key features or advantages of using Django?
Django provides many powerful features that make web development faster, secure, and scalable.
Rapid Development: Built-in components like ORM, admin panel, and authentication reduce development time.
Security: Protects against common threats such as SQL injection, CSRF, XSS, and clickjacking.
Scalability: Suitable for both small and large-scale applications.
Built-in Admin Panel: Automatically generated admin interface for managing database records.
ORM Support: Simplifies database operations using Python code instead of raw SQL.
Reusable Components: Encourages modular and reusable app structure.
3. How does Django differ from Flask? (Compare their scopes and use cases.)
Django and Flask are both popular Python web frameworks, but they differ in scope, flexibility, and use cases.
Django: It is a full-stack framework that has in-built functionalities such as ORM, authentication, admin panel, and security. It has a proper MVT structure and is most suitable for complex applications that need rapid development.
Flask: It is a micro-framework that has basic routing and request functionality. It has flexibility but lacks libraries for functionalities such as ORM and authentication. It is most suitable for small applications or APIs.
In short, Django is preferred for large-scale, feature-rich applications, while Flask is better for minimalistic, flexible, or microservice-based projects.
4. What is the difference between Python and Django?
Python is a high-level, general-purpose programming language that can be used for different purposes like web development, data science, automation, machine learning, and scripting.
Django, on the other hand, is a web framework that is written in Python. It is used for developing web applications quickly and efficiently with the help of in-built tools like ORM, authentication, routing, templates, and security.
In short, Python is a programming language, and Django is a framework that is built using Python.
5. Is Django used for frontend, backend, or both?
Django is primarily a backend framework. It handles server-side logic such as database operations, authentication, business logic, API development, and request/response handling.
However, Django also supports frontend rendering through its template engine, which allows developers to generate dynamic HTML pages. For modern applications, Django is often used as a backend API with frontend frameworks like React, Angular, or Vue.
So, Django is mainly used for backend development but can also render frontend templates when needed.
6. What architectural pattern does Django follow (Model-Template-View, i.e. MTV)? How is this different from the traditional MVC pattern?
Django follows the Model-Template-View (MTV) architectural pattern. This pattern separates the application into three main components to promote clean structure and maintainability.
Model: Handles the database structure and business logic using Django's ORM.
Template: Responsible for presentation and UI (HTML files).
View: Contains the business logic and handles requests and responses.
In the traditional MVC architecture, the Controller is responsible for handling user input and interacting with the Model and View. In the MTV architecture of Django, the View is responsible for the job of the Controller, and the URL routing of Django is responsible for routing the request. Therefore, MTV is basically Django's version of MVC with a different naming convention.
7. Explain the basic Django project directory structure (e.g., manage.py, settings.py, urls.py, wsgi.py, etc.).
When you create a Django project using the startproject command, Django generates a default directory structure that organizes configuration and application files.
manage.py: A command-line utility used to interact with the project (runserver, migrate, createsuperuser, etc.).
settings.py: Contains project configuration such as database settings, installed apps, middleware, templates, and static files.
urls.py: Defines URL routing and maps URLs to views.
wsgi.py: Entry point for WSGI-compatible web servers in production environments.
asgi.py: Entry point for ASGI-compatible servers, used for asynchronous features.
This structured layout helps keep configuration, routing, and application logic organized and scalable.
8. What is the difference between a Django project and a Django app?
A Django project is the overall configuration and container for an entire web application, while a Django app is a modular component within the project that handles a specific functionality.
The project contains global settings, URL configurations, middleware, and database configurations. It can include multiple apps. An app, on the other hand, focuses on a single feature or module such as authentication, blog, payments, or user management, and contains its own models, views, templates, and URLs.
In short, a project is the whole website, and apps are the building blocks of the website.
9. What are Django URLs, and how do they map to views?
URLs in Django are used to define the routing system that links web requests (URLs) to particular view functions or class views. This is done in the urls.py file.
When a user enters a URL in the browser, Django checks the URL patterns defined in urls.py, matches the path, and calls the corresponding view function. The view processes the request, interacts with models if needed, and returns an HTTP response.
Example:
1# urls.py
2from django.urls import path
3from . import views
4
5urlpatterns = [
6 path('home/', views.home, name='home'),
7]
8
9# views.py
10from django.http import HttpResponse
11
12def home(request):
13 return HttpResponse("Welcome to Django")
1410. What are Django views?
Django views are Python functions or class-based methods that process HTTP requests and return HTTP responses. They hold the business logic of an application and serve as an interface between models and templates in the MTV pattern.
There are two types of views in Django: Function-Based Views (FBVs) and Class-Based Views (CBVs). Function-based views are simple and easy to understand, while class-based views are reusable and well-structured.
Example (Function-Based View):
1from django.http import HttpResponse
2
3
4def hello(request):
5 return HttpResponse("Hello, Django!")
611. What are Django models?
Django models are Python classes that represent the structure of database tables. Every model corresponds to a database table, and every attribute of the model corresponds to a column in the database table.
Django provides an Object Relational Mapping (ORM) system, which enables developers to work with the database using Python code without having to write SQL queries. Models assist in the creation, retrieval, updating, and deletion of records.
Example:
1from django.db import models
2
3class Student(models.Model):
4 name = models.CharField(max_length=100)
5 age = models.IntegerField()
6
7 def __str__(self):
8 return self.name
912. What is Django ORM?
Django ORM (Object-Relational Mapping) is a feature that allows developers to interact with the database using Python objects instead of writing raw SQL queries. It converts Python code into SQL queries automatically and maps database tables to Django models.
With Django ORM, you can create, retrieve, update, and delete database records using model methods. It supports complex queries, relationships (ForeignKey, ManyToManyField), and database migrations while maintaining database independence.
Example:
1# Creating a record
2student = Student.objects.create(name="Vishal", age=25)
3
4# Retrieving records
5students = Student.objects.filter(age__gt=20)
6
7# Updating a record
8student.age = 26
9student.save()
10
11# Deleting a record
12student.delete()
1313. What are static files in Django and how are they managed?
Static files in Django refer to files like CSS, JavaScript, images, and fonts that are not dynamically created. These files are used for styling and improving the frontend of a web application.
Django handles static files through the staticfiles app. Developers organize static files in a static directory in each app or in a project-wide static directory. The settings file contains settings such as STATIC_URL and STATICFILES_DIRS to specify where the static files are located.
In production, the collectstatic command is employed to collect all static files in one directory specified by STATIC_ROOT, which can then be served by a web server such as Nginx.
Example (Template usage):
1{% load static %}
2<link rel="stylesheet" href="{% static 'css/style.css' %}">
314. What are templates in Django?
Templates in Django are HTML files that define the presentation layer of a web application. They are used to display dynamic data passed from views and allow separation of business logic from UI design.
Django uses its own template engine that supports template tags, filters, and inheritance. Views pass context data to templates, and the template renders the final HTML response sent to the browser.
Example:
1<h1>Welcome, {{ name }}!</h1>
2{% if user.is_authenticated %}
3 <p>You are logged in.</p>
4{% endif %}
515. What is Jinja templating?
Jinja is a modern and powerful templating engine for Python, mainly used with frameworks like Flask and sometimes with Django. It allows developers to generate dynamic HTML pages by embedding Python-like expressions inside HTML files.
Jinja supports functionalities such as template inheritance, filters, control structures (if, for), macros, and auto-escaping. Its syntax is similar to that of Django's template language, with double curly braces for variables and {% %} for logic.
Example:
1<h1>Hello, {{ user.name }}!</h1>
2{% for item in items %}
3 <p>{{ item }}</p>
4{% endfor %}
516. What is the Django admin interface?
The Django admin interface is a built-in, automatically generated web interface that allows developers and administrators to manage database records easily. It provides a ready-to-use dashboard for performing CRUD (Create, Read, Update, Delete) operations on models.
It is highly customizable and supports features like authentication, search, filtering, sorting, and inline editing. To use it, models must be registered in the admin file, and a superuser account must be created.
Example (Registering a model):
1from django.contrib import admin
2from .models import Student
3
4admin.site.register(Student)
517. Explain Django Architecture?
Django follows the Model-Template-View (MTV) architectural pattern, which separates application logic, user interface, and data management to maintain clean and scalable code.
Model: Represents the database structure. It defines data fields and handles database operations using Django ORM.
Template: Handles the presentation layer (HTML files). It displays dynamic data passed from views.
View: Contains business logic. It processes user requests, interacts with models, and returns responses.
When a user sends a request, Django routes it through urls.py to the appropriate view. The view interacts with the model to retrieve or modify data, then passes the data to a template, which renders the final HTML response returned to the user.
18. What are sessions in Django and how are they used?
Sessions in Django are used to hold user data on the server. This is necessary because HTTP is stateless. Sessions are used to store data such as user login status, preferences, or shopping cart information.
Django stores session data on the server (by default in the database) and sends a session ID to the client through cookies. The session ID is used to retrieve the stored data for subsequent requests.
Example:
1# Setting session data
2request.session['username'] = 'Vishal'
3
4# Getting session data
5username = request.session.get('username')
6
7# Deleting session data
8del request.session['username']
919. What are cookies in Django?
Cookies in Django are small pieces of data stored on the client's browser to remember information between requests. They are commonly used to store user preferences, session IDs, or tracking information.
Unlike sessions (which store data on the server), cookies store data on the client side. Django allows setting, retrieving, and deleting cookies through the HTTP response object.
Example:
1# Setting a cookie
2response.set_cookie('username', 'Vishal')
3
4# Getting a cookie
5username = request.COOKIES.get('username')
6
7# Deleting a cookie
8response.delete_cookie('username')
920. What are QuerySets in Django?
QuerySets in Django are collections of database queries used to retrieve data from the database using the Django ORM. They represent a lazy database lookup, meaning the query is not executed until the data is actually needed.
QuerySets allow filtering, ordering, slicing, and chaining multiple queries together. They return model instances that match the given conditions.
Example:
1# Retrieve all records
2students = Student.objects.all()
3
4# Filter records
5students = Student.objects.filter(age__gt=20)
6
7# Order records
8students = Student.objects.order_by('name')
9
10# Get a single record
11student = Student.objects.get(id=1)
1221. How do you create a new Django project and run the development server?
To create a new Django project, you first install Django using pip and then use the django-admin startproject command followed by the project name. This generates the initial project directory structure.
Once the project is created, navigate into the project directory and run the development server using the manage.py runserver command. By default, the server starts on port 8000 and can be accessed at http://127.0.0.1:8000/.
Example:
1pip install django
2django-admin startproject myproject
3cd myproject
4python manage.py runserver
522. What are Django forms and why are they used?
Django forms are Python classes that handle HTML form rendering, data validation, and processing. They simplify the process of collecting user input and ensuring it meets required constraints before saving to the database.
Django provides two main types of forms: the base Form class for custom forms and ModelForm for automatically generating forms from model definitions. Forms handle CSRF protection, field validation, and error rendering out of the box.
Example:
1from django import forms
2
3class ContactForm(forms.Form):
4 name = forms.CharField(max_length=100)
5 email = forms.EmailField()
6 message = forms.CharField(widget=forms.Textarea)
723. Explain the request-response cycle in Django.
The request-response cycle in Django describes the complete journey of an HTTP request from the browser to the server and back. Understanding this cycle is fundamental to working with Django effectively.
The browser sends an HTTP request to the Django server.
Django's middleware processes the request first (e.g., authentication, session handling).
The URL dispatcher (urls.py) matches the request URL to a view.
The view processes the request, interacts with models if needed, and prepares context data.
The view renders a template with the context and returns an HTTP response.
Middleware processes the response before it is sent back to the browser.
24. What is the purpose of urlpatterns in Django's urls.py?
The urlpatterns list in Django's urls.py file is a list of URL route definitions that maps incoming URL paths to their corresponding view functions or class-based views. It acts as the routing table for the Django application.
Each entry in urlpatterns is typically created using the path() or re_path() function. The path() function accepts a URL string, a view, and an optional name for reverse URL resolution. The include() function is used to include URL configurations from individual apps.
Example:
1from django.urls import path, include
2
3urlpatterns = [
4 path('blog/', include('blog.urls')),
5 path('about/', views.about, name='about'),
6]
725. What is a superuser in Django and how do you create one?
A superuser in Django is a special user account that has all permissions in the system, including access to the Django admin interface. A superuser can create, edit, and delete any data across all models and manage other users.
You create a superuser using the createsuperuser management command. Django will prompt you to enter a username, email address, and password. Once created, the superuser can log into the admin panel at /admin/.
Example:
1python manage.py createsuperuser
2# Follow the prompts to set username, email, and password
326. What is manage.py in Django and what are its common commands?
manage.py is a command-line utility automatically created when you start a new Django project. It serves as a wrapper around Django's django-admin tool and is used to interact with your Django project for various administrative tasks.
runserver: Starts the development web server.
makemigrations: Creates migration files based on model changes.
migrate: Applies migrations to the database.
createsuperuser: Creates an admin superuser account.
shell: Opens an interactive Python shell with the Django environment loaded.
test: Runs the test suite for the project.
27. What is the INSTALLED_APPS setting in Django?
INSTALLED_APPS is a list in Django's settings.py that tells Django which applications are active for the project. Each entry is a string representing the Python path to an application configuration class or the application package name.
Django uses INSTALLED_APPS to know which apps to include when running database migrations, discovering template directories, loading static files, and registering models with the admin. Both Django's built-in apps (like django.contrib.admin and django.contrib.auth) and your custom apps must be listed here.
Example:
1INSTALLED_APPS = [
2 'django.contrib.admin',
3 'django.contrib.auth',
4 'django.contrib.contenttypes',
5 'django.contrib.sessions',
6 'myapp', # Your custom app
7]
8II. Intermediate Level
1. What is the difference between get() and filter() in Django ORM?
In Django ORM, get() and filter() are used to retrieve records from the database, but they behave differently.
get(): Returns a single object that matches the query. It raises DoesNotExist if no record is found and MultipleObjectsReturned if more than one record matches.
filter(): Returns a QuerySet containing all matching records. It does not raise an exception if no records are found; instead, it returns an empty QuerySet.
Example:
1# Using get()
2student = Student.objects.get(id=1)
3
4# Using filter()
5students = Student.objects.filter(age__gt=20)
62. What is the difference between CharField and TextField in Django?
In Django models, CharField and TextField are used to store text data, but they differ mainly in length and usage.
CharField: Used for shorter strings such as names or titles. It requires a max_length parameter to define the maximum allowed characters.
TextField: Used for large amounts of text such as descriptions or content. It does not require a max_length parameter.
Example:
1class Article(models.Model):
2 title = models.CharField(max_length=200)
3 content = models.TextField()
43. What is the difference between null=True and blank=True on Django model fields?
In Django models, null=True and blank=True are used to control whether a field is optional, but they apply to different layers.
null=True: Specifies that the database can store NULL values for this field. It affects the database level.
blank=True: Specifies that the field is allowed to be empty in forms and admin validation. It affects the application level.
For text-based fields like CharField or TextField, it is common to use blank=True instead of null=True, since empty strings are usually preferred over NULL values.
4. What do the commands python manage.py makemigrations and python manage.py migrate do in Django?
In Django, python manage.py makemigrations and python manage.py migrate are used to apply database changes based on model modifications.
makemigrations: Creates new migration files based on changes detected in models. It prepares the changes but does not apply them to the database.
migrate: Applies the generated migration files to the database, creating or altering tables accordingly.
In simple terms, makemigrations prepares the changes, and migrate executes them in the database.
5. Why is setting up a virtual environment important for a Django project?
Creating a virtual environment in a Django project is important because it creates an isolated Python environment for that particular project. This ensures that the dependencies of the project do not conflict with other projects or the Python packages installed in the system.
It helps you to install a particular version of Django and other packages that the project requires, without interfering with other applications. Virtual environments also help with the deployment of projects because they ensure that there is a clean list of dependencies in files such as requirements.txt.
6. What is middleware in Django, and what is it used for?
Middleware in Django is a framework of hooks into Django's request/response processing. It is a layer that processes requests before they reach the view and responses before they are sent back to the client.
Middleware is used for tasks such as authentication, session management, security checks (CSRF protection), logging, caching, and modifying request or response objects globally across the application.
Middleware classes are defined in the MIDDLEWARE setting in settings.py and are executed in the order they are listed for requests and in reverse order for responses.
7. What are context processors in Django and how are they used?
Context processors in Django are functions that add extra variables to the template context automatically. They allow certain data to be available in all templates without explicitly passing it from every view.
Example:
1# context_processors.py
2
3def site_name(request):
4 return {'site_name': 'My Website'}
5
6# settings.py
7TEMPLATES = [
8 {
9 'OPTIONS': {
10 'context_processors': [
11 'myapp.context_processors.site_name',
12 ],
13 },
14 },
15]
168. What are signals in Django and how are they used?
Signals in Django are a mechanism that allows certain senders to notify a group of receivers about certain actions that have occurred. Signals are useful in decoupling applications because they enable certain code to run automatically when certain actions occur, such as saving or deleting a model instance.
Example:
1from django.db.models.signals import post_save
2from django.dispatch import receiver
3from .models import Student
4
5@receiver(post_save, sender=Student)
6def student_created(sender, instance, created, **kwargs):
7 if created:
8 print("New student created:", instance.name)
99. What is the difference between function-based views and class-based views in Django?
In Django, both Function-Based Views (FBVs) and Class-Based Views (CBVs) are used to handle HTTP requests, but they differ in structure and reusability.
Function-Based Views (FBVs): Defined as simple Python functions that take a request object and return a response. They are easy to understand and suitable for simple logic.
Class-Based Views (CBVs): Defined as Python classes that provide methods like get() and post(). They support inheritance and mixins, making them more reusable and organized for complex applications.
10. How do you configure Django to connect to a database (e.g., PostgreSQL, MySQL)?
To connect Django to a database like PostgreSQL or MySQL, you need to configure the DATABASES setting in the settings.py file.
Example (PostgreSQL):
1DATABASES = {
2 'default': {
3 'ENGINE': 'django.db.backends.postgresql',
4 'NAME': 'mydatabase',
5 'USER': 'myuser',
6 'PASSWORD': 'mypassword',
7 'HOST': 'localhost',
8 'PORT': '5432',
9 }
10}
1111. What caching strategies does Django provide?
Django provides several caching strategies to improve performance by storing frequently accessed data and reducing database load.
Per-site cache: Caches the entire website using middleware.
Per-view cache: Caches the output of specific views using decorators.
Template fragment cache: Caches specific parts of templates.
Low-level cache API: Allows manual caching of data using cache.set() and cache.get().
12. What are some of Django's built-in exception classes?
Django provides several built-in exception classes to handle errors related to models, HTTP requests, validation, and configuration.
ObjectDoesNotExist: Raised when a query does not return any matching object.
MultipleObjectsReturned: Raised when a query expected a single object returns multiple results.
ValidationError: Raised when data validation fails.
ImproperlyConfigured: Raised when Django is improperly configured.
PermissionDenied: Raised when a user does not have permission to perform an action.
13. What is NoSQL, and does Django natively support NoSQL databases?
NoSQL (Not Only SQL) databases are non-relational database systems that are capable of handling large amounts of unstructured or semi-structured data.
Django does not natively support NoSQL databases because its ORM system is designed for relational databases such as PostgreSQL, MySQL, SQLite, and Oracle. However, Django can be used with NoSQL databases such as MongoDB through third-party libraries such as Djongo or MongoEngine.
14. What are the different model inheritance styles supported in Django?
Django supports three types of model inheritance that allow you to reuse fields and behavior across multiple models.
Abstract Base Classes: The parent model is declared with abstract = True in its Meta class. Its fields are inherited by child models, but no separate database table is created for the parent.
Multi-table Inheritance: Each model in the inheritance chain has its own database table. The child model has a OneToOneField linking to the parent.
Proxy Models: Used to change behavior without creating a new database table. The proxy model operates on the same table as the parent.
15. What is the role of the settings.py file in a Django project?
The settings.py file is the central configuration file of a Django project. It contains configurations such as database connections, installed applications, middleware, template settings, static and media file paths, authentication settings, security options, and environment-specific variables like DEBUG and ALLOWED_HOSTS.
16. What is the {% csrf_token %} and why is it used in Django forms?
The {% csrf_token %} is a template tag in Django used to protect forms from Cross-Site Request Forgery (CSRF) attacks. When you include it inside a form, Django generates a unique security token and embeds it as a hidden input field. On form submission, Django verifies the token to ensure the request is legitimate.
Example:
1<form method="post">
2 {% csrf_token %}
3 <input type="text" name="username">
4 <button type="submit">Submit</button>
5</form>
617. How can you handle unique constraint (IntegrityError) exceptions when saving models in Django?
In Django, a unique constraint violation raises an IntegrityError. To handle this safely, wrap the save operation inside a try-except block and catch the IntegrityError exception.
Example:
1from django.db import IntegrityError
2from .models import User
3
4try:
5 user = User(username="vishal")
6 user.save()
7except IntegrityError:
8 print("Username already exists.")
918. How does the update_or_create() method work in Django's ORM?
The update_or_create() method in Django ORM is used to either update an existing object or create a new one if it does not exist. It works by first searching for an object that matches the given lookup parameters. If found, it updates the fields provided in the defaults dictionary. If no matching object exists, it creates a new record.
Example:
1student, created = Student.objects.update_or_create(
2 name="Vishal",
3 defaults={"age": 26}
4)
519. What are Django's generic class-based views and when should you use them?
Django's generic class-based views (GCBVs) are pre-built view classes that implement common web development patterns such as displaying a list of objects, showing a single object detail, creating, updating, or deleting objects. They eliminate boilerplate code that would otherwise be repeated across many views.
Common generic views include ListView, DetailView, CreateView, UpdateView, and DeleteView. You should use them when your view logic closely matches one of these standard patterns, as they significantly reduce the amount of code you need to write and maintain.
Example:
1from django.views.generic import ListView, DetailView
2from .models import Article
3
4class ArticleListView(ListView):
5 model = Article
6 template_name = 'articles/list.html'
7 context_object_name = 'articles'
8
9class ArticleDetailView(DetailView):
10 model = Article
11 template_name = 'articles/detail.html'
1220. How do you use database transactions in Django?
Database transactions in Django ensure that a group of database operations either all succeed or all fail together, maintaining data integrity. Django provides the atomic() context manager and decorator from django.db.transaction to wrap operations in a transaction.
If an exception occurs inside an atomic block, Django automatically rolls back all changes made within that block. This is especially useful when performing multiple related write operations, such as creating an order and deducting inventory at the same time.
Example:
1from django.db import transaction
2
3@transaction.atomic
4def create_order(user, items):
5 order = Order.objects.create(user=user)
6 for item in items:
7 OrderItem.objects.create(order=order, product=item)
8 # If anything fails here, both Order and OrderItems are rolled back
921. How do you create custom template tags and filters in Django?
Custom template tags and filters in Django allow you to extend the template engine with your own reusable logic. To create them, you create a templatetags directory inside your app, add an __init__.py file, and define your tags or filters in a Python file within that directory.
Filters are simple functions that transform a value and are registered using the @register.filter decorator. Template tags are more powerful and can accept arguments or output complex HTML, registered using @register.simple_tag or @register.inclusion_tag.
Example (Custom filter):
1# myapp/templatetags/custom_filters.py
2from django import template
3
4register = template.Library()
5
6@register.filter
7def capitalize_words(value):
8 return value.title()
9
10# Usage in template:
11# {% load custom_filters %}
12# {{ 'hello world'|capitalize_words }}
1322. How do you handle file uploads in Django?
Django handles file uploads through model fields and form processing. In a model, you use FileField or ImageField to define a file upload field and set the upload_to argument to specify the directory where files should be stored. In settings.py, you configure MEDIA_URL and MEDIA_ROOT to control where uploaded files are served from and stored.
In the HTML form, you must set enctype="multipart/form-data" and in the view, access the uploaded file via request.FILES. For image uploads, the Pillow library must be installed.
Example:
1# models.py
2class Profile(models.Model):
3 avatar = models.ImageField(upload_to='avatars/')
4
5# views.py
6def upload(request):
7 if request.method == 'POST':
8 form = ProfileForm(request.POST, request.FILES)
9 if form.is_valid():
10 form.save()
1123. How do you define and use a ManyToManyField in Django models?
A ManyToManyField in Django is used to define a many-to-many relationship between two models, where multiple instances of one model can be related to multiple instances of another. Django automatically creates an intermediate junction table to manage this relationship.
You interact with many-to-many relationships using the add(), remove(), set(), and clear() methods on the related manager. The through argument can be used to specify a custom intermediate model if you need to store additional data on the relationship.
Example:
1class Student(models.Model):
2 name = models.CharField(max_length=100)
3 courses = models.ManyToManyField('Course')
4
5class Course(models.Model):
6 title = models.CharField(max_length=200)
7
8# Usage
9student = Student.objects.get(id=1)
10student.courses.add(Course.objects.get(id=2))
11all_courses = student.courses.all()
1224. What is the reverse() function in Django and why is it useful?
The reverse() function in Django is used to dynamically generate URLs from named URL patterns instead of hardcoding URL strings. It takes the name of a URL pattern and any required arguments, and returns the corresponding URL path.
This is useful because if you change a URL path in urls.py, you only need to update it in one place, and all reverse() calls will automatically reflect the new URL. It prevents broken links caused by hardcoded URLs scattered across views and templates.
Example:
1from django.urls import reverse
2from django.http import HttpResponseRedirect
3
4def my_view(request):
5 # Instead of hardcoding '/home/', use reverse()
6 url = reverse('home') # Returns '/home/'
7 return HttpResponseRedirect(url)
8III. Advanced Level
1. What should you be careful about when overriding a model's save() method?
When overriding a model's save() method in Django, you must always call the parent class's save() method using super().save(*args, **kwargs). If you skip this step, the object will not be saved to the database.
You should also avoid placing heavy business logic inside save(), as it can impact performance and may execute multiple times. Additionally, be careful not to create recursive save() calls, which can lead to infinite loops.
Example:
1class Student(models.Model):
2 name = models.CharField(max_length=100)
3
4 def save(self, *args, **kwargs):
5 self.name = self.name.title()
6 super().save(*args, **kwargs)
72. How are form validation errors handled in a Django view?
In Django, form validation errors are handled using the is_valid() method of a form. When a form is submitted, Django automatically validates the data based on field definitions and custom validation methods. If form.is_valid() returns False, the form object contains error messages accessible via form.errors.
Example:
1def register(request):
2 if request.method == 'POST':
3 form = UserForm(request.POST)
4 if form.is_valid():
5 form.save()
6 else:
7 return render(request, 'register.html', {'form': form})
8 else:
9 form = UserForm()
10 return render(request, 'register.html', {'form': form})
113. How do you create a custom manager in Django, and when would you use one?
A custom manager in Django is created by subclassing models.Manager and adding custom query methods. It is used when you want to define reusable database query logic that can be accessed directly from the model.
Example:
1from django.db import models
2
3class ActiveManager(models.Manager):
4 def get_queryset(self):
5 return super().get_queryset().filter(is_active=True)
6
7class User(models.Model):
8 name = models.CharField(max_length=100)
9 is_active = models.BooleanField(default=True)
10
11 objects = models.Manager()
12 active_users = ActiveManager()
134. How can you customize the Django admin interface (e.g., using list_display, search_fields, inlines)?
The Django admin interface can be customized by defining a ModelAdmin class and registering it with the model. Common customization options include list_display for columns in the list view, search_fields to enable search, list_filter for sidebar filters, and inlines to edit related models on the same page.
Example:
1from django.contrib import admin
2from .models import Author, Book
3
4class BookInline(admin.TabularInline):
5 model = Book
6
7class AuthorAdmin(admin.ModelAdmin):
8 list_display = ('name', 'email')
9 search_fields = ('name',)
10 inlines = [BookInline]
11
12admin.site.register(Author, AuthorAdmin)
135. Why is Django considered a loosely coupled framework?
Django is said to be a loosely coupled framework since its components — models, views, templates, middleware, and URLs — are designed to be independent and interchangeable. For example, you can switch the database backend, template engine, or middleware without tightly coupled side effects on the rest of the application.
6. What built-in security features does Django provide (e.g., XSS, CSRF, SQL injection protection)?
Django provides several built-in security features to protect web applications from common vulnerabilities.
CSRF Protection: Uses CSRF tokens in forms to prevent Cross-Site Request Forgery attacks.
SQL Injection Protection: Django ORM uses parameterized queries, preventing malicious SQL injection.
XSS Protection: Automatically escapes variables in templates to prevent Cross-Site Scripting attacks.
Clickjacking Protection: Provides X-Frame-Options middleware to prevent embedding in malicious iframes.
Password Hashing: Uses strong hashing algorithms like PBKDF2 by default for secure password storage.
7. How does Django promote code reusability across projects?
Django promotes code reusability through its modular app-based architecture. Each app is a self-contained module with its own models, views, templates, forms, and static files that can be reused in multiple projects. Django also supports template inheritance, custom managers, middleware, and third-party packages which further enhance reusability.
8. How can you implement database sharding in Django for large-scale applications?
Database sharding in Django involves splitting data across multiple databases to handle large-scale applications. Django supports multiple databases configured in the DATABASES setting, and you use a custom database router to control how models are distributed across databases based on rules such as user ID ranges or hashing logic.
Example (Basic Router):
1class UserRouter:
2 def db_for_read(self, model, **hints):
3 if model._meta.app_label == 'users':
4 return 'shard1'
5 return 'default'
6
7 def db_for_write(self, model, **hints):
8 if model._meta.app_label == 'users':
9 return 'shard1'
10 return 'default'
119. What is the difference between select_related and prefetch_related in Django ORM?
Both select_related and prefetch_related are used to optimize database queries when accessing related objects, but they work differently.
select_related: Performs a SQL JOIN and retrieves related objects in a single query. Used for ForeignKey and OneToOneField relationships.
prefetch_related: Executes separate queries for related objects and performs joining in Python. Used for ManyToManyField and reverse ForeignKey relationships.
10. What is the Django REST Framework (DRF) and why is it useful?
Django REST Framework (DRF) is a powerful toolkit that uses Django to build Web APIs. It provides reusable building blocks such as serializers, viewsets, authentication, permissions, and routers. DRF handles common tasks like parsing requests, validating data, serializing querysets, token/JWT authentication, pagination, and provides a browsable API interface.
11. What are Q objects in Django's ORM and when would you use them?
Q objects in Django ORM are used to construct complex database queries using logical operators such as AND, OR, and NOT. You use Q objects when you need OR conditions or complex filtering logic that cannot be achieved using simple filter() arguments.
Example:
1from django.db.models import Q
2
3students = Student.objects.filter(
4 Q(name="Vishal") | Q(age__gt=20)
5)
612. How does update_or_create() optimize object creation or updating?
update_or_create() merges the lookup and save process into a single atomic operation, reducing boilerplate code, minimizing race conditions, and ensuring data consistency by wrapping the operation in a transaction. If a matching object is found it updates the specified fields; otherwise it creates a new record.
13. What are the implications of overriding a Django model's save() method?
Overriding save() allows custom behavior before or after saving, but requires calling super().save(). Heavy logic inside save() impacts performance and can cause unexpected behavior in admin, signals, or bulk operations. Signals or service layers may be better alternatives for complex business logic.
14. How should you handle unique constraint errors (like IntegrityError) when saving objects?
Wrap the save operation in a try-except block catching IntegrityError. Alternatively, validate data before saving using form validation or model.full_clean(), or use get_or_create() / update_or_create() to safely handle duplicate cases.
Example:
1from django.db import IntegrityError
2
3try:
4 user = User(username="vishal")
5 user.save()
6except IntegrityError:
7 print("Duplicate entry detected.")
815. How are form validation errors surfaced when calling form.is_valid() in a view?
When form.is_valid() is called and validation fails, is_valid() returns False. Errors are stored in form.errors as a dictionary mapping field names to error messages. When the form is passed back to the template, Django automatically displays errors next to the corresponding fields.
16. When and why would you use a custom manager in Django?
Use a custom manager when certain filtering or business rules are frequently applied, such as retrieving only active users, published articles, or soft-deleted records. Custom managers improve code readability, avoid repetition, and keep query logic centralized in one place.
17. If a Django view returns a 404 error even though the URL exists, what might be wrong?
Common causes include an incorrect URL pattern in urls.py (e.g., missing trailing slash, wrong parameter type), a parameter mismatch where the view expects <int:id> but receives a string, an object not found in the database when using get() or get_object_or_404(), or the app's urls.py not being included in the project's main urls.py.
18. How can you avoid N+1 query problems in Django REST Framework serializers?
Avoid N+1 problems by using select_related() for ForeignKey and OneToOneField relationships, prefetch_related() for ManyToMany and reverse relationships, and optimizing the queryset in the view's get_queryset() method rather than inside the serializer.
Example:
1class StudentViewSet(ModelViewSet):
2 queryset = Student.objects.select_related('school').prefetch_related('courses')
3 serializer_class = StudentSerializer
419. In what scenarios might you choose Django over Flask, or vice versa?
Choose Django for large, feature-rich applications requiring built-in authentication, admin, ORM, and security — ideal for e-commerce, CMS, or enterprise systems. Choose Flask for small applications, microservices, or APIs where flexibility and minimalism are preferred and you want full control over every component.
20. Is Django stable and well-suited for high-traffic applications?
Yes, Django is a stable and mature framework well-suited for high-traffic applications. When combined with caching layers like Redis, database optimization, load balancers, and production servers like Gunicorn or Nginx, Django can handle millions of users efficiently. It powers large-scale platforms and is production-ready.
21. How can you scale a Django application to handle large workloads?
Scaling a Django application involves using caching (Redis, Memcached) to reduce database load, optimizing queries with select_related() and prefetch_related(), using load balancers to distribute traffic, running Django with Gunicorn or uWSGI behind Nginx, and using Celery for background task processing.
22. What additional security measures should you take when deploying Django to production?
Set DEBUG = False, configure ALLOWED_HOSTS, enable HTTPS with SECURE_SSL_REDIRECT = True, use secure cookies (SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE), enable SecurityMiddleware with HSTS headers, and never expose sensitive configuration values like SECRET_KEY in source control.
23. How do you integrate Celery with Django for asynchronous task processing?
Celery is a distributed task queue that integrates with Django to handle time-consuming or background tasks asynchronously, such as sending emails, processing images, or generating reports. It decouples these operations from the request-response cycle, improving application responsiveness.
To integrate Celery, you install it along with a message broker like Redis or RabbitMQ, create a celery.py configuration file in your Django project, and define tasks using the @shared_task or @app.task decorators. Tasks are then called asynchronously using .delay() or .apply_async().
Example:
1# tasks.py
2from celery import shared_task
3from django.core.mail import send_mail
4
5@shared_task
6def send_welcome_email(user_email):
7 send_mail(
8 'Welcome!',
9 'Thanks for signing up.',
10 'noreply@example.com',
11 [user_email]
12 )
13
14# In a view:
15send_welcome_email.delay(user.email)
1624. What are Django Channels and how do they enable WebSocket support?
Django Channels extends Django beyond HTTP to handle WebSockets, long-polling, and other asynchronous protocols. By default, Django is synchronous and only handles HTTP requests. Channels introduces the concept of consumers — similar to views — that handle different types of connections including WebSockets.
Channels uses ASGI (Asynchronous Server Gateway Interface) instead of WSGI to support concurrent connections. It relies on a channel layer (usually Redis) to pass messages between consumers. This makes it ideal for real-time features like chat applications, live notifications, or collaborative tools.
Example (WebSocket Consumer):
1from channels.generic.websocket import AsyncWebsocketConsumer
2import json
3
4class ChatConsumer(AsyncWebsocketConsumer):
5 async def connect(self):
6 await self.accept()
7
8 async def receive(self, text_data):
9 data = json.loads(text_data)
10 await self.send(text_data=json.dumps({'message': data['message']}))
11
12 async def disconnect(self, close_code):
13 pass
1425. How does Django's database router work when using multiple databases?
Django's database router allows you to control which database is used for read and write operations, allowing migrations, and determining whether cross-database relationships are permitted. A router is a Python class that implements up to four methods: db_for_read(), db_for_write(), allow_relation(), and allow_migrate().
You register your router in settings.py under DATABASE_ROUTERS. Django will call the router methods automatically during ORM operations to determine the correct database. Multiple routers can be chained, with Django consulting them in order until one returns a non-None result.
Example:
1# routers.py
2class AnalyticsRouter:
3 def db_for_read(self, model, **hints):
4 if model._meta.app_label == 'analytics':
5 return 'analytics_db'
6 return None
7
8 def db_for_write(self, model, **hints):
9 if model._meta.app_label == 'analytics':
10 return 'analytics_db'
11 return None
12
13 def allow_migrate(self, db, app_label, model_name=None, **hints):
14 if app_label == 'analytics':
15 return db == 'analytics_db'
16 return None
17
18# settings.py
19DATABASE_ROUTERS = ['myproject.routers.AnalyticsRouter']
2026. What is the Django contenttypes framework and what are its use cases?
The Django contenttypes framework (django.contrib.contenttypes) provides a generic interface to work with any installed model in your project. It stores information about every model in your application and allows you to create generic relationships between models without hard-coding a ForeignKey to a specific model.
Common use cases include implementing generic comment or tagging systems that can attach to any model, building activity streams, creating permission systems, and implementing polymorphic relationships. It uses ContentType model together with GenericForeignKey and GenericRelation fields.
Example (Generic comment system):
1from django.contrib.contenttypes.fields import GenericForeignKey
2from django.contrib.contenttypes.models import ContentType
3
4class Comment(models.Model):
5 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
6 object_id = models.PositiveIntegerField()
7 content_object = GenericForeignKey('content_type', 'object_id')
8 text = models.TextField()
9
10# A Comment can now be attached to any model instance
1127. How do you implement JWT authentication in Django REST Framework?
JWT (JSON Web Token) authentication in DRF is commonly implemented using the djangorestframework-simplejwt package. JWTs are stateless tokens that encode user identity and are sent with each API request in the Authorization header, eliminating the need for server-side session storage.
After installing the package, you configure DEFAULT_AUTHENTICATION_CLASSES in settings.py and add token obtain and refresh URL endpoints. The client exchanges credentials for an access token and a refresh token. The access token is short-lived while the refresh token can be used to obtain new access tokens without re-authentication.
Example:
1# settings.py
2REST_FRAMEWORK = {
3 'DEFAULT_AUTHENTICATION_CLASSES': (
4 'rest_framework_simplejwt.authentication.JWTAuthentication',
5 ),
6}
7
8# urls.py
9from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
10
11urlpatterns = [
12 path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
13 path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
14]
1528. What are the best practices for writing tests in Django?
Django provides a robust testing framework built on Python's unittest module. Writing good tests ensures your application behaves correctly as it evolves. Best practices include organizing tests into separate files per app, using Django's TestCase class for database tests and SimpleTestCase for tests that don't require the database.
Use Django's TestClient to simulate HTTP requests and test views end-to-end.
Use fixtures or factory libraries like factory_boy to create test data cleanly.
Mock external services and API calls using unittest.mock to keep tests isolated.
Keep tests fast and independent — each test should set up its own state and not rely on other tests.
Aim for high coverage on models, views, serializers, and forms, but prioritize meaningful tests over 100% coverage.
Example:
1from django.test import TestCase, Client
2from django.urls import reverse
3from .models import Student
4
5class StudentViewTest(TestCase):
6 def setUp(self):
7 self.client = Client()
8 self.student = Student.objects.create(name='Alice', age=22)
9
10 def test_student_list_view(self):
11 response = self.client.get(reverse('student-list'))
12 self.assertEqual(response.status_code, 200)
13 self.assertContains(response, 'Alice')
1429. What are F() expressions in Django ORM and when would you use them?
F() expressions in Django ORM allow you to reference the value of a model field directly in a database query without first loading it into Python. This means the operation is performed entirely at the database level, which is more efficient and avoids race conditions in concurrent environments.
Common use cases include incrementing a counter field without reading its current value first, comparing two fields on the same model in a filter, or performing arithmetic between model fields in an update query. F() expressions are particularly valuable in high-concurrency scenarios where multiple requests might update the same record simultaneously.
Example:
1from django.db.models import F
2
3# Increment view_count without reading it first (race-condition safe)
4Article.objects.filter(id=1).update(view_count=F('view_count') + 1)
5
6# Compare two fields in a filter
7Product.objects.filter(stock__lt=F('min_stock'))
8
9# Use in an annotation
10from django.db.models import ExpressionWrapper, FloatField
11Product.objects.annotate(
12 profit=ExpressionWrapper(F('price') - F('cost'), output_field=FloatField())
13)
14Related Articles
React JS Interview Questions
Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.
BackendPython Interview Questions
Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.