Django - Interview Questions and Answers
Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. It follows the Model-View-Template (MVT) architecture.
- Built-in authentication
- ORM (Object-Relational Mapping)
- Middleware support
- Scalability and security
- Admin panel for easy management
- Model: Manages data and database interactions
- View: Handles business logic and user requests
- Template: Defines how data is presented to the user
Run:
django-admin startproject myproject
Run:
python manage.py startapp myapp
It is a command-line utility for managing a Django project, including database migrations, running the server, and creating superusers.
Django models define database tables using Python classes. Example:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
published_date = models.DateField()
Django’s ORM allows interaction with the database using Python instead of SQL. Example:
books = Book.objects.all() # Fetch all books
python manage.py makemigrations
python manage.py migrate
Views handle HTTP requests and responses. Example:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
- Function-Based Views (FBV): Simple functions handling requests
- Class-Based Views (CBV): Use Python classes for better code reusability
Example of CBV:
from django.views import View
from django.http import HttpResponse
class HomeView(View):
def get(self, request):
return HttpResponse("Hello from CBV")
Templates define HTML structure with dynamic content using template tags.
Example:
<h1>Welcome {{ user.username }}</h1>
Middleware processes requests before reaching views and responses before sending them to clients.
In urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
It contains all configuration settings like database setup, installed apps, and middleware.
The cycle involves the request passing through middleware, reaching the view, and returning a response.
Signals help decouple applications by sending notifications when an event occurs.
Example:
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import UserProfile
@receiver(post_save, sender=UserProfile)
def notify_user(sender, instance, **kwargs):
print(f"User {instance.user} was updated")
Django provides django.contrib.auth
for user authentication.
Run:
python manage.py createsuperuser
Django Forms simplify HTML form handling in Python.
Example:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
DRF helps create RESTful APIs in Django.
Example using DRF ViewSets:
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
Django provides built-in caching to store frequently used data. Example:
from django.core.cache import cache
cache.set('key', 'value', timeout=60)
Django includes CSRF middleware to prevent cross-site request forgery attacks.
Celery is used for background task processing in Django.
Sessions store user-specific data across requests.
- Static Files: CSS, JavaScript, images
- Media Files: User-uploaded content
Django Admin can be customized using admin.py
.
Example:
from django.contrib import admin
from .models import Book
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author')
admin.site.register(Book, BookAdmin)
Django provides logging for debugging.
Django provides protection against SQL injection, XSS, and CSRF.
- Django Signals are used to handle events like user creation or updates asynchronously.
- Middleware modifies requests or responses globally before they reach the view.
You can define multiple databases in settings.py
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'default_db',
'USER': 'default_user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
},
'secondary': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'secondary_db',
'USER': 'secondary_user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
},
}
To query different databases:
from myapp.models import User
User.objects.using('secondary').all()
- ForeignKey: Many-to-one relationship
- OneToOneField: One-to-one relationship
- ManyToManyField: Many-to-many relationship
Example:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Use Django Channels to handle WebSockets:
pip install channels
In settings.py
:
INSTALLED_APPS = [
'channels',
'myapp',
]
ASGI_APPLICATION = 'myproject.asgi.application'
Example consumer:
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def receive(self, text_data):
data = json.loads(text_data)
await self.send(text_data=json.dumps({'message': data['message']}))
Use Django’s built-in unittest
framework:
from django.test import TestCase
from .models import Book
class BookTestCase(TestCase):
def setUp(self):
Book.objects.create(title="Test Book", author="John Doe")
def test_book_title(self):
book = Book.objects.get(title="Test Book")
self.assertEqual(book.author, "John Doe")
Run tests:
python manage.py test
Use atomic
to ensure a transaction is successful or rolled back:
from django.db import transaction
with transaction.atomic():
user = User.objects.create(username="testuser")
profile = Profile.objects.create(user=user)
- Install Celery:
pip install celery
- Configure Celery in
settings.py
:
CELERY_BROKER_URL = 'redis://localhost:6379/0'
- Create a Celery task:
from celery import shared_task
@shared_task
def add(x, y):
return x + y
- Run Celery:
celery -A myproject worker --loglevel=info
- Install Gunicorn:
pip install gunicorn
- Run Django with Gunicorn:
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000
- Configure Nginx as a reverse proxy for Gunicorn.
- Use
select_related()
for foreign key relationships - Use
prefetch_related()
for many-to-many relationships - Avoid N+1 query problems
- Use indexes on frequently queried fields
Example:
books = Book.objects.select_related('author').all()
- Install Redis:
pip install django-redis
- Configure Redis in
settings.py
:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
}
}
- Use Redis for caching:
from django.core.cache import cache
cache.set('key', 'value', timeout=60)
Django supports multiple languages using:
from django.utils.translation import gettext_lazy as _
class Book(models.Model):
title = models.CharField(max_length=100, verbose_name=_("Book Title"))
class Document(models.Model):
file = models.FileField(upload_to='documents/')
In views.py
:
from django.http import Http404
def my_view(request):
if not some_condition:
raise Http404("Page not found")
Custom 404 template:
{% block content %}
<h1>Page Not Found</h1>
{% endblock %}
Use Django’s Group
and Permission
:
from django.contrib.auth.models import Group, Permission
group = Group.objects.create(name="Editors")
permission = Permission.objects.get(codename="change_article")
group.permissions.add(permission)
It restricts views to authenticated users:
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, "dashboard.html")
from django.http import JsonResponse
def my_view(request):
data = {'message': 'Hello, Django!'}
return JsonResponse(data)
Use reportlab
:
pip install reportlab
Example PDF view:
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def generate_pdf(request):
response = HttpResponse(content_type='application/pdf')
p = canvas.Canvas(response)
p.drawString(100, 800, "Hello, PDF!")
p.showPage()
p.save()
return response
Use Celery
or cron jobs
. Example using Celery:
@shared_task
def scheduled_task():
print("Scheduled task executed")
STATICFILES_DIRS
: List of directories for static files during developmentSTATIC_ROOT
: The folder where collected static files are stored in production
In settings.py
:
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
get_object_or_404()
returns an object or raises a404 Not Found
error if the object doesn’t exist.get()
raises aDoesNotExist
exception, which needs to be handled manually.
Example:
from django.shortcuts import get_object_or_404
from myapp.models import Book
book = get_object_or_404(Book, id=1) # Returns a 404 error if not found
Django Signals allow decoupled applications to communicate when an event occurs.
Example: Execute a function after a user is created.
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from myapp.models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
- ListView: Displays a list of objects.
- DetailView: Displays a single object.
- CreateView: Handles form submission to create an object.
Example:
from django.views.generic import ListView
from myapp.models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
- Create a
templatetags
directory inside your Django app. - Add a Python file (e.g.,
custom_filters.py
). - Define the filter:
from django import template
register = template.Library()
@register.filter
def upper_case(value):
return value.upper()
- Use it in a template:
{{ "hello" | upper_case }}
Django supports various session backends:
- Database (
django.contrib.sessions.backends.db
) - Cached (
django.contrib.sessions.backends.cache
) - File-based (
django.contrib.sessions.backends.file
)
Enable sessions in settings.py
:
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_COOKIE_AGE = 3600 # Session expires in 1 hour
Set and get session data:
request.session["username"] = “DynamicUser”
usernamedata = request.session.get("username" “Guest”)
Django provides built-in authentication using django.contrib.auth
.
- Login View:
from django.contrib.auth import authenticate, login
user = authenticate(request, username='admin', password='mypassword')
if user:
login(request, user)
- Logout View:
from django.contrib.auth import logout
logout(request)
- Protect Views:
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')
Use Django’s Paginator
class for paginating query results.
from django.core.paginator import Paginator
from django.shortcuts import render
from myapp.models import Book
def book_list(request):
book_objects = Book.objects.all()
paginator = Paginator(book_objects, 10) # 10 books per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'book_list.html', {'page_obj': page_obj})
- SQL Injection: Use Django ORM instead of raw SQL.
- CSRF Attacks: Enable
csrf_token
in forms. - XSS Attacks: Use Django’s built-in escaping in templates.
- Clickjacking: Add
X-Frame-Options
header insettings.py
:
X_FRAME_OPTIONS = 'DENY'
- Use
SECURE_SSL_REDIRECT = True
to enforce HTTPS.
Django supports multiple caching backends like Redis, Memcached, and database caching.
- Enable caching in
settings.py
:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
- Cache a view using
cache_page
:
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # Cache for 15 minutes
def my_view(request):
...
- Set and get cache manually:
from django.core.cache import cache
cache.set('key', 'value', timeout=60)
data = cache.get('key')
Install Django REST Framework:
pip install djangorestframework
In settings.py
:
INSTALLED_APPS = [
'rest_framework',
'myapp',
]
Define a Serializer:
from rest_framework import serializers
from myapp.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
Define a ViewSet:
from rest_framework import viewsets
from myapp.models import Book
from myapp.serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
Define URLs using a router:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
Tutorials
Random Blogs
- 15 Amazing Keyword Research Tools You Should Explore
- Important Mistakes to Avoid While Advertising on Facebook
- Python Challenging Programming Exercises Part 3
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- SQL Joins Explained: A Complete Guide with Examples
- The Ultimate Guide to Machine Learning (ML) for Beginners
- Best Platform to Learn Digital Marketing in Free
- Datasets for Natural Language Processing
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Google’s Core Update in May 2020: What You Need to Know