Free practice questions

Technical
Interview questions

Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.

Django questions
50 questions
25
25 concept questions
25
25 coding questions

Django technical questions

Django MVT Architecture, ORM QuerySets, Views, Models, Security, Middleware & REST Framework
Total 50 Questions
Part A: Core concept & theory questions
Questions 01 to 25 • Theoretical Foundations
25 Concept Questions

Django is a Python web framework that comes with most of what a site needs: an ORM, an admin panel, authentication, forms and security protections. Its motto is "batteries included", so I write less setup code.

Model handles data, View holds the logic and decides what to return, and Template controls how it looks. The URL dispatcher routes each request to the right view. It's Django's version of MVC, and the framework itself plays the controller role.

A project is the whole website with its settings and main URLs. An app is one feature inside it, like blog or accounts. One project holds many apps, and an app can be reused in other projects.

The request passes through middleware, then the URL resolver finds the matching view. The view may use models and templates, builds a response, and the response travels back out through middleware to the browser.

It holds the project's configuration: installed apps, database, middleware, templates, static files, time zone and the secret key. Sensitive values should come from environment variables, not be hardcoded.

urls.py maps URL patterns to views using path(). Patterns can capture values like <int:id>, and include() lets each app keep its own URL file.

A function-based view is a plain function, simple and explicit. A class-based view uses classes and mixins, so common jobs like listing or creating objects need very little code. I use functions for custom logic and classes for standard CRUD.

It's Django's templating system with {{ variable }} for output, {% tag %} for logic like loops and conditions, and filters like |date. Output is HTML-escaped by default, which helps against XSS.

A base template defines the common layout with {% block %} areas, and child templates use {% extends %} to fill those blocks. This avoids repeating headers and footers.

It lets me work with the database using Python classes instead of SQL. A model class is a table, an instance is a row, and Post.objects.filter(...) becomes a SELECT query.

Files that record changes to my models so the database structure can be updated to match. makemigrations creates them and migrate applies them. They also act as a history of the schema.

A QuerySet is a collection of database results. It doesn't hit the database until I actually use it, such as looping over it or calling list(). This lets me chain filters without extra queries.

ForeignKey for one-to-many, OneToOneField for one-to-one and ManyToManyField for many-to-many.

Looping over objects and running an extra query for each related object. select_related fixes it for foreign keys with a SQL join, and prefetch_related fixes it for many-to-many with one extra query.

An automatic management interface built from my models. After registering a model, I can add, edit, search and delete records with no extra code, and I can customize it with ModelAdmin.

A Form is defined by hand with its own fields. A ModelForm builds its fields from a model, so validation and saving to the database come almost for free.

A layer that sits between the request and the view, and again on the way back. Built-in examples handle sessions, authentication, security headers and CSRF checks. I can also write my own.

The django.contrib.auth app provides users, passwords (hashed), login and logout, sessions, groups and permissions. Views can be protected with @login_required or LoginRequiredMixin.

Django gives each session a secret token and requires it on POST forms through {% csrf_token %}. If the token is missing or wrong, the request is rejected, which blocks forged requests from other sites.

Static files are part of my code, like CSS, JavaScript and logos. Media files are uploaded by users while the site runs, like profile photos. They use separate settings: STATIC_URL and MEDIA_URL.

They let one part of the app react when something happens elsewhere, like creating a profile whenever a new user is saved. They're useful but can make code hard to follow if overused.

Protection against SQL injection (through the ORM), XSS (template escaping), CSRF, clickjacking (X-Frame-Options), and secure password hashing. I still must set DEBUG = False and use HTTPS in production.

A toolkit for building APIs on top of Django. It provides serializers (convert models to JSON and back), viewsets, routers, authentication and permissions.

It supports per-site, per-view and low-level caching, with backends like local memory, Redis and Memcached. Caching saves repeated work on expensive pages or queries.

Set DEBUG = False and ALLOWED_HOSTS, keep secrets in environment variables, run collectstatic, serve the app with Gunicorn behind Nginx, use a real database like PostgreSQL, and enable HTTPS.

Part B: Coding questions & algorithm solutions
Questions 01 to 25 • Runnable Solution Scripts
25 Coding Questions

CLI setup commands for virtualenv, django project, blog app and development server.

Django Solution
python -m venv venv
source venv/bin/activate        # Windows: venv\Scripts\activate
pip install django
django-admin startproject mysite
cd mysite
python manage.py startapp blog
python manage.py runserver

Configure INSTALLED_APPS, create HttpResponse home view, and map path in blog/urls.py.

Django Solution
# mysite/settings.py
INSTALLED_APPS = [
    # ...default apps...
    "blog",
]

# blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to my blog")

# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
]

Use include() in root urls.py to attach blog.urls.

Django Solution
# mysite/urls.py
from django.contrib.admin import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("blog.urls")),
]

Define Django model with CharField, TextField, ForeignKey to User, choices, and Ordering meta.

Django Solution
# blog/models.py
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    STATUS = [("draft", "Draft"), ("published", "Published")]

    title = models.CharField(max_length=150)
    body = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
    status = models.CharField(max_length=10, choices=STATUS, default="draft")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

CLI commands for makemigrations, migrate and createsuperuser.

Django Solution
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Use @admin.register with ModelAdmin list_display, list_filter and search_fields.

Django Solution
# blog/admin.py
from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "status", "created_at")
    list_filter = ("status", "created_at")
    search_fields = ("title", "body")

Execute ORM CRUD operations inside python manage.py shell.

Django Solution
# python manage.py shell
from blog.models import Post
from django.contrib.auth.models import User

user = User.objects.first()

p = Post.objects.create(title="First post", body="Hello", author=user)  # create
Post.objects.all()                                                       # read all
Post.objects.get(id=p.id)                                                # read one

p.title = "Updated title"                                                # update
p.save()

p.delete()                                                               # delete

Use filter(), exclude(), order_by(), Q objects and count().

Django Solution
from django.db.models import Q
from blog.models import Post

Post.objects.filter(status="published")
Post.objects.exclude(status="draft")
Post.objects.filter(title__icontains="django").order_by("-created_at")
Post.objects.filter(Q(title__icontains="python") | Q(body__icontains="python"))
Post.objects.filter(status="published").count()

Use select_related('author') to perform SQL join.

Django Solution
# slow: one extra query per post
for post in Post.objects.all():
    print(post.author.username)

# fast: author is fetched with a join
for post in Post.objects.select_related("author"):
    print(post.author.username)

Use get_object_or_404 and render template with context.

Django Solution
# blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
    posts = Post.objects.filter(status="published").select_related("author")
    return render(request, "blog/post_list.html", {"posts": posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk, status="published")
    return render(request, "blog/post_detail.html", {"post": post})

# blog/urls.py
urlpatterns = [
    path("", views.post_list, name="post_list"),
    path("post/<int:pk>/", views.post_detail, name="post_detail"),
]

Use {% block %}, {% extends %}, {% for %} and DTL template filters.

Django Solution
<!-- blog/templates/base.html -->
<!DOCTYPE html>
<html>
<head><title>{% block title %}My Blog{% endblock %}</title></head>
<body>
  <nav><a href="{% url 'post_list' %}">Home</a></nav>
  {% block content %}{% endblock %}
</body>
</html>

<!-- blog/templates/blog/post_list.html -->
{% extends "base.html" %}
{% block content %}
  {% for post in posts %}
    <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a></h2>
    <p>{{ post.body|truncatewords:30 }}</p>
    <small>By {{ post.author }} on {{ post.created_at|date:"d M Y" }}</small>
  {% empty %}
    <p>No posts yet.</p>
  {% endfor %}
{% endblock %}

Define ModelForm with custom field validation clean_title().

Django Solution
# blog/forms.py
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body", "status"]

    def clean_title(self):
        title = self.cleaned_data["title"]
        if len(title) < 5:
            raise forms.ValidationError("Title must be at least 5 characters.")
        return title

Use @login_required, form.is_valid(), commit=False and {% csrf_token %}.

Django Solution
# blog/views.py
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from .forms import PostForm

@login_required
def post_create(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect("post_detail", pk=post.pk)
    else:
        form = PostForm()
    return render(request, "blog/post_form.html", {"form": form})

<!-- HTML Form -->
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>

Inherit ListView and DetailView.

Django Solution
from django.views.generic import ListView, DetailView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = "blog/post_list.html"
    context_object_name = "posts"
    queryset = Post.objects.filter(status="published")

class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html"

# blog/urls.py
path("", PostListView.as_view(), name="post_list"),
path("post/<int:pk>/", PostDetailView.as_view(), name="post_detail"),

Combine LoginRequiredMixin, UserPassesTestMixin (OwnerMixin) with CreateView, UpdateView, DeleteView.

Django Solution
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ["title", "body", "status"]

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class OwnerMixin(UserPassesTestMixin):
    def test_func(self):
        return self.get_object().author == self.request.user

class PostUpdateView(LoginRequiredMixin, OwnerMixin, UpdateView):
    model = Post
    fields = ["title", "body", "status"]

class PostDeleteView(LoginRequiredMixin, OwnerMixin, DeleteView):
    model = Post
    success_url = reverse_lazy("post_list")

Create middleware calculating time.time() elapsed.

Django Solution
# blog/middleware.py
import time

class TimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start = time.time()
        response = self.get_response(request)
        response["X-Time-Taken"] = f"{time.time() - start:.3f}s"
        return response

# settings.py
MIDDLEWARE = [
    # ...existing middleware...
    "blog.middleware.TimingMiddleware",
]

Set LOGIN_URL, LOGIN_REDIRECT_URL, include django.contrib.auth.urls, and create registration/login.html.

Django Solution
# settings.py
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "post_list"
LOGOUT_REDIRECT_URL = "post_list"

# mysite/urls.py
urlpatterns += [
    path("accounts/", include("django.contrib.auth.urls")),
]

<!-- templates/registration/login.html -->
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button>Log in</button>
</form>

Use UserCreationForm with login() upon valid registration.

Django Solution
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

def signup(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect("post_list")
    else:
        form = UserCreationForm()
    return render(request, "registration/signup.html", {"form": form})

Use django.core.paginator Paginator in view and DTL page navigation in template.

Django Solution
from django.core.paginator import Paginator

def post_list(request):
    posts = Post.objects.filter(status="published")
    paginator = Paginator(posts, 5)
    page = paginator.get_page(request.GET.get("page"))
    return render(request, "blog/post_list.html", {"page": page})

<!-- Template -->
{% for post in page %}<h2>{{ post.title }}</h2>{% endfor %}

{% if page.has_previous %}<a href="?page={{ page.previous_page_number }}">Previous</a>{% endif %}
Page {{ page.number }} of {{ page.paginator.num_pages }}
{% if page.has_next %}<a href="?page={{ page.next_page_number }}">Next</a>{% endif %}

Extend models.Manager overriding get_queryset().

Django Solution
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status="published")

class Post(models.Model):
    # ...fields...
    objects = models.Manager()
    published = PublishedManager()

# Usage: Post.published.all()

Use @receiver(post_save, sender=User) to auto-create Profile.

Django Solution
# accounts/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True)

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

Create ModelSerializer, ModelViewSet and DefaultRouter.

Django Solution
# blog/serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Post
        fields = ["id", "title", "body", "author", "status", "created_at"]

# blog/api.py
from rest_framework import viewsets, permissions
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

# mysite/urls.py
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("posts", PostViewSet)
urlpatterns += [path("api/", include(router.urls))]

Configure ImageField, MEDIA_URL, MEDIA_ROOT and form enctype='multipart/form-data'.

Django Solution
# models.py
cover = models.ImageField(upload_to="covers/", blank=True, null=True)

# settings.py
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

# mysite/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

<!-- Template -->
<form method="post" enctype="multipart/form-data">
  {% csrf_token %}{{ form.as_p }}<button>Save</button>
</form>
{% if post.cover %}<img src="{{ post.cover.url }}" alt="{{ post.title }} text-center me-2">{% endif %}

Extend TestCase using self.client.get and assertEqual/assertContains.

Django Solution
# blog/tests.py
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from .models import Post

class PostTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user("asha", password="pass12345")
        Post.objects.create(title="Hello world", body="Body text",
                            author=self.user, status="published")

    def test_list_page_shows_post(self):
        response = self.client.get(reverse("post_list"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Hello world")

    def test_create_requires_login(self):
        response = self.client.get(reverse("post_create"))
        self.assertEqual(response.status_code, 302)

    def test_logged_in_user_can_open_create_page(self):
        self.client.login(username="asha", password="pass12345")
        response = self.client.get(reverse("post_create"))
        self.assertEqual(response.status_code, 200)

Extend BaseCommand with handle() querying created_at__lt=cutoff.

Django Solution
# blog/management/commands/clean_drafts.py
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from blog.models import Post

class Command(BaseCommand):
    help = "Delete draft posts older than 30 days"

    def handle(self, *args, **options):
        cutoff = timezone.now() - timedelta(days=30)
        deleted, _ = Post.objects.filter(status="draft", created_at__lt=cutoff).delete()
        self.stdout.write(self.style.SUCCESS(f"Deleted {deleted} old drafts"))

No Matching Questions Found

Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".

Technical Panel Preparation

Ready to Benchmark Your Technical Skills?

Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.

1