πΈ Django Web Framework
in Python
Learn Django step by step: project layout, settings, models and the ORM, migrations, views, URLs, templates, admin, forms, auth and a small blog walk-through.
What this lesson is about
Django is a full-stack web framework for Python. It gives you, in one package, an object-relational mapper for talking to a database, a URL router, a template engine, forms and validation, user authentication, and a ready-made admin interface for managing your data. Its motto of being the framework for perfectionists with deadlines is a fair summary: it makes the common parts of a database-backed website quick to build and consistent to maintain.
You will meet Django wherever a team needs a content site, a dashboard, an internal tool or the back end of an app with accounts and a database. Compared with Flask, which hands you a small core and lets you choose the rest, Django is the batteries-included option, and compared with FastAPI, which focuses on typed JSON APIs, Django is strongest when you want pages, forms and an admin as well. None of them is better in every case; knowing Django widens your options.
A practical note first: Django cannot run inside a browser tab, so the real framework code on this page is shown as static blocks that you run on your own computer after installing it in a virtual environment. To make the ideas runnable here, I have also written small teaching versions that do run in your browser: a tiny ORM on top of sqlite3, a URL resolver built with regular expressions, and field validators. They are not Django, but they show you what Django is doing for you, and I mark each clearly.
What you will learn
- βUnderstand the Django project and app layout and what
manage.pydoes - βRead and edit
settings.py: installed apps, database, templates, static files - βDefine models and query them through the ORM
- βCreate and apply migrations, and know why they exist
- βWrite views, map URLs to them and render templates
- βRegister models in the admin and customise the admin list
- βBuild forms and validate user input with
ModelForm - βAdd login and permission checks, and tie it all together in a small blog
Why programmers should learn this
- β Django is widely used for production websites, so knowing it makes you useful on teams that already run Django projects.
- β Its built-in admin lets you manage data on day one, which is perfect for prototypes, internal tools and content sites.
- β Security features such as CSRF protection, SQL-injection-safe queries, password hashing and template auto-escaping are on by default, so beginners get safe behaviour without extra work.
- β Learning the ORM, migrations and request-response cycle teaches ideas that transfer to every other web framework and to databases in general (see also SQLite databases).
- β A consistent project structure means you can open a stranger's Django project and quickly find the models, views and templates.
Project and app layout
Django separates a project from its apps. The project is the whole website: its settings, its root URL configuration and its deployment entry points. An app is a self-contained feature, such as blog or accounts, with its own models, views and templates. One project normally contains several apps, and a well-made app can be reused in another project.
You create both with the django-admin and manage.py commands. After startproject you get a folder holding manage.py (a small script that runs management commands for this project) and an inner package with settings.py, urls.py and the ASGI and WSGI files that web servers use. After startapp blog you get a blog folder with models.py, views.py, admin.py, apps.py, a migrations folder and a tests.py.
Creating an app does not activate it. You must add it to INSTALLED_APPS in settings, otherwise Django will ignore its models and templates. That single forgotten line is the most common beginner stumble. The commands below are for a terminal on your computer; the layout block that follows is only a picture of what you will see.
python -m venv .venv source .venv/bin/activate python -m pip install django django-admin startproject mysite cd mysite python manage.py startapp blog python manage.py runserver
Line by line
- 1-2Create and activate a virtual environment (on Windows the activate script is in
.venv\Scripts). - 3Install Django into that environment.
- 4-5Create the project called
mysiteand move into it. - 6Create an app named
blognext tomanage.py. - 7Start the development server, normally at
http://127.0.0.1:8000/. It is for development only, never for production.
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
blog/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
__init__.pyLine by line
- 1-2The outer folder and
manage.py, the command-line entry point. - 3-8The project package: settings, the root URL list and the server entry points.
- 9-16The app: models for data, views for logic, admin for the admin site, and migrations for database changes.
Settings: the project's control panel
settings.py is an ordinary Python module full of upper-case names. The ones you will touch first are INSTALLED_APPS (which apps are active), DATABASES (where data lives; new projects default to a SQLite file, which is perfect for learning), TEMPLATES (where HTML templates are found), STATIC_URL for CSS and images, and DEBUG, which shows detailed error pages while you develop.
Treat settings with care. DEBUG = True must never be used on a public site, because error pages reveal code and configuration. The SECRET_KEY signs sessions and tokens and must be kept out of public repositories; production projects usually read it, and database passwords, from environment variables. ALLOWED_HOSTS lists the hostnames the site may serve when debug is off. Django's own deployment checklist (python manage.py check --deploy) points out missing security settings.
Because settings are just Python, reading environment variables is easy with os.environ. Many teams split settings into a base file plus development and production variants. For a first project, one file is fine; the important thing is to know which values are secrets and keep them out of version control.
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-only-not-secret")
DEBUG = os.environ.get("DJANGO_DEBUG", "1") == "1"
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"blog",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
STATIC_URL = "static/"
LOGIN_REDIRECT_URL = "/"Line by line
- 1-4
BASE_DIRis the project's root folder, computed withpathlibso paths work on any system. - 6-8Secret key and debug flag come from environment variables, with safe development defaults; real secrets never go in the repository.
- 10-18Apps that are switched on: Django's own contrib apps and our
blogapp. Forgettingbloghere is a classic mistake. - 20-25One SQLite database file; to use PostgreSQL you would change the engine and add connection details.
- 27-40Where templates are found: a project-level
templatesfolder plus atemplatesfolder inside each installed app. - 42-43Prefix for static files and where to go after login.
Models and the ORM
A model is a Python class that describes one database table. Each attribute is a field (CharField, TextField, DateTimeField, ForeignKey and so on) and becomes a column. The ORM (object-relational mapper) lets you create, query, update and delete rows by working with those classes instead of writing SQL strings. Behind the scenes it generates SQL, escapes values to prevent injection, and returns model instances.
The most important idea is the QuerySet. Post.objects.filter(published=True).order_by('-created') does not hit the database when you write it; it builds a lazy query that runs when you iterate over it, slice it or call something like .count(). QuerySets chain, so you can refine them step by step. Relationships are expressed with fields: a ForeignKey from Comment to Post gives you comment.post going forward and post.comment_set (or a name you choose with related_name) going back.
The real model code below is static, because it needs Django. Right after it I show a mini-ORM written with plain sqlite3 that runs in your browser. It is about forty lines and has no relation to Django's internals, but it demonstrates the central trick: a class that knows its table, turns attributes into SQL with placeholders, and turns rows back into objects.
from django.conf import settings
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts"
)
body = models.TextField()
published = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog:detail", kwargs={"slug": self.slug})Line by line
- 1-3Import the settings object, Django's models module and the
reversehelper that builds URLs from names. - 6-14Fields: a title, a unique URL slug, the author (a foreign key to the user model, deleting a user deletes their posts), body text, a published flag and an automatic creation time.
- 16-17
Meta.orderingmakes newest posts come first by default. - 19-20
__str__controls how a post is shown in the admin and the shell. - 22-23
get_absolute_urlreturns the post's page URL by using the URL nameblog:detail, so the URL is defined only once.
from blog.models import Post
from django.contrib.auth import get_user_model
user = get_user_model().objects.first()
post = Post.objects.create(title="Hello", slug="hello", author=user, body="First!")
Post.objects.filter(published=True).count()
Post.objects.filter(title__icontains="hell").first()
Post.objects.exclude(author=user).order_by("-created")[:5]
post.published = True
post.save()
post.delete()Line by line
- 4-5Fetch a user, then create and save a post in one call.
- 7-9Filter with lookups:
title__icontainsmeans a case-insensitive contains. QuerySets are lazy, so slicing[:5]becomes a SQLLIMIT. - 11-13Change an attribute and
save()to update the row;delete()removes it.
import sqlite3
class Model:
"""A tiny teaching ORM (not Django): classes map to tables."""
table = ""
fields = ()
conn = None
def __init__(self, **values):
self.id = values.pop("id", None)
for name in self.fields:
setattr(self, name, values.get(name))
@classmethod
def create_table(cls):
cols = ", ".join(f"{name} TEXT" for name in cls.fields)
cls.conn.execute(
f"CREATE TABLE IF NOT EXISTS {cls.table} (id INTEGER PRIMARY KEY, {cols})"
)
def save(self):
values = [getattr(self, name) for name in self.fields]
marks = ", ".join("?" for _ in self.fields)
cur = self.conn.execute(
f"INSERT INTO {self.table} ({', '.join(self.fields)}) VALUES ({marks})", values
)
self.id = cur.lastrowid
return self
@classmethod
def filter(cls, **where):
clause = " AND ".join(f"{k} = ?" for k in where) or "1 = 1"
rows = cls.conn.execute(
f"SELECT id, {', '.join(cls.fields)} FROM {cls.table} WHERE {clause} ORDER BY id",
list(where.values()),
).fetchall()
return [cls(id=r[0], **dict(zip(cls.fields, r[1:]))) for r in rows]
def __repr__(self):
shown = ", ".join(f"{n}={getattr(self, n)!r}" for n in self.fields)
return f"{type(self).__name__}(id={self.id}, {shown})"
class Post(Model):
table = "post"
fields = ("title", "status")
Model.conn = sqlite3.connect(":memory:")
Post.create_table()
Post(title="Hello", status="draft").save()
Post(title="Django ORM", status="published").save()
Post(title="Migrations", status="published").save()
print(Post.filter(status="published"))
print(Post.filter(title="Hello"))
print(len(Post.filter()))[Post(id=2, title='Django ORM', status='published'), Post(id=3, title='Migrations', status='published')] [Post(id=1, title='Hello', status='draft')] 3
Line by line
- 3-8A base class holds the table name, the field names and the shared database connection.
- 10-13The constructor copies keyword arguments onto the object, the way a model instance holds its field values.
- 15-20
create_tablebuilds aCREATE TABLEstatement from the field names. - 22-29
saveinserts a row using?placeholders, so values are never pasted into the SQL (this is how real ORMs avoid SQL injection), and remembers the new id. - 31-38
filterbuilds aWHEREclause from keyword arguments and turns each returned row back into an object. - 40-42A readable
reprso the printed results are easy to understand. - 45-47A concrete model is just a subclass that names its table and fields.
- 50-55Connect to an in-memory database, create the table, insert three rows.
- 57-59Query by status, by title and with no conditions to count everything.
Real Django does much more: field types, lazy QuerySets, joins, transactions and many database backends. The mini-ORM only shows the core idea of mapping classes to rows.
Migrations: versioning your database
When you change a model, the database table must change too. Migrations are Django's answer: each migration is a small Python file that records a step, such as creating a table or adding a column. makemigrations compares your models with the recorded history and writes a new migration file; migrate applies unapplied migrations to the actual database and records which ones have run.
Migrations live in the app's migrations folder and belong in version control. That way a teammate, or your production server, can run migrate and arrive at exactly the same database structure. Never edit an applied migration casually and never delete migration files on a shared project; instead, create a new migration that makes the next change.
Two practical tips. Run makemigrations and read the output before applying it, since it tells you what Django thinks changed. And be careful adding a non-nullable field to a table that already has rows: Django will ask for a default value, because it has to fill the existing records. You can inspect the SQL a migration will run with sqlmigrate.
python manage.py makemigrations blog python manage.py sqlmigrate blog 0001 python manage.py migrate python manage.py showmigrations python manage.py createsuperuser
Line by line
- 1Write a migration file for changes to the
blogmodels (for exampleblog/migrations/0001_initial.py). - 2Print the SQL that migration
0001would run, without running it. Useful for learning and for review. - 3Apply all pending migrations (including Django's own apps) to the database.
- 4List migrations and mark which have been applied.
- 5Create an administrator account for the admin site, which we use soon.
import sqlite3
# Teaching version of what migrations do: an ordered history plus a record of what ran.
MIGRATIONS = [
("0001_create_post", "CREATE TABLE post (id INTEGER PRIMARY KEY, title TEXT NOT NULL)"),
("0002_add_published", "ALTER TABLE post ADD COLUMN published INTEGER NOT NULL DEFAULT 0"),
("0003_add_slug", "ALTER TABLE post ADD COLUMN slug TEXT NOT NULL DEFAULT ''"),
]
def migrate(conn):
conn.execute("CREATE TABLE IF NOT EXISTS applied (name TEXT PRIMARY KEY)")
done = {row[0] for row in conn.execute("SELECT name FROM applied")}
for name, sql in MIGRATIONS:
if name in done:
print("skip ", name)
continue
conn.execute(sql)
conn.execute("INSERT INTO applied VALUES (?)", (name,))
print("applied", name)
conn = sqlite3.connect(":memory:")
migrate(conn)
print("--- run again ---")
migrate(conn)
print([row[1] for row in conn.execute("PRAGMA table_info(post)")])applied 0001_create_post applied 0002_add_published applied 0003_add_slug --- run again --- skip 0001_create_post skip 0002_add_published skip 0003_add_slug ['id', 'title', 'published', 'slug']
Line by line
- 4-8An ordered list of named steps, like the numbered files in a
migrationsfolder. - 10-12A bookkeeping table remembers which migrations have run; Django uses a table called
django_migrationsfor this. - 13-19Apply each step that is not yet recorded, and record it. Steps already applied are skipped.
- 22-25Running twice shows that the second run changes nothing, which is why
migrateis safe to repeat. - 26
PRAGMA table_infolists the columns, proving that the later migrations added theirs.
URLs and views: from request to response
When a browser asks for a page, Django walks through the URL configuration top to bottom looking for a pattern that matches the path. The first match decides which view runs. A view is simply a function (or a class) that takes a request and returns a response. Project-level urls.py usually delegates to each app with include(), so every app owns its own URL list.
Patterns can capture parts of the path with converters such as <int:pk> or <slug:slug>, and the captured values arrive as keyword arguments in your view. Give every route a name, and use that name in templates ({% url 'blog:detail' post.slug %}) and in Python (reverse(...)) instead of hard-coding paths. Then you can reorganise URLs later without breaking links.
To see what the router does, the runnable example below implements a miniature resolver with the re module: it turns <int:pk> style patterns into regular expressions, finds the first match and calls the matching function with the captured values. Real Django is more sophisticated, but this is the heart of it.
# blog/views.py
from django.shortcuts import get_object_or_404, render
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True)
return render(request, "blog/post_list.html", {"posts": posts})
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug, published=True)
return render(request, "blog/post_detail.html", {"post": post})
# blog/urls.py
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.post_list, name="list"),
path("<slug:slug>/", views.post_detail, name="detail"),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("blog/", include("blog.urls")),
]Line by line
- 2-4Import the shortcut helpers and the model.
- 7-9The list view fetches published posts and renders a template, passing the posts in a context dictionary.
- 12-14The detail view receives the
slugcaptured from the URL;get_object_or_404returns the post or raises an HTTP 404 page. - 18-26The app's URL list;
app_namecreates theblog:namespace used byreverseand{% url %}. - 29-35The project's root URLs hand everything under
blog/to the app and mount the admin atadmin/.
import re
def compile_route(pattern):
"""Turn '<int:pk>' style patterns into a regex (teaching version)."""
converters = {"int": r"[0-9]+", "slug": r"[-a-zA-Z0-9_]+", "str": r"[^/]+"}
def repl(match):
kind, name = match.group(1), match.group(2)
return f"(?P<{name}>{converters[kind]})"
regex = re.sub(r"<(\w+):(\w+)>", repl, pattern)
return re.compile("^" + regex + "$")
def post_list():
return "list of posts"
def post_detail(slug):
return f"post page for {slug}"
def user_page(pk):
return f"user number {int(pk) * 1} profile"
ROUTES = [
(compile_route("blog/"), post_list),
(compile_route("blog/<slug:slug>/"), post_detail),
(compile_route("users/<int:pk>/"), user_page),
]
def resolve(path):
for regex, view in ROUTES:
match = regex.match(path)
if match:
return view(**match.groupdict())
return "404 not found"
for path in ["blog/", "blog/hello-django/", "users/42/", "users/abc/", "contact/"]:
print(f"{path:22} -> {resolve(path)}")blog/ -> list of posts blog/hello-django/ -> post page for hello-django users/42/ -> user number 42 profile users/abc/ -> 404 not found contact/ -> 404 not found
Line by line
- 3-10Convert each
<converter:name>piece into a named regular-expression group, then anchor the whole pattern. - 12-19Three plain view functions that receive captured values as keyword arguments.
- 21-25The route table, like
urlpatterns: first match wins, so order matters. - 27-32
resolvetries each route in order and calls the first matching view; no match means a 404. - 34-35Try five paths.
users/abc/fails becauseabcis not digits, so the int converter does not match.
Templates: turning data into HTML
A Django template is an HTML file with a few extra tags. Double braces print a value ({{ post.title }}), and {% ... %} tags control logic such as for, if, url and extends. Templates deliberately have limited logic: calculations and database queries belong in views and models, so the template stays about presentation.
Template inheritance removes repeated HTML. A base template defines the page frame (head, navigation, footer) and marks replaceable blocks; child templates say {% extends %} and fill in only their blocks. Django auto-escapes variables by default, turning <script> into harmless text, which protects you from cross-site scripting unless you deliberately mark something safe.
Because templates need Django's engine, the blocks below are static. Whenever a form is posted, include {% csrf_token %} inside the form, or Django will reject the request. For static files such as CSS use {% load static %} and {% static 'css/site.css' %}.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}My Blog{% endblock %}</title>
</head>
<body>
<nav><a href="{% url 'blog:list' %}">Home</a></nav>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>Line by line
- 5A
blockwith default text that child pages may override. - 8
{% url %}builds the link from the route's name, so it never goes stale. - 9-11The main block where each page puts its own content.
{% extends "base.html" %}
{% block title %}All posts{% endblock %}
{% block content %}
<h1>Posts</h1>
{% for post in posts %}
<article>
<h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
<p>{{ post.body|truncatewords:30 }}</p>
</article>
{% empty %}
<p>No posts yet.</p>
{% endfor %}
{% endblock %}Line by line
- 1Inherit the page frame from
base.html. - 3Override the title block.
- 7-12Loop over the posts passed in by the view;
{{ }}output is HTML-escaped automatically andtruncatewordsis a filter. - 13-14
{% empty %}runs when the list has no items.
The admin site
One of Django's most loved features is the admin: after you register a model, you get a secure web interface for creating, searching, editing and deleting records, with forms generated from your fields. It is meant for trusted staff, not for the public, but for small projects it replaces weeks of building back-office screens.
You register models in admin.py. A ModelAdmin class lets you customise the list: which columns to show (list_display), which filters to offer in the sidebar (list_filter), what can be searched (search_fields) and how the slug is auto-filled (prepopulated_fields). Run createsuperuser once and log in at /admin/.
Treat the admin like any powerful tool: use strong passwords, give staff only the permissions they need, and do not expose it on a guessable address if you can avoid it. Permissions in Django are per model (add, change, delete, view), and groups let you hand them out in bundles.
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ("title", "author", "published", "created")
list_filter = ("published", "created")
search_fields = ("title", "body")
prepopulated_fields = {"slug": ("title",)}Line by line
- 6-7The
registerdecorator attaches this admin configuration to thePostmodel. - 8Columns shown in the list page.
- 9Sidebar filters, handy for the published flag and dates.
- 10A search box that looks in the listed fields.
- 11While typing a title, the slug field fills itself in using JavaScript.
Forms and validation
Whenever users send data, you must validate it: check types, lengths, uniqueness and anything your rules require. Django's forms do this declaratively. A ModelForm builds a form from a model, renders the HTML fields, and on submission cleans the data, runs validators and reports errors in a consistent way. You call form.is_valid(), and if it is true, form.save().
The standard view pattern handles both display and submission: on GET show an empty form; on POST bind the submitted data, validate and either redirect (the post/redirect/get pattern, which stops double submissions) or redisplay the form with its errors. Custom validation goes in field validators or in clean_<fieldname> methods that raise ValidationError.
A validator is just a callable that raises an error for bad input, so the idea can be shown without Django. The runnable example below defines a small ValidationError, several reusable validators and a function that runs them all and collects every error message, which is what Django's forms do for each field.
# blog/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "slug", "body", "published"]
def clean_title(self):
title = self.cleaned_data["title"].strip()
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters.")
return title
# blog/views.py (addition)
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
@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)
else:
form = PostForm()
return render(request, "blog/post_form.html", {"form": form})Line by line
- 6-10A form generated from the
Postmodel, limited to four editable fields (the author is set in the view, not by the user). - 12-16A field-specific cleaning hook: trim the title and reject very short ones with a
ValidationError. - 23-24
login_requiredredirects anonymous visitors to the login page. - 25-28On POST, bind submitted data and check validity.
- 29-32
commit=Falsegives an unsaved object so the view can set the author before saving; then redirect to the new post (redirectusesget_absolute_url). - 33-35On GET, show an empty form; if validation failed, the bound form is redisplayed with errors.
class ValidationError(Exception):
pass
def min_length(n):
def check(value):
if len(value) < n:
raise ValidationError(f"must be at least {n} characters")
return check
def max_length(n):
def check(value):
if len(value) > n:
raise ValidationError(f"must be at most {n} characters")
return check
def slug_chars(value):
if not value or not all(c.islower() or c.isdigit() or c == "-" for c in value):
raise ValidationError("use lowercase letters, digits and hyphens only")
FIELDS = {
"title": [min_length(5), max_length(20)],
"slug": [slug_chars],
}
def validate(data):
errors = {}
for field, validators in FIELDS.items():
value = data.get(field, "")
for check in validators:
try:
check(value)
except ValidationError as exc:
errors.setdefault(field, []).append(str(exc))
return errors
print(validate({"title": "Hello Django", "slug": "hello-django"}))
print(validate({"title": "Hi", "slug": "Bad Slug!"}))
print(validate({"title": "x" * 30})){}
{'title': ['must be at least 5 characters'], 'slug': ['use lowercase letters, digits and hyphens only']}
{'title': ['must be at most 20 characters'], 'slug': ['use lowercase letters, digits and hyphens only']}Line by line
- 1-2A custom exception plays the role of Django's
ValidationError. - 4-14Validator factories return a checking function; this is the same shape as Django's
MinLengthValidatorand friends. - 16-18A plain validator for slug characters.
- 20-23A table of fields and the validators each must pass, like a form's field list.
- 25-34Run every validator for every field and collect all error messages, not just the first one.
- 36-38Valid data gives an empty dict; bad data gives per-field message lists; a missing slug is treated as an empty string.
Authentication and permissions
Django ships with an authentication system: a User model, password hashing, sessions, login and logout views, and permissions. You rarely write the hard parts yourself. Add path('accounts/', include('django.contrib.auth.urls')) to get login, logout and password-change views at ready-made URLs, then provide a registration/login.html template that shows the form.
In views, protect pages with the @login_required decorator (or LoginRequiredMixin for class-based views) and check request.user for who is logged in. In templates, user.is_authenticated lets you show different navigation to guests and members. Permissions such as blog.add_post can be checked with @permission_required or user.has_perm().
A tip I want you to remember: even if you plan to use the default user now, start new projects with a custom user model (a small subclass of AbstractUser) before the first migration, because switching later is painful. Passwords are never stored as plain text; Django stores a salted hash, so you also should never compare passwords yourself.
# mysite/urls.py (addition)
from django.urls import include, path
urlpatterns += [
path("accounts/", include("django.contrib.auth.urls")),
]
# blog/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
class MyPostsView(LoginRequiredMixin, ListView):
template_name = "blog/my_posts.html"
context_object_name = "posts"
def get_queryset(self):
return self.request.user.posts.all()Line by line
- 2-5Mount Django's built-in auth views (
login,logout, password change and reset) under/accounts/. - 8-9A class-based view and its login mixin.
- 12-14
LoginRequiredMixinsends anonymous users to the login page;template_nameandcontext_object_nametellListViewhow to render. - 16-17Only the logged-in user's own posts are returned, using the
related_name='posts'we defined on the model.
Putting it together: a small blog walk-through
Here is the order I would follow to build the blog from scratch. First create the project and the blog app, and add blog to INSTALLED_APPS. Second, write the Post model, run makemigrations and migrate, and create a superuser. Third, register the model in the admin and add two or three posts through the admin, which is a fast way to get sample data.
Fourth, write the list and detail views, give them URLs in the app, and include the app URLs from the project. Fifth, create base.html, post_list.html and post_detail.html. Sixth, add the login URLs and the post_create view with its form, protected by login_required. At each step run the server and look at the page; small steps make errors easy to locate.
Next steps are testing and deployment. Django has a test framework built on unittest (and works well with pytest through plugins), and the check --deploy command lists security issues. When you deploy, set DEBUG off, restrict ALLOWED_HOSTS, keep secrets in environment variables, run collectstatic for CSS and use a production server such as Gunicorn or an ASGI server behind a reverse proxy. Hosting details change often, so follow your host's current Django guide.
python manage.py startapp blog python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py test python manage.py check --deploy python manage.py collectstatic
Line by line
- 1Create the app, then edit models and settings.
- 2-3Generate and apply the database changes.
- 4Make an admin login so you can add data.
- 5Run the project's tests; Django creates a temporary test database.
- 6Print warnings about unsafe deployment settings.
- 7Gather static files into one folder for the production web server.
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import Post
class PostViewTests(TestCase):
def setUp(self):
user = get_user_model().objects.create_user("glenn", password="pw12345!")
Post.objects.create(title="Live", slug="live", author=user, body="x", published=True)
Post.objects.create(title="Draft", slug="draft", author=user, body="x")
def test_list_shows_only_published(self):
response = self.client.get(reverse("blog:list"))
self.assertContains(response, "Live")
self.assertNotContains(response, "Draft")
def test_unpublished_detail_is_404(self):
response = self.client.get(reverse("blog:detail", kwargs={"slug": "draft"}))
self.assertEqual(response.status_code, 404)Line by line
- 8-12
setUpruns before each test in a clean temporary database and creates a user and two posts. - 14-17The test client requests the list page like a browser would; the draft must not appear.
- 19-21A draft's detail page must return 404, matching
get_object_or_404(..., published=True).
Common mistakes
β Forgetting to add the app to INSTALLED_APPS
Without it Django ignores the app's models, templates and admin, so migrations seem to do nothing. Add the app name (or its config path) to the setting right after startapp.
β Running with DEBUG on in production
Debug pages show settings, code and queries to anyone who triggers an error. Turn debug off, set ALLOWED_HOSTS and keep SECRET_KEY out of the repository.
β Editing or deleting applied migrations
On a shared project, rewriting history breaks teammates' and production databases. Add a new migration instead, and commit migration files.
β Putting business logic in templates
Templates are limited on purpose. Compute values in views or model methods and keep the template for presentation.
β Skipping the CSRF token in forms
A POST form without {% csrf_token %} is rejected with a 403 error. Include the tag in every form that posts to your site.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What is the difference between a Django project and an app?
Q2. What does makemigrations do?
makemigrations records changes as files; migrate is the command that applies them to the database.Q3. Why use name= on URL patterns and {% url %} in templates?
Q4. When does a QuerySet like Post.objects.filter(published=True) actually query the database?
Q5. Why use form.save(commit=False) in the create view?
Q6. What happens if you POST a form without a CSRF token?
Frequently asked questions
Should I learn Django or Flask first?
+Both are fine. Flask shows the basics of web requests with very little code, while Django teaches a complete, structured approach with ORM, admin and auth. If you want to build database-backed sites quickly, Django is a good first framework.
Do I need to know SQL to use Django?
+Not to start, because the ORM writes SQL for you. Understanding SQL still helps you reason about performance and relationships, and our SQLite lesson is a gentle way to learn it.
Why can't I run Django code in the browser on this page?
+Django is a server framework that needs a real Python environment, a database and a web server process. That is why real Django examples here are static and the teaching examples (mini-ORM, URL resolver, validators) are runnable.
Can Django build APIs?
+Yes. Django can return JSON from views, and the Django REST framework is a popular add-on for full APIs. If APIs are your main goal, also look at FastAPI.
Which database should I use?
+SQLite is the default and is fine for learning and small sites. Many production sites use PostgreSQL. Because the ORM abstracts the database, switching is mostly a settings change, though you should test your queries.
Key takeaways
- βA Django project holds settings and root URLs; apps are feature modules that must be listed in
INSTALLED_APPS. - βModels describe tables, the ORM queries them lazily, and migrations record and apply schema changes.
- βURL patterns map paths to views; give routes names and reverse them instead of hard-coding paths.
- βTemplates present data with inheritance, auto-escaping and a deliberately small set of tags.
- βThe admin,
ModelFormand the auth system give you powerful features with little code, so use them. - βKeep secrets out of the repository, turn DEBUG off in production and test your views.