Lesson 45 of 59Other frameworks
Django Essentials
Build with Django's batteries-included stack - projects and apps, models and migrations, querysets, the admin, URLs, views, templates and forms.
FastAPI gives you a fast, typed way to build an API, and you pick everything else yourself: the ORM, migrations, auth, an admin screen. Django makes the opposite bet. It ships all of those in one box, wired together, with one way to do each job. A huge number of companies run Django in production, so you will meet it in job listings, in codebases you inherit, and in interviews. This lesson gives you a working mental model of a Django project and the pieces you touch every day.
Batteries included
Django calls itself "the web framework for perfectionists with deadlines". In practice that means a new project already has:
- An ORM with models, relations and query building.
- Migrations generated from your models.
- An admin site: a full CRUD interface for your data, generated for free.
- Auth: users, groups, permissions, password hashing, login and logout views, sessions.
- Templates, forms with validation, CSRF protection, a test client and a development server.
The trade is flexibility for speed. You do things the Django way, and in return a small team can ship a content site, an internal tool or a marketplace back office in days. Swapping out a core piece (say, using SQLAlchemy instead of the Django ORM) is possible but fights the framework, so almost nobody does it.
Projects and apps
Two words cause confusion on day one. A project is the whole site: settings, the root URL list, and the entry points for servers. An app is a Python package for one feature area (blog, billing, accounts) with its own models, views and admin. A project contains many apps, and an app can in principle be reused in another project.
uv init mysite && cd mysiteuv add djangouv run django-admin startproject config .uv run python manage.py startapp bloguv run python manage.py runserverThe config . trick puts the settings package in a folder named config and manage.py in the current directory, which keeps the layout flat. manage.py is your command line for the project: run the server, make migrations, open a shell, create a superuser.
- mysite/
- manage.pyrun any project command
- pyproject.toml
- config/
- settings.pyINSTALLED_APPS, DATABASES, ...
- urls.pyroot URL list
- asgi.pyentry point for ASGI servers
- wsgi.pyentry point for WSGI servers
- blog/
- models.pytables as classes
- views.pyrequest handlers
- admin.pyregister models in the admin
- apps.py
- migrations/generated schema changes
- templates/
- blog/
- post_list.html
A new app does nothing until you add it to INSTALLED_APPS in config/settings.py. Forgetting this is the classic "why are my migrations empty" bug.
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"blog",
]settings.py is a plain Python module, which is both handy and dangerous: it is easy to hardcode a secret in it and commit it. A handful of settings matter most:
| Setting | What it controls |
|---|---|
SECRET_KEY | Signs sessions, password reset links and CSRF tokens. Load it from the environment. |
DEBUG | Detailed error pages. True locally, always False in production. |
ALLOWED_HOSTS | Which host names the site answers to. Required when DEBUG is off. |
DATABASES | Engine, name, user, password, host. SQLite by default, usually Postgres in production. |
INSTALLED_APPS | Which apps Django loads models, admin and migrations from. |
MIDDLEWARE | The ordered chain every request passes through. |
Real projects read secrets and the database URL from environment variables, often with a small helper package such as django-environ, or split settings into a base module plus per-environment overrides. Run python manage.py check --deploy before going live: it lists insecure settings such as DEBUG = True or missing HTTPS options.
Models and migrations
A model is a class that maps to a table. Each attribute is a field, and Django adds an id primary key for you.
from django.conf import settings
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
body = models.TextField()
published = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="posts",
)
class Meta:
ordering = ["-created_at"]
def __str__(self) -> str:
return self.titleChanging models is a two-step loop. makemigrations compares your models with the existing migration files and writes a new migration. migrate applies pending migrations to the database.
uv run python manage.py makemigrations bloguv run python manage.py migrateMigration files are code. Commit them, review them in pull requests, and never edit one that has already run in production; write a new one instead.
Order the steps to add a published field to an existing model and see it in the database.
- Tap the steps below in the right order.
Querysets
Each model gets a manager, Post.objects, that returns querysets. A queryset describes a query. It is lazy: building and chaining one runs no SQL. The database is hit only when you need results, for example when you loop over it, slice it, call list() or len(), or print it.
from blog.models import Post
drafts = Post.objects.filter(published=False) # no query yet
mine = drafts.filter(author__username="ada").order_by("title")
print(mine.count()) # SELECT COUNT(*) ...
for post in mine: # SELECT ... runs here
print(post.title)
post = Post.objects.get(slug="hello") # exactly one row, or an exception
Post.objects.filter(published=False).update(published=True)
Post.objects.exclude(body="").exists()The double underscore follows relations and adds lookups: author__username="ada" joins to the user table, and title__icontains="django" does a case-insensitive search. get() raises Post.DoesNotExist if nothing matches and MultipleObjectsReturned if more than one does.
Here is a toy version of that laziness in plain Python. Each filter returns a new object holding one more condition, and nothing runs until you iterate.
Press Run (⌘ Enter) to see what happens.The real one turns conditions into SQL instead of a Python loop, and caches results after the first evaluation.
In a Django shell, how many SQL queries run for these three lines?
qs = Post.objects.filter(published=True)
qs = qs.exclude(title="")
qs = qs.order_by("-created_at")Laziness has a cost you must know about. Looping over posts and reading post.author.username runs one extra query per post: the N+1 problem. Fix it with select_related("author") for foreign keys (a join) and prefetch_related("tags") for many-to-many or reverse relations (a second query).
The admin
Register a model and you get list, search, filter, create, edit and delete screens, with permissions, for free.
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "author", "published", "created_at"]
list_filter = ["published"]
search_fields = ["title", "body"]
prepopulated_fields = {"slug": ["title"]}Run python manage.py createsuperuser, open /admin/, and staff can manage content on day one. The admin is an internal tool, not a customer-facing UI. Teams pick Django for it often, because building the same screens by hand on FastAPI takes weeks.
URLs, views and templates
A request travels through a fixed path. The root urls.py matches the path, hands off to an app's urls.py, which calls a view. The view uses models to load data and renders a template to HTML.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("blog/", include("blog.urls")),
]from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.post_list, name="post_list"),
path("<slug:slug>/", views.post_detail, name="post_detail"),
]from django.shortcuts import get_object_or_404, render
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True).select_related("author")
return render(request, "blog/post_list.html", {"posts": posts})
def post_detail(request, slug: str):
post = get_object_or_404(Post, slug=slug, published=True)
return render(request, "blog/post_detail.html", {"post": post})<h1>Posts</h1>
<ul>
{% for post in posts %}
<li><a href="{% url 'blog:post_detail' post.slug %}">{{ post.title }}</a> by {{ post.author.username }}</li>
{% empty %}
<li>No posts yet.</li>
{% endfor %}
</ul>Templates escape variables by default, so a title containing <script> shows up as text, not code. {% url %} builds links from route names, so renaming a path does not break every link.
Django also has class-based views such as ListView and DetailView that do the above in a few lines. They save code once you know them, but function views are easier to read when you start.
Every request passes through middleware first. It loads the session, attaches request.user and checks CSRF tokens on form posts.
Match each file to its job in a Django app.
Forms
A form validates input and renders HTML fields. A ModelForm builds the fields from a model, so validation rules live in one place.
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "slug", "body"]from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from .forms import PostForm
@login_required
def post_create(request):
form = PostForm(request.POST or None)
if request.method == "POST" and form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect("blog:post_detail", slug=post.slug)
return render(request, "blog/post_form.html", {"form": form})is_valid() fills form.errors with messages to show next to each field, and form.cleaned_data with converted values. It plays the same role Pydantic plays in FastAPI. Every HTML form that posts must include {% csrf_token %}, or the CSRF middleware rejects it with a 403.
403 Forbidden with a CSRF error. What is the most likely fix?When Django is the right choice
Pick Django when the product is mostly data plus people managing it: content sites, marketplaces, SaaS dashboards, internal tools, anything where the admin alone saves weeks. Its conventions also help larger teams, since every Django project looks alike. Django supports async views and an ASGI entry point, but most of the ecosystem and the ORM's typical usage are still synchronous, so for a small, high-concurrency JSON API, FastAPI is often the lighter fit.
- project
- The whole Django site: settings, the root URLconf and the ASGI/WSGI entry points.
- app
- A package for one feature area with its own models, views, admin and migrations.
- model
- A class that maps to a database table; each field is a column.
- queryset
- A lazy, chainable description of a database query that runs when evaluated.
- migration
- A generated, committed file describing a schema change, applied with
migrate. - Django admin
- An automatic staff interface for creating, editing and searching registered models.
- ModelForm
- A form whose fields and validation are built from a model.