Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Django Documentation

The batteries-included Python web framework — ORM, migrations, admin panel, auth and templates.

Django is a "batteries-included" Python web framework. Out of the box you get an ORM, migrations, an admin panel, authentication, forms, templates and strong security defaults. Instagram, Pinterest and Disqus started on Django. It follows the MVT pattern: Model (data), View (logic), Template (HTML).

1. Introduction & Installation

python -m venv venv
venv\Scripts\activate            # Windows
source venv/bin/activate         # macOS / Linux
pip install django
django-admin startproject mysite .
python manage.py startapp notes
python manage.py runserver

Output:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
mysite/
├── manage.py               ← command-line tool
├── mysite/
│   ├── settings.py         ← configuration
│   ├── urls.py             ← root URL routes
│   └── wsgi.py / asgi.py   ← entry points for servers
└── notes/                  ← an "app" (a feature module)
    ├── models.py
    ├── views.py
    ├── admin.py
    ├── apps.py
    ├── tests.py
    └── migrations/

Register the app in settings.py:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "notes",                       # ← your app
]

⚠️ Common error: ModuleNotFoundError: No module named 'django' — the virtual environment isn't activated.

Project vs app: a project is the whole website (settings); apps are reusable pieces (blog, accounts, notes).

2. URLs & Views

# notes/views.py
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect

def home(request):
    return HttpResponse("Hello from Django!")

def note_detail(request, pk):
    note = get_object_or_404(Note, pk=pk)          # 404 if missing
    return render(request, "notes/detail.html", {"note": note})

def api_ping(request):
    return JsonResponse({"ok": True})
# notes/urls.py
from django.urls import path
from . import views

app_name = "notes"
urlpatterns = [
    path("", views.note_list, name="list"),
    path("<int:pk>/", views.note_detail, name="detail"),
    path("new/", views.note_create, name="create"),
]

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

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

Path converters: <int:pk>, <str:name>, <slug:slug>, <uuid:id>, <path:rest>. Reverse URLs by name instead of hard-coding: reverse("notes:detail", args=[3]) → /notes/3/.

Class-based views (less code for common patterns):

from django.views.generic import ListView, DetailView, CreateView
from django.urls import reverse_lazy

class NoteListView(ListView):
    model = Note
    paginate_by = 20
    template_name = "notes/list.html"

class NoteCreateView(CreateView):
    model = Note
    fields = ["title", "body"]
    success_url = reverse_lazy("notes:list")

3. Models & the ORM

# notes/models.py
from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name

class Note(models.Model):
    title = models.CharField(max_length=120)
    body = models.TextField(blank=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name="notes")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    tags = models.ManyToManyField("Tag", blank=True)
    published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True)

Migrations turn model changes into SQL:

python manage.py makemigrations     # create migration files from model changes
python manage.py migrate            # apply them to the database
python manage.py showmigrations
python manage.py sqlmigrate notes 0001   # see the SQL

Common fields: CharField, TextField, IntegerField, DecimalField, BooleanField, DateField, DateTimeField, EmailField, SlugField, ImageField, FileField, JSONField, ForeignKey, OneToOneField, ManyToManyField. on_delete: CASCADE, PROTECT, SET_NULL, SET_DEFAULT, DO_NOTHING.

4. QuerySets

Note.objects.all()
Note.objects.filter(published=True, title__icontains="graph")
Note.objects.exclude(category__name="DSA")
Note.objects.get(pk=1)                       # exactly one, else DoesNotExist / MultipleObjectsReturned
Note.objects.order_by("-created_at")[:10]    # LIMIT 10
Note.objects.filter(created_at__year=2026).count()
Note.objects.filter(author=request.user).exists()

note = Note.objects.create(title="Heaps", author=user)
Note.objects.filter(pk=1).update(published=False)
note.delete()

Field lookups: exact, iexact, contains, icontains, in, gt, gte, lt, lte, startswith, range, isnull, year, and follow relations with __ (category__name).

Complex filters and aggregation:

from django.db.models import Q, F, Count, Avg

Note.objects.filter(Q(title__icontains="tree") | Q(body__icontains="tree"))
Product.objects.update(price=F("price") * 1.1)          # in the database, no race
Category.objects.annotate(n=Count("notes")).order_by("-n")

Avoid N+1 queries:

Note.objects.select_related("author", "category")    # ForeignKey / OneToOne → SQL JOIN
Note.objects.prefetch_related("tags")                 # ManyToMany / reverse FK → 2nd query

QuerySets are lazy — no SQL runs until you iterate, slice, len(), list() or print them.

5. Templates

<!-- notes/templates/notes/base.html -->
<!doctype html>
<html>
<head><title>{% block title %}Codify{% endblock %}</title></head>
<body>
  <nav><a href="{% url 'notes:list' %}">Notes</a></nav>
  {% block content %}{% endblock %}
</body>
</html>
<!-- notes/templates/notes/list.html -->
{% extends "notes/base.html" %}
{% block title %}All notes{% endblock %}
{% block content %}
  <h1>Notes ({{ page_obj.paginator.count }})</h1>
  {% for note in note_list %}
    <article>
      <a href="{% url 'notes:detail' note.pk %}">{{ note.title }}</a>
      <small>{{ note.created_at|date:"d M Y" }} · {{ note.body|truncatewords:15 }}</small>
    </article>
  {% empty %}
    <p>No notes yet.</p>
  {% endfor %}
{% endblock %}
  • {{ variable }} prints (auto-escaped → safe from XSS), {% tag %} runs logic, |filter transforms (upper, date, default, length, linebreaks).
  • Static files: {% load static %} then <link href="{% static 'css/site.css' %}">.

6. Forms

# notes/forms.py
from django import forms
from .models import Note

class NoteForm(forms.ModelForm):
    class Meta:
        model = Note
        fields = ["title", "body", "category"]

    def clean_title(self):
        title = self.cleaned_data["title"].strip()
        if len(title) < 3:
            raise forms.ValidationError("Title must be at least 3 characters")
        return title
# notes/views.py
from django.contrib.auth.decorators import login_required

@login_required
def note_create(request):
    form = NoteForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        note = form.save(commit=False)
        note.author = request.user
        note.save()
        return redirect("notes:detail", pk=note.pk)
    return render(request, "notes/form.html", {"form": form})
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>

⚠️ Common error: 403 Forbidden — CSRF verification failed — the form is missing {% csrf_token %}.

7. Admin Panel & Authentication

python manage.py createsuperuser
# notes/admin.py
from django.contrib import admin
from .models import Note, Category

@admin.register(Note)
class NoteAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "category", "published", "created_at")
    list_filter = ("published", "category")
    search_fields = ("title", "body")

admin.site.register(Category)

Visit /admin/ — a full CRUD dashboard for your models with no extra code.

Authentication (built in):

# mysite/urls.py
path("accounts/", include("django.contrib.auth.urls")),   # login, logout, password reset views
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin

@login_required
def dashboard(request):
    return render(request, "dashboard.html", {"user": request.user})

class MyNotes(LoginRequiredMixin, ListView):
    def get_queryset(self):
        return Note.objects.filter(author=self.request.user)

Passwords are hashed with PBKDF2 by default (Argon2 available). For a custom user model, set AUTH_USER_MODEL before the first migration.

8. REST APIs with Django REST Framework

pip install djangorestframework
# notes/serializers.py
from rest_framework import serializers
from .models import Note

class NoteSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source="author.username")

    class Meta:
        model = Note
        fields = ["id", "title", "body", "author", "created_at"]
# notes/api.py
from rest_framework import viewsets, permissions

class NoteViewSet(viewsets.ModelViewSet):
    serializer_class = NoteSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        return Note.objects.select_related("author").filter(published=True)

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

# urls.py
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("api/notes", NoteViewSet, basename="note")
urlpatterns += router.urls          # GET/POST /api/notes/, GET/PUT/PATCH/DELETE /api/notes/<id>/

Add JWT with djangorestframework-simplejwt, CORS with django-cors-headers, filtering with django-filter.

9. Settings, Static Files & Deployment

Important settings:

import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DEBUG") == "1"           # never True in production
ALLOWED_HOSTS = ["codify.example", "localhost"]

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "codify", "USER": "app", "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": "localhost", "PORT": "5432",
    }
}
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

Production checklist:

python manage.py check --deploy       # security warnings
python manage.py collectstatic        # gather static files
pip install gunicorn whitenoise
gunicorn mysite.wsgi:application --bind 0.0.0.0:8000 --workers 3

Serve static files with WhiteNoise or Nginx; use PostgreSQL; set CSRF_TRUSTED_ORIGINS, SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE. Hosts: Render, Railway, PythonAnywhere, a VPS, or Docker.

10. Advanced Concepts

  • Request/response cycle: URL resolver → middleware → view → (model + template) → response → middleware.
  • Middleware: classes in MIDDLEWARE that process every request/response (security, sessions, CSRF, auth). Write your own for logging or timing.
  • Signals: post_save, pre_delete hooks (e.g. create a Profile when a User is created) — use sparingly.
  • Custom managers: objects = PublishedManager() to reuse filters.
  • Transactions: from django.db import transaction → with transaction.atomic(): ….
  • Caching: per-view @cache_page(60), low-level cache.get/set, Redis backend.
  • Async views (async def) and Django Channels for WebSockets.
  • Background tasks: Celery + Redis/RabbitMQ.
  • Testing: django.test.TestCase and the test client:
from django.test import TestCase
from django.urls import reverse

class NoteTests(TestCase):
    def test_list_page(self):
        res = self.client.get(reverse("notes:list"))
        self.assertEqual(res.status_code, 200)
  • Django vs Flask vs FastAPI: Django = full framework with everything included; Flask = minimal, pick your own tools; FastAPI = async APIs with type hints and automatic docs.

11. Examples with Output

Example 1 — Shell queries

python manage.py shell
>>> from notes.models import Category
>>> Category.objects.create(name="DSA")
<Category: DSA>
>>> Category.objects.count()
1

Example 2 — JSON view

def api_stats(request):
    return JsonResponse({"notes": Note.objects.count(), "status": "ok"})
{"notes": 12, "status": "ok"}

Example 3 — Migrations

python manage.py makemigrations notes
Migrations for 'notes':
  notes/migrations/0001_initial.py
    + Create model Category
    + Create model Note

12. Practice Problems

  1. Build a blog with Post and Comment models, list/detail pages and template inheritance.
  2. Register the models in the admin with search, filters and list columns.
  3. Add signup, login and logout; allow only the author to edit or delete a post.
  4. Add pagination (10 per page) and a search box using Q objects.
  5. Fix an N+1 problem on a list page using select_related and check the query count with Django Debug Toolbar.
  6. Build a REST API for posts with DRF ViewSets and token/JWT auth.
  7. Upload a profile picture with ImageField and show it on the profile page.
  8. Deploy the project with PostgreSQL, Gunicorn and WhiteNoise.

13. Interview Questions

1. What is MVT? Model (data and business rules), View (request handling logic), Template (presentation). Django's framework itself acts as the controller via the URL dispatcher.

2. Project vs app? A project is the whole site configuration; apps are self-contained modules that can be reused.

3. What are migrations? Version-controlled files describing schema changes, generated with makemigrations and applied with migrate.

4. select_related vs prefetch_related? select_related uses a SQL JOIN for foreign key/one-to-one; prefetch_related runs a separate query for many-to-many/reverse relations and joins in Python.

5. Are QuerySets lazy? Yes — the query runs only when the data is needed (iteration, slicing, len, list, bool).

6. How does Django prevent CSRF, XSS and SQL injection? CSRF tokens on forms, auto-escaping in templates, and parameterised queries in the ORM.

7. What is middleware? A layer that processes every request and response globally (sessions, auth, security headers).

8. get() vs filter()? get() returns one object or raises an exception; filter() returns a QuerySet (possibly empty).

9. What are signals? Hooks that run code when events happen (e.g. after a model is saved).

10. FBV vs CBV? Function-based views are explicit and simple; class-based views reuse behaviour through inheritance and mixins (ListView, CreateView).

14. Cheat Sheet & References

Commands

django-admin startproject mysite .
python manage.py startapp notes
python manage.py runserver
python manage.py makemigrations && python manage.py migrate
python manage.py createsuperuser
python manage.py shell
python manage.py collectstatic
python manage.py test

Models and queries

title = models.CharField(max_length=120)
author = models.ForeignKey(User, on_delete=models.CASCADE)
Note.objects.filter(title__icontains="x").order_by("-created_at")[:10]
Note.objects.get(pk=1)
Note.objects.select_related("author").prefetch_related("tags")
Category.objects.annotate(n=Count("notes"))

Views and URLs

path("<int:pk>/", views.detail, name="detail")
include("notes.urls")
get_object_or_404(Note, pk=pk)
render(request, "t.html", {"x": 1})
redirect("notes:list")
JsonResponse({"ok": True})

Templates

<!-- inheritance, loops, urls, filters -->
{% extends "base.html" %} {% block content %}{% endblock %}
{% for n in notes %}{{ n.title|upper }}{% empty %}None{% endfor %}
{% url 'notes:detail' n.pk %} {% load static %} {% static 'a.css' %}
{% csrf_token %}

Official documentation