Browse Python Topics โ–ผ
Pick a Web Framework

Django

๐Ÿ“‚ Pick a Web Framework ๐Ÿ“˜ Lesson 53 of 57

Build full-featured, secure web applications and backends using Django's batteries-included MVT architecture, ORM, and admin dashboard.

Think of web frameworks as choices for furnishing a home. A microframework like flask gives you four bare concrete walls: you have complete freedom, but you must build your own kitchen cabinets, buy your own locks, and wire your own electrical sockets.

Django is the opposite philosophy: it is a fully furnished luxury penthouse. From the moment you turn the key, you have built-in authentication, a rock-solid security shield against web attacks, a database manager (databases), database migration tooling, and even an administrative control panel. This design philosophy is famously called โ€œbatteries included.โ€

Django powers massive, data-driven platforms like Instagram, Pinterest, and the Washington Post because it enforces clean organization and takes care of tedious boilerplate.


The MVT Architecture (Model - View - Template)

Traditional web development often talks about MVC (Model-View-Controller). Django uses a slightly renamed variation called MVT (Model-View-Template):

       Incoming HTTP Request
                 โ”‚
                 โ–ผ
             urls.py (URL Router)
                 โ”‚
                 โ–ผ
             views.py (The View / Chef)
             โ”Œโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
             โ–ผ                     โ–ผ
    models.py (The Model)   templates/ (The Template)
    (Fetches data from DB)  (Formats HTML structure)
             โ”‚                     โ”‚
             โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         โ–ผ
               HTTP Response (HTML/JSON)
  1. The Model (models.py): Defines your data schema in pure Python. Django translates these Python classes into SQL database tables.
  2. The View (views.py): The brain of your page. It receives the HTTP request, asks the Model for whatever data is needed, applies your business rules, and decides what to send back.
  3. The Template (templates/): The presentation skin. An HTML file enriched with Django Template Language ({{ variable }}) to insert dynamic data into the final page.

Starting a Django Project

Django comes with CLI tools to scaffold a clean project structure:

# Install Django
pip install django

# Create the top-level project wrapper
django-admin startproject mywebsite .

# Create a modular application inside your project
python manage.py startapp blog

Django projects are composed of small, modular โ€œappsโ€ (e.g., blog, accounts, store).

[!IMPORTANT] Whenever you create an app with startapp, you must add it to INSTALLED_APPS inside mywebsite/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    # ...
    'blog',  # Your new app
]

If you forget this step, Django will not recognize your models, migrations, or templates!


Defining Models and Running Migrations

Instead of writing raw SQL CREATE TABLE statements, you define Python classes that inherit from models.Model:

# blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    body = models.TextField()
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self) -> str:
        # What shows up in the admin dashboard and debug shells
        return self.title

The Two-Step Migration Process

When you change a model, you update the database using two commands:

# Step 1: Detect changes and create a blueprint script in blog/migrations/
python manage.py makemigrations

# Step 2: Apply the blueprint script directly to your database
python manage.py migrate
  • makemigrations: Creates a version-controlled Python file recording what changed (like a git commit for your database schema).
  • migrate: Runs the generated SQL against your SQLite, PostgreSQL, or MySQL database to update the tables.

Querying Data with the Django ORM

Django includes an Object-Relational Mapper (ORM). You read and write database rows without writing a single line of SQL:

from blog.models import Post

# 1. CREATE: Insert a new row
post = Post.objects.create(
    title="My First Django Post",
    slug="first-post",
    body="Learning the MVT pattern is fun!",
    is_published=True
)

# 2. READ: Fetch records
all_posts = Post.objects.all()

# Filtering records (uses double-underscore lookups)
published_posts = Post.objects.filter(is_published=True)
recent_posts = Post.objects.filter(title__icontains="django")

# Fetching a single record (raises Post.DoesNotExist if not found)
try:
    single_post = Post.objects.get(slug="first-post")
    print("Found post:", single_post.title)
except Post.DoesNotExist:
    print("Post not found!")

# 3. UPDATE: Modify and save
single_post.title = "Updated Title"
single_post.save()

# 4. DELETE: Remove from database
# single_post.delete()

QuerySets Are Lazy

Django QuerySet objects are lazy: they do not hit the database until you evaluate them (e.g., looping through them with for post in posts:, indexing them, or checking len()). This makes query chaining extremely fast and efficient:

# No database query has occurred yet!
query = Post.objects.filter(is_published=True).order_by("-created_at")

# Still no query! Just modifying the query plan
query = query.filter(title__icontains="python")

# The database is queried ONLY right here:
for item in query:
    print(item.title)

URL Routing and Views

To display data in a web browser, connect a URL pattern to a view function:

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

urlpatterns = [
    path("", views.post_list, name="post-list"),
    path("<slug:slug>/", views.post_detail, name="post-detail"),
]

Now write the view functions to handle incoming HTTP requests:

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

def post_list(request):
    posts = Post.objects.filter(is_published=True).order_by("-created_at")
    # render() takes request, template path, and data context dictionary
    return render(request, "blog/post_list.html", {"posts": posts})

def post_detail(request, slug):
    # Automatically raises a 404 page if no post matches the slug
    post = get_object_or_404(Post, slug=slug, is_published=True)
    return render(request, "blog/post_detail.html", {"post": post})

And in your template (templates/blog/post_list.html):

<!DOCTYPE html>
<html>
<head><title>Engineering Blog</title></head>
<body>
  <h1>Recent Articles</h1>
  <ul>
    {% for post in posts %}
      <li><a href="/{{ post.slug }}/">{{ post.title }}</a></li>
    {% empty %}
      <li>No articles published yet.</li>
    {% endfor %}
  </ul>
</body>
</html>

The Built-in Admin Interface

One of Djangoโ€™s killer features is its automatic administrative dashboard. Register your model in blog/admin.py:

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

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ("title", "is_published", "created_at")
    list_filter = ("is_published", "created_at")
    search_fields = ("title", "body")
    prepopulated_fields = {"slug": ("title",)}

Create an admin user in your terminal:

python manage.py createsuperuser

Run your development server with python manage.py runserver, navigate to http://127.0.0.1:8000/admin/, and you have a fully working, secure back-office dashboard to search, edit, create, and delete posts without writing any frontend code.


Common Beginner Traps

1. Forgetting to Register in INSTALLED_APPS

If you define models in a new app and run python manage.py makemigrations, Django might say No changes detected. Nine times out of ten, you forgot to list your app name in INSTALLED_APPS in settings.py.

2. The N+1 Query Problem with Foreign Keys

If an Article has an Author foreign key, running:

for article in Article.objects.all():
    print(article.author.name)  # Hits the DB once per article!

If you have 1,000 articles, this runs 1,001 database queries. Always use select_related() for single relations or prefetch_related() for many-to-many relations:

for article in Article.objects.select_related("author").all():
    print(article.author.name)  # Hits the DB exactly ONCE using an SQL JOIN

3. Modifying Models Without Running makemigrations and migrate

Python will compile fine, but the moment you query or save the model, your database driver will crash with OperationalError: no such column. Always run both commands after changing any field.


Choosing Between Python Web Frameworks

FeatureDjangoFlaskFastAPI
PhilosophyFull-stack monolithMinimalist microframeworkAsync API microframework
Primary StrengthAdmin dashboard, ORM, AuthTotal design freedomBlazing speed, type safety
Default DatabaseBuilt-in Django ORMNone (add SQLAlchemy)None (add SQLAlchemy / SQLModel)
Admin UIBuilt-in out of the boxNone (add Flask-Admin)None
Automatic DocsNo (manual)No (manual)Yes (Interactive Swagger UI)
Best ForContent sites, SaaS, internal toolsSmall services, quick prototypesREST APIs, microservices, AI backends

Test your understanding of Django

Quick interactive practice questions with instant feedback.

Take Quiz โ†’