Explain it simply
Django in plain language
Django is a 'batteries included' web framework for building websites and APIs in Python. When a browser asks for a URL, Django finds the Python function, called a view, that matches it, calls that function, and sends whatever response it returns back to the browser.
Picture a restaurant: the list of URLs is the menu, a view is the cook who prepares one dish, and the response is the plate that reaches the table. Django also ships with a database layer (the ORM), logins, an admin panel, forms and security protections, so you do not rebuild those from scratch.
Problem → Why → Solution
The problem: writing a web server by hand
Build a small API with Python's http.server and you end up parsing the path yourself with if/elif. You split strings to pull the number out of /books/2/, encode JSON by hand and write headers manually. Every new route is another branch, and an id like 'abc' crashes the handler.
from http.server import BaseHTTPRequestHandler
import json
BOOKS = {1: "Dune", 2: "Emma"}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
body = b"Hello"
elif self.path.startswith("/books/"):
book_id = int(self.path.split("/")[2]) # crashes on /books/abc/
body = json.dumps({"title": BOOKS[book_id]}).encode() # KeyError on 9
self.send_response(200) # always 200, even for errors
self.end_headers()
self.wfile.write(body) # unknown paths: body undefinedWhat the framework takes off your hands
In Django, the single line path("books/<int:book_id>/", view) splits the URL, converts the id to int and answers 404 when it is not a number. The view returns Python data and JsonResponse handles encoding and headers, so your attention stays on the application logic.
Core concept: the journey of one request
Django request-response cycle
-----------------------------
browser --GET /books/2/--> Django
|
v
middleware (security, sessions, ...)
|
v
ROOT_URLCONF -> urlpatterns, checked top to bottom
| "books/<int:book_id>/" matches
v
book_detail(request, book_id=2)
|
v
browser <--200 + JSON------ JsonResponse(...)When a request arrives, Django builds an HttpRequest object and passes it through the middleware layers. It then walks the urlpatterns list in the module named by the ROOT_URLCONF setting, from top to bottom, and calls the view of the first pattern that matches. If nothing matches, the answer is 404 Not Found.
A view is a function that receives the request as its first argument and must return an HttpResponse or a subclass such as JsonResponse. A path converter like <int:book_id> captures part of the URL, converts it to int and passes it to the view as a keyword argument. The built-in converters are str, int, slug, uuid and path, and a value that does not fit, such as abc for an int, simply means the pattern does not match.
Middleware is a stack of small layers that every request passes through before and after the view. Built-in ones such as SecurityMiddleware, SessionMiddleware, CsrfViewMiddleware and AuthenticationMiddleware add security headers, load the session, check form POSTs for a CSRF token and fill in request.user, all in one place instead of in every view.
Django separates the project from its apps. The project is the configuration for the whole site: settings, the root URLs and the deployment entry points wsgi.py and asgi.py. An app is a Python package grouping the models, views and URLs of one feature, such as blog, accounts or shop, and Django only knows about it once it is listed in INSTALLED_APPS.
| Setting | Meaning |
|---|---|
| DEBUG | True shows detailed error pages; must be False in production |
| ALLOWED_HOSTS | host names the site will answer when DEBUG is False |
| SECRET_KEY | signs sessions and tokens; keep it out of git |
| INSTALLED_APPS | the apps active in this project |
- A request arrives
- urlpatterns are checked top-down
- The matching view gets called
- The view returns an HttpResponse
When a Django page fails, find which of these four links broke: no URL match, an error in the view, or no response returned.
General pattern
# views.py
from django.http import HttpResponse, JsonResponse
def view_name(request, captured_value):
return JsonResponse({"key": value}, status=200)
# urls.py
from django.urls import path
urlpatterns = [
path("prefix/<int:captured_value>/", view_name, name="route-name"),
]A view takes the request plus any values captured from the URL and returns a response. Each path() in urlpatterns connects a URL shape to a view, and the name lets reverse() build that URL later.
Worked example: a book API in a single file
The program below configures Django in code with settings.configure() so it runs as one file, without a project folder. That is only for this demo; in a real project these values live in settings.py. ROOT_URLCONF=__name__ tells Django that this very file plays the role of urls.py.
Instead of opening a browser, django.test.Client sends fake requests through the full Django stack: URL routing, the view and the response. Each output line shows the status code, the URL and the first line of the response body.
# Single-file demo: settings.configure() stands in for a project's settings.py
import django
from django.conf import settings
settings.configure(
DEBUG=False,
SECRET_KEY="demo-only-not-secret",
ALLOWED_HOSTS=["testserver"],
ROOT_URLCONF=__name__, # this file also acts as urls.py
)
django.setup()
from django.http import HttpResponse, JsonResponse
from django.test import Client
from django.urls import path
BOOKS = {1: "Dune", 2: "Emma"}
def home(request):
return HttpResponse("Hello, Django!")
def book_detail(request, book_id):
if book_id not in BOOKS:
return JsonResponse({"error": "not found"}, status=404)
return JsonResponse({"id": book_id, "title": BOOKS[book_id]})
def search(request):
q = request.GET.get("q", "").lower()
hits = [t for t in BOOKS.values() if q in t.lower()]
return JsonResponse({"query": q, "results": hits})
urlpatterns = [
path("", home),
path("books/<int:book_id>/", book_detail, name="book-detail"),
path("search/", search),
]
client = Client() # sends fake requests through the full Django stack
for url in ["/", "/books/2/", "/books/9/", "/books/abc/", "/search/?q=un"]:
response = client.get(url)
first_line = response.content.decode().strip().splitlines()[0]
print(response.status_code, url, first_line[:40])Code breakdown
- Configure, then set up
django.setup()settings.configure() replaces settings.py, and django.setup() prepares the app registry. Other Django modules are imported only after these two lines.
- A plain-text view
return HttpResponse("Hello, Django!")Every view must return a response object. HttpResponse sends a string body with the default status 200.
- JSON and a status
return JsonResponse({"error": "not found"}, status=404)An unknown book id returns a JSON error with status 404. JsonResponse turns the dict into a JSON string and sets the Content-Type: application/json header.
- Query string
q = request.GET.get("q", "").lower()Parameters after the ? in /search/?q=un land in request.GET. Using .get() with a default avoids an error when q is missing.
- Converter rejects abc
path("books/<int:book_id>/", book_detail, name="book-detail"),/books/abc/ does not fit the int converter, so the view is never called and Django's HTML 404 page comes back. /books/9/ does match, and gets the view's own JSON 404.
200 / Hello, Django!
200 /books/2/ {"id": 2, "title": "Emma"}
404 /books/9/ {"error": "not found"}
404 /books/abc/ <!doctype html>
200 /search/?q=un {"query": "un", "results": ["Dune"]}The layout of a real project
A real project does not use settings.configure(). It starts with four commands: pip install django, django-admin startproject mysite, cd mysite, then python manage.py startapp books. startapp does not create a urls.py, so you add one yourself and connect it from the project's urls.py with include().
startproject + startapp layout
------------------------------
mysite/
manage.py command-line entry: runserver, migrate, startapp...
mysite/ the project package
__init__.py
settings.py DEBUG, INSTALLED_APPS, DATABASES, ...
urls.py root urlpatterns (ROOT_URLCONF)
asgi.py, wsgi.py entry points for production servers
books/ an app created by startapp
models.py views.py admin.py apps.py tests.py
migrations/
urls.py you create this one yourselffrom django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("books/", include("books.urls")), # hand the rest to the app
]python manage.py runserver starts a development server at http://127.0.0.1:8000/ and reloads when code changes. python manage.py migrate creates the tables for the built-in apps, and createsuperuser makes an account for /admin/. Never use runserver in production; use a server such as Gunicorn or Uvicorn.
In real projects
Django in real projects
Django powers content sites, online shops, internal tools and backend APIs for mobile apps. It shines when a data-heavy application must be built quickly, since the admin panel alone gives staff a working interface for managing data on day one. Teams also lean on the test client from this lesson to check every URL in automated tests.
- Content sites and blogs: features are split into apps such as blog and accounts, and templates render HTML pages.
- JSON APIs: teams start with the JsonResponse style from this lesson and often add Django REST Framework for serialization, authentication and pagination as the project grows.
- Security: the ORM uses parameterized queries against SQL injection, templates autoescape HTML to reduce XSS, and the CSRF middleware checks form POSTs.
Common mistakes
Common beginner mistakes in Django
A view that returns nothing
Forget a return in one branch and the function returns None, so Django raises ValueError: 'The view ... didn't return an HttpResponse object. It returned None instead.' Make sure every branch returns a response, including explicit 404 or 400 responses for error cases.
Leaving DEBUG=True in production
With DEBUG=True, error pages reveal settings, code and request details to anyone. In production set DEBUG=False, fill ALLOWED_HOSTS with your real domain and read SECRET_KEY from an environment variable. python manage.py check --deploy flags these problems for you.
Not adding the app to INSTALLED_APPS
After startapp, an app missing from INSTALLED_APPS is invisible to Django: its models, templates and migrations are ignored. makemigrations reports 'No changes detected' and templates fail to load.
Best practices
Best practices
- Give each app its own urls.py and connect it from the project's urls.py with include().
- Name every route and build URLs with reverse() in code or {% url %} in templates.
- Keep views thin and move business logic into separate functions or model methods.
- Read secrets and per-environment settings from environment variables.
Mini challenge
Mini challenge: a task list API
Build a small JSON API for tasks in one file. /tasks/ returns the list on GET and adds a task on POST, and /tasks/<id>/ returns one task. Use the test client to exercise a success case, a blank title, a missing id and a method that is not allowed.
- POST returns 400 for a blank title and 201 with the new task on success
- An unknown id such as /tasks/7/ returns a 404 JSON error
- Use require_http_methods so DELETE /tasks/ answers 405
- Build URLs with reverse() instead of hard-coding strings
import django
from django.conf import settings
# TODO: settings.configure(...) with DEBUG, SECRET_KEY, ALLOWED_HOSTS
# and ROOT_URLCONF=__name__, then django.setup()
TASKS = {1: {"id": 1, "title": "Read the Django tutorial", "done": False}}
# TODO: allow only GET and POST
def task_list(request):
# TODO: POST -> validate request.POST["title"], add a task, return 201
# TODO: GET -> return {"count": ..., "tasks": [...]}
...
def task_detail(request, pk):
# TODO: 404 JSON when pk is unknown, otherwise the task
...
urlpatterns = [
# TODO: "tasks/" named "task-list" and "tasks/<int:pk>/" named "task-detail"
]
# TODO: use django.test.Client to try each case and print status codesExpected: reverse prints /tasks/2/, the first POST gives 201 with task id 2, the blank POST gives 400, the list shows 2 tasks, /tasks/7/ gives 404 and DELETE /tasks/ gives 405.
Show hint
Import require_http_methods from django.views.decorators.http and put @require_http_methods(["GET", "POST"]) above the view. The test client's c.post(url, {"title": ...}) sends form data into request.POST, and response.json() turns a JSON body into a dict.
Show solution
import django
from django.conf import settings
settings.configure(
DEBUG=False,
SECRET_KEY="demo-only",
ALLOWED_HOSTS=["testserver"],
ROOT_URLCONF=__name__,
)
django.setup()
from django.http import JsonResponse
from django.test import Client
from django.urls import path, reverse
from django.views.decorators.http import require_http_methods
TASKS = {1: {"id": 1, "title": "Read the Django tutorial", "done": False}}
@require_http_methods(["GET", "POST"])
def task_list(request):
if request.method == "POST":
title = request.POST.get("title", "").strip()
if not title:
return JsonResponse({"error": "title is required"}, status=400)
new_id = max(TASKS) + 1
TASKS[new_id] = {"id": new_id, "title": title, "done": False}
return JsonResponse(TASKS[new_id], status=201)
return JsonResponse({"count": len(TASKS), "tasks": list(TASKS.values())})
def task_detail(request, pk):
task = TASKS.get(pk)
if task is None:
return JsonResponse({"error": f"task {pk} not found"}, status=404)
return JsonResponse(task)
urlpatterns = [
path("tasks/", task_list, name="task-list"),
path("tasks/<int:pk>/", task_detail, name="task-detail"),
]
c = Client()
print("URL for task 2:", reverse("task-detail", args=[2]))
r = c.post(reverse("task-list"), {"title": "Write a view"})
print(r.status_code, r.json())
r = c.post(reverse("task-list"), {"title": " "})
print(r.status_code, r.json())
print(c.get("/tasks/").json()["count"], "tasks")
print(c.get("/tasks/2/").json()["title"])
print(c.get("/tasks/7/").status_code, c.delete("/tasks/").status_code)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A request travels through middleware, urlpatterns and a view, and leaves as an HttpResponse.
- path() with converters such as <int:pk> splits and converts the URL into view arguments.
- Every branch of a view must return an HttpResponse or JsonResponse.
- The project holds settings and root URLs; each app is one feature and must be in INSTALLED_APPS.
Django — Getting Started — Django Software Foundation