Every Django Concept a Beginner Needs to Know
Every Django concept a beginner needs, each shown doing its job: project and apps, settings, URLs, views, templates, models, migrations, QuerySets, the admin, forms, middleware, and users and sessions. One small renovation job board, built for real on Ubuntu, takes 21 database queries to show one page, and by the end one change brings it to one.
One page, 21 questions
Your Django page works, but the words around it still blur together. View, QuerySet, middleware. Ben's page works too. It's the job board for his small renovation company: twenty open tasks across eight houses.

To show this one page, Django asked the database twenty-one questions. Twenty of them were wasted. curl shows the page's headers, little notes sent along with it. Ben added one that counts queries, and it says twenty-one. By the end, you'll know the twelve Django concepts behind this page, and the one change that brings twenty-one down to one.
(.venv) ben@laptop:~/renovate$ curl -sI localhost:8000/tasks/open/HTTP/1.1 200 OK Date: Wed, 25 Nov 2026 03:27:19 GMT Server: WSGIServer/0.2 CPython/3.12.3 Content-Type: text/html; charset=utf-8 X-Queries: 21 X-Frame-Options: DENY Content-Length: 1454 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin
Here's where those concepts live. A request comes in from the browser. It's wrapped by middleware, matched by its address to a view, and the view is just a Python function. The view asks models for data, models ask the database, and a template turns the data into HTML. The answer goes back the same way.

Project and apps
First, two words people mix up: project and app. The project is the whole site. Start project made a folder named renovate, with the settings and the main list of URLs. The dot at the end means right here. It also made manage.py, the helper you run every other command through. An app is one part of the site, with its own models and views. Ben's one app is jobs. A bigger site has several apps, like invoices or a blog.
(.venv) ben@laptop:~/renovate$ django-admin startproject renovate .
(.venv) ben@laptop:~/renovate$ python manage.py startapp jobs
(.venv) ben@laptop:~/renovate$ ls renovate__init__.py __pycache__ asgi.py settings.py urls.py wsgi.py
(.venv) ben@laptop:~/renovate$ ls jobs__init__.py admin.py apps.py migrations models.py tests.py views.py
Settings
Forget one line in one file, and Django won't even see Ben's app. That file is settings.py. DEBUG True gives detailed error pages while you build. DATABASES says where the data lives: a SQLite file, unless you change it. And INSTALLED_APPS lists the apps Django loads. Ben added jobs by hand, on the last line. Forget that line, and Django never looks for its templates or models.
(.venv) ben@laptop:~/renovate$ grep -n '^DEBUG\|^INSTALLED_APPS\|^DATABASES\|^MIDDLEWARE\|^LOGIN' renovate/settings.py26:DEBUG = True 33:INSTALLED_APPS = [ 43:MIDDLEWARE = [ 77:DATABASES = { 131:LOGIN_REDIRECT_URL = "/mine/"
(.venv) ben@laptop:~/renovate$ grep -A8 '^INSTALLED_APPS' renovate/settings.pyINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jobs', ]
URLs
URLs pick which view answers. Think of the directory board in a building's lobby: find the name, and it tells you the floor. Ben's main urls.py sends anything starting with admin to Django's admin, and hands everything else to the jobs app's own urls.py.
(.venv) ben@laptop:~/renovate$ sed -n '/^urlpatterns/,$p' renovate/urls.pyurlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("django.contrib.auth.urls")), path("", include("jobs.urls")), ]
Here's one pattern from that list: jobs, slash, then a number in angle brackets. The int part means it only matches digits. The pk part, short for primary key, the job's ID number, is the name the number gets, and Django hands it to the view. So slash jobs slash two calls job detail with pk equal to two.

Slash jobs slash a b c has no digits, so no pattern matches. With DEBUG on, the 404 page lists every pattern it tried, like a name that isn't on the directory board.

Views
A view is a Python function. It takes the request and returns a response. Ben's job detail view gets pk from the URL. It fetches that job, or returns a 404 if there isn't one. Then it renders a template with the job in it. The same view handles the add-a-task form. A GET is the browser asking for the page, so it just shows it. A POST is the browser sending the form, so it saves the task and sends the browser back to the page.
(.venv) ben@laptop:~/renovate$ sed -n '/^def job_detail/,/^$/p' jobs/views.pydef job_detail(request, pk): job = get_object_or_404(Job, pk=pk) form = TaskForm(request.POST or None) if request.method == "POST" and form.is_valid(): task = form.save(commit=False) task.job = job task.save() return redirect(f"/jobs/{job.pk}/") return render(request, "jobs/job.html", {"job": job, "form": form})
So what about slash jobs slash ninety-nine? The pattern matches, but there's no job ninety-nine. Guess first. Also a 404, but a different one: no job matches the given query. The first 404 came from the URL list. This one came from the view.
(.venv) ben@laptop:~/renovate$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/jobs/99/404
(.venv) ben@laptop:~/renovate$ curl -s localhost:8000/jobs/99/ | grep -o 'No Job matches the given query.'No Job matches the given query.
(.venv) ben@laptop:~/renovate$ curl -s localhost:8000/jobs/abc/ | grep -o 'didn.t match any of these'didn’t match any of these
Templates
Ben's pages all share one header and one frame. Does he copy it into every file? No. A template is HTML with blanks Django fills in, and tags in percent signs that shape the page. Ben writes the page frame once, in base.html, with named blocks. Every other page starts with extends, and fills only its own blocks. That's template inheritance: change the frame once, every page follows. The blanks are the double curly braces, like task dot room. Django fills them from the context, the dictionary the view passed in.
(.venv) ben@laptop:~/renovate$ grep -h 'extends\|block content\|{{ task' jobs/templates/jobs/{base,open}.html{% block content %}{% endblock %} {% extends "jobs/base.html" %} {% block content %} <h1>Open tasks ({{ tasks|length }})</h1> <li>{{ task.job.address }}: {{ task.room }}, {{ task.title }}</li>
Templates also protect you. Someone typed bold tags into a task's title. Django printed them as plain text, not as HTML. That's automatic escaping: whatever people type into your site can't turn into code on your page.

Models
A model is a Python class that describes one kind of thing you store. Each model becomes a table, and each field becomes a column. A Task has a room, a title, and a done field that's true or false. And ForeignKey links each task to its job, so one house has many tasks. You never write create table yourself: that's the next concept's job.
(.venv) ben@laptop:~/renovate$ sed -n '4,20p' jobs/models.pyclass Job(models.Model): address = models.CharField(max_length=100) client = models.CharField(max_length=60) def __str__(self): return self.address class Task(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="tasks") room = models.CharField(max_length=40) title = models.CharField(max_length=100) done = models.BooleanField(default=False) def __str__(self): return f"{self.room}: {self.title}"
Migrations
But a class isn't a table yet. Make migrations writes a migration: a small file that describes the change. S Q L migrate shows the S Q L that file will run, create table jobs task. Then migrate runs it.
(.venv) ben@laptop:~/renovate$ python manage.py makemigrationsMigrations for 'jobs': jobs/migrations/0001_initial.py + Create model Job + Create model Task
(.venv) ben@laptop:~/renovate$ python manage.py sqlmigrate jobs 0001BEGIN; -- -- Create model Job -- CREATE TABLE "jobs_job" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "address" varchar(100) NOT NULL, "client" varchar(60) NOT NULL); -- -- Create model Task -- CREATE TABLE "jobs_task" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "room" varchar(40) NOT NULL, "title" varchar(100) NOT NULL, "done" bool NOT NULL, "job_id" bigint NOT NULL REFERENCES "jobs_job" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "jobs_task_job_id_6fefee23" ON "jobs_task" ("job_id"); COMMIT;
Later, Ben gives each task a person: assigned to. A second migration adds just that field, migrate applies it, and show migrations ticks off both. The migration files go in Git with your code, so every copy of the site builds the same tables.
(.venv) ben@laptop:~/renovate$ python manage.py makemigrationsMigrations for 'jobs': jobs/migrations/0002_task_assigned_to.py + Add field assigned_to to task
(.venv) ben@laptop:~/renovate$ python manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, jobs, sessions Running migrations: Applying jobs.0002_task_assigned_to... OK
(.venv) ben@laptop:~/renovate$ python manage.py showmigrations jobsjobs [X] 0001_initial [X] 0002_task_assigned_to
QuerySets
Back to those twenty-one questions: this is where Django asks them. To watch it happen, Ben opens the shell, a Python prompt with his project loaded and his models already imported.
(.venv) ben@laptop:~/renovate$ python manage.py shell14 objects imported automatically (use -v 2 for details). Python 3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole)
>>> from django.db import connection
A QuerySet is a question you haven't asked yet. Every model has a handle on its table, called objects. Ben writes Task dot objects dot filter, done equals False. Nothing runs. connection dot queries, Django's list of the S Q L it has run, still holds zero. Only when he asks for the count does Django run one.
>>> tasks = Task.objects.filter(done=False)
>>> len(connection.queries)0
>>> tasks.count()20
>>> len(connection.queries)1
Curious what it asked? Print the QuerySet's query: plain SQL. Select from jobs task, where done is false. That's the ORM, the object relational mapper: you write Python, and Django writes the SQL for whichever database you use.
>>> print(tasks.query)SELECT "jobs_task"."id", "jobs_task"."job_id", "jobs_task"."room", "jobs_task"."title", "jobs_task"."done", "jobs_task"."assigned_to_id" FROM "jobs_task" WHERE "jobs_task"."done" = False
You can add to a QuerySet before it runs: filter open tasks again for the kitchen, four. And get expects exactly one row. Ask for P K ninety-nine, the job with ID ninety-nine, and it raises DoesNotExist, the error that the view turned into a 404.
>>> tasks.filter(room='Kitchen').count()4
>>> Job.objects.get(pk=99)Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/ben/renovate/.venv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ben/renovate/.venv/lib/python3.12/site-packages/django/db/models/query.py", line 722, in get raise self.model.DoesNotExist( jobs.models.Job.DoesNotExist: Job matching query does not exist.
So where did twenty-one come from? The view asks once for twenty tasks. Then the template prints each task's house address, and every task fetches its job on its own: twenty more queries. Call the number of tasks N: one query for the list, plus N for the houses. That's the N plus one problem.
(.venv) ben@laptop:~/renovate$ grep -n 'task.job.address' jobs/templates/jobs/open.html7: <li>{{ task.job.address }}: {{ task.room }}, {{ task.title }}</li>
The fix is one method on the QuerySet: select_related, with the field's name.

How many queries now? Guess first. One. Django joins the two tables and brings each task's house along. Same twenty tasks, one trip.
(.venv) ben@laptop:~/renovate$ curl -sI localhost:8000/tasks/open/ | grep -i x-queriesX-Queries: 1
(.venv) ben@laptop:~/renovate$ curl -s localhost:8000/tasks/open/ | grep -c '<li>'20
The admin
Ben's office manager needs to fix a typo in a task, and she can't edit Python. Django already built a back office: the admin. Ben registers his models in admin.py and picks the columns and a filter.
(.venv) ben@laptop:~/renovate$ sed -n '3,$p' jobs/admin.pyfrom .models import Job, Task @admin.register(Task) class TaskAdmin(admin.ModelAdmin): list_display = ["room", "title", "job", "done"] list_filter = ["done"] admin.site.register(Job)
That's the whole setup. It lives at slash admin, and Ben signs in with the superuser account he made with create superuser. Staff can now find, fix and add tasks without writing any code. It's for the people who run the site, not for customers.

Forms
What stops someone adding a task with a blank title? A form. It checks what people type before it reaches a model. Ben's form for a new task wants a room and a title. Type three spaces for the title, and the form strips them, finds nothing, and shows the message: this field is required. The form also carries a CSRF token, short for cross-site request forgery: a hidden secret. Django checks it every time a form is sent, so another website can't send this form in your name.

In the shell it's the same check. is_valid says False, and errors names the field and the reason. Your view saves only when is_valid is True.
>>> form = TaskForm(data={'room': 'Bathroom', 'title': ' '})
>>> form.is_valid()False
>>> form.errors{'title': ['This field is required.']}
Middleware
Something had to wrap every page to count those queries. That's middleware: code that wraps every request and every response. Django ships seven in the list: sessions, CSRF checks, signing people in. Order matters: a request passes down the list, top to bottom, and the response comes back up. Signing in reads the session, Django's memory of who you are between pages, so it sits below the session one. The last one is Ben's, and it's the one that counted those twenty-one queries.
(.venv) ben@laptop:~/renovate$ grep -A9 '^MIDDLEWARE' renovate/settings.pyMIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'jobs.middleware.QueryCountMiddleware', ]
It's a dozen lines. Count the queries so far, call get response, which runs the view, count again, and put the difference in a header, a note sent with the page. Every page on the site now reports its own number.
(.venv) ben@laptop:~/renovate$ cat jobs/middleware.pyfrom django.db import connection class QueryCountMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): before = len(connection.queries) response = self.get_response(request) response["X-Queries"] = len(connection.queries) - before return response
Users and sessions
Last, users and sessions. Ana should see her own tasks, and a stranger none. Ben put login_required on the line just above his my tasks view: a marker that means signed-in users only. Ask for it signed out, and Django answers 302: go to the login page, then come back to slash mine.
(.venv) ben@laptop:~/renovate$ curl -sI localhost:8000/mine/ | grep -i '^HTTP\|^location'HTTP/1.1 302 Found Location: /accounts/login/?next=/mine/
Ana, one of Ben's crew, signs in, and lands on her own three tasks.

How does the next page know it's her? A session: one row in the database. Decoded, it says user two, and user two is Ana. Her browser holds only a random key to that row, in a cookie named sessionid. Sign out, and the row is deleted. That's why there's only one: Ben signed out of the admin earlier.
>>> Session.objects.count()1
>>> Session.objects.first().get_decoded()['_auth_user_id']'2'
>>> User.objects.get(username='ana').pk2
What comes next
Three more you'll meet soon. Class-based views: a view written as a class, like ListView, for pages every site has. Static files: your CSS and images, served differently once the site is live. And tests: manage.py test runs them against a throwaway copy of your database.

Recap
Twelve concepts, one path. Middleware wraps the request, URLs pick the view, the view asks models, and a template draws the answer. And when a page feels slow, count its queries first.

If the Django words are less of a blur now, subscribing brings the next one your way.
The job board's code and every command are linked in the description. Thanks for watching Cloud Explainers.
Sources
- Django documentation, Applications
- Django documentation, Settings
- Django documentation, URL dispatcher (path converters)
- Django documentation, Writing views and get_object_or_404
- Django documentation, The Django template language (inheritance, automatic HTML escaping)
- Django documentation, Models
- Django documentation, Migrations
- Django documentation, Making queries (QuerySets are lazy)
- Django documentation, QuerySet API: select_related
- Django documentation, The Django admin site
- Django documentation, Working with forms
- Django documentation, Middleware
- Django documentation, Using the Django authentication system (login_required)
- Django documentation, How to use sessions
Demos: a container on our own Mac standing in for a laptop; the renovation company is made up. Django was downloaded from PyPI during the run. Every command, error and number was real. Watch the full video on YouTube.