Frameworks
Build database-backed web apps and APIs with Django: routing, views, templates, the ORM, auth, testing and deployment.
A path through Django from a first project to production: URL routing, views and templates, models and the ORM, forms, authentication, REST APIs, testing and deployment. It is for developers comfortable with basic Python who want to build full web applications. Each subject links the official documentation.
The subjects follow the roadmap.sh Django roadmap.
Django is a batteries-included Python web framework: ORM, migrations, templates, forms, auth, admin and security defaults all ship in the box. It favours convention and explicit configuration, which makes it quick for database-backed sites and APIs.
Browsers send HTTP requests to a server, which returns HTML, JSON or files with status codes and headers. Django is the code that turns each request into a response on that server.
Routing, sessions, database access, templating, CSRF protection and input validation are needed by nearly every site. A framework solves them once, tested and secure, so you write only the parts specific to your product.
Model–view–controller splits data, presentation and request handling. Django calls its variant MTV: models hold data, templates render it, and views play the controller role, with the URLconf dispatching requests.
Give each project its own isolated Python environment so dependency versions never clash. Create one with python -m venv .venv, activate it, and pin packages in requirements.txt or a pyproject.toml lock managed by a tool such as uv or Poetry.
Inside the active environment run pip install django, then confirm with python -m django --version. Prefer the current LTS release for long-lived projects and check which Python versions it supports.
A project is the whole site — settings, root URLconf, WSGI/ASGI entry points — created with django-admin startproject. Apps are reusable packages of models, views and templates created with python manage.py startapp and listed in INSTALLED_APPS.
The files startproject generates and what each controls. Knowing them tells you where configuration, routing and command-line tooling live.
A thin wrapper around django-admin that sets DJANGO_SETTINGS_MODULE. You run runserver, makemigrations, migrate, shell, test and your own custom commands through it.
Plain Python module holding INSTALLED_APPS, MIDDLEWARE, DATABASES, TEMPLATES, DEBUG, SECRET_KEY and more. Read secrets and per-environment values from environment variables, never commit them.
The root URLconf named by ROOT_URLCONF maps paths to views and pulls in each app's own urls.py with include(), giving every app a namespaced, self-contained route list.
Each app follows the same layout, which keeps large projects navigable. Split a file into a package (views/, models/) once it grows too big — Django does not care as long as imports resolve.
Model classes subclassing models.Model; each maps to a table. Changes here are what makemigrations detects.
Functions or classes that take an HttpRequest and return an HttpResponse. Keep them thin and push domain logic into models or service modules.
Registers models with the admin site via admin.site.register() or the @admin.register decorator, plus their ModelAdmin options.
Default home for the app's test cases, discovered by manage.py test. Most projects soon replace it with a tests/ package split by area.
The package of generated migration files, one numbered module per schema change. Commit them and review them like code.
Beyond Python modules, a project carries front-end assets, user uploads and templates. Each has its own setting and is served differently in development and production.
Per-app static/<app>/ folders for CSS, JavaScript and images you ship. collectstatic gathers them into STATIC_ROOT for the web server or CDN.
User-uploaded files saved under MEDIA_ROOT and served from MEDIA_URL. Never trust their names or types; in production serve them from object storage, not Django.
Per-app templates/<app>/ folders (found when APP_DIRS is true) plus project-wide directories listed in TEMPLATES['DIRS']. The app-name subfolder prevents name collisions.
python manage.py runserver starts the auto-reloading development server on port 8000; run migrate first so the built-in apps have their tables. It is for development only — production uses Gunicorn, uWSGI or an ASGI server like Uvicorn.
Django matches the request path against urlpatterns in order and calls the first matching view with captured values as keyword arguments. Naming routes and reversing them keeps URLs out of your code.
A list of path() and re_path() entries, each pairing a route string with a view and optional name and kwargs. Order matters: specific routes go before catch-alls.
Typed captures like <int:pk>, <slug:slug>, <uuid:id> and <path:rest> that validate and convert segments. Register your own with register_converter().
re_path() accepts a regular expression with named groups for cases converters cannot express. Captured values arrive as strings, so convert them yourself.
Give each pattern a name and an app an app_name namespace, then refer to "blog:detail" instead of hard-coded paths, so routes can move without breaking links.
Build URLs from names: reverse() and reverse_lazy() in Python, {% url %} in templates, redirect("name", pk=1) in views, and get_absolute_url() on models.
Middleware can influence resolution: CommonMiddleware handles APPEND_SLASH, LocaleMiddleware adds language prefixes, and setting request.urlconf swaps the URLconf per request, e.g. for subdomains.
A request enters through WSGI or ASGI, becomes an HttpRequest, passes down the middleware stack, is resolved to a view, and the returned HttpResponse travels back up through middleware. Knowing this order explains where sessions, auth and CSRF checks happen.
A view is any callable that takes a request and returns a response, or raises an exception such as Http404. Shortcuts like render(), get_object_or_404() and redirect() cover most needs.
Plain functions, explicit and easy to read. Restrict methods with @require_POST or @require_http_methods and add access control with @login_required.
Classes whose as_view() returns a view function and dispatches to get(), post() and friends. Behaviour composes through mixins like LoginRequiredMixin; understand the method resolution order before overriding.
Django's generic class-based views implement common patterns; you customise them by setting attributes (model, template_name, paginate_by) and overriding hooks such as get_queryset(), get_context_data() and form_valid().
Ready-made views for displaying and editing objects, plus TemplateView and RedirectView. They save boilerplate but hide control flow, so read the source when behaviour surprises you.
Renders a queryset into <model>_list.html with object_list in context and built-in pagination through paginate_by. Override get_queryset() to filter by the request.
Looks up one object by pk or slug from the URL and renders <model>_detail.html, returning 404 when it is missing.
Shows a model form on GET and saves on a valid POST, then redirects to success_url or the object's get_absolute_url(). Set fields explicitly.
Like CreateView but bound to an existing object. Restrict get_queryset() so users can only edit what they own.
Shows a confirmation page on GET and deletes on POST. Since Django 4.0 it uses FormMixin, so put custom delete logic in form_valid().
Django renders HTML through pluggable template engines configured in TEMPLATES: the Django Template Language by default, or Jinja2. Templates receive a context dict from the view and autoescape output to prevent XSS.
The Django Template Language is deliberately limited: it displays data and does light presentation logic, not business rules. Four constructs — variables, filters, tags and comments — cover it.
{{ post.title }} resolves by dictionary lookup, attribute, list index, then calling a no-argument method. Missing values render as empty strings (or string_if_invalid), not errors.
Transform values with {{ value|date:"Y-m-d" }}, |default, |truncatewords. Write your own in a templatetags module with @register.filter, minding autoescaping and mark_safe.
{% ... %} constructs for logic and output such as {% url %}, {% csrf_token %} and {% include %}. Custom ones use @register.simple_tag or @register.inclusion_tag.
{% for item in items %} loops with forloop.counter, forloop.first and forloop.last, and an {% empty %} branch for empty sequences.
{% if %}, {% elif %}, {% else %} with and, or, not, comparisons and in. Keep conditions simple; complex checks belong in the view or a model method.
Single-line {# ... #} or multi-line {% comment %}...{% endcomment %}; unlike HTML comments they never reach the browser.
A base template defines the page skeleton with {% block %} placeholders; children start with {% extends "base.html" %} and fill blocks, using {{ block.super }} to keep the parent's content. Combine with {% include %} for small reusable fragments.
A model is a Python class describing a table: each attribute is a field, and the Meta class sets ordering, constraints, indexes and verbose names. Models are the single source of truth for your schema.
Fields define the column type, Python type, validation and default form widget at once. Pick types carefully: changing them later means a data migration.
CharField, TextField, IntegerField, DecimalField for money, DateTimeField (timezone-aware when USE_TZ), BooleanField, JSONField, UUIDField, FileField and more.
null controls the database, blank controls validation; plus default, unique, choices, db_index, validators and help_text. Avoid null=True on string fields.
Subclass Field (or an existing field) and implement from_db_value(), to_python(), get_prep_value() and deconstruct() for migrations, to store types Django lacks.
ForeignKey for many-to-one (always set on_delete), ManyToManyField with an optional through model for extra data, and OneToOneField for extensions such as profiles. related_name controls the reverse accessor.
Put row-level behaviour on the model: __str__() for readable output, get_absolute_url() for canonical links, properties for derived values, and overridden save() or clean() when needed. Table-level queries belong on custom managers and QuerySets.
Three styles: abstract base classes share fields without their own table, multi-table inheritance creates a joined table per class (and implicit joins), and proxy models change Python behaviour only. Abstract bases are usually what you want.
The DATABASES setting picks an engine and connection details; many projects parse a single DATABASE_URL with dj-database-url. Tune CONN_MAX_AGE for persistent connections and keep credentials in the environment.
The default: a single file, zero setup, perfect for learning and tests. Recent releases make it viable for small production sites with WAL mode, but concurrency is limited.
The best-supported production choice, with extras in django.contrib.postgres such as ArrayField, full-text search and specialised indexes. Use the psycopg driver.
Supported with the mysqlclient driver. Use InnoDB and utf8mb4, and be aware MySQL cannot run DDL inside transactions, so a failed migration can leave partial changes.
Uses the same backend as MySQL with its own minimum supported version; behaviour is close to MySQL including the non-transactional DDL caveat.
makemigrations writes schema changes detected from models; migrate applies them and records them in django_migrations. Use RunPython for data migrations, sqlmigrate to inspect SQL, and squash long histories when they slow down tests.
QuerySets are lazy, chainable and evaluated only when iterated, sliced or counted. The ORM covers almost every query, but you must watch how many SQL statements a page really runs.
Model.objects.all(), filter(), exclude(), get(), order_by(), values() and slicing. get() raises DoesNotExist or MultipleObjectsReturned, so handle both.
objects.create(), save() with update_fields, get_or_create(), update_or_create(), and bulk update(), bulk_create() and delete(). Bulk operations skip save() and signals.
Double-underscore lookups like title__icontains, created__gte and author__name that span relations. Combine conditions with Q objects and reference columns with F expressions.
aggregate() returns a single dict (Avg, Sum, Count); annotate() adds a computed value per row, often combined with values() for GROUP BY.
Model.objects.raw() maps rows to models; connection.cursor() runs anything. Always pass parameters separately, never via string formatting, to avoid SQL injection.
Wrap related writes in transaction.atomic(), consider ATOMIC_REQUESTS, lock rows with select_for_update(), and defer side effects such as emails with transaction.on_commit().
Kill N+1 queries with select_related() for foreign keys and prefetch_related() for reverse and many-to-many, fetch less with only(), and add indexes in Meta.indexes.
Serialized data files loaded with loaddata and created with dumpdata, useful for seed data and tests. Factories (factory_boy) are often easier to maintain for tests.
Django forms take untrusted input, validate and clean it into Python values, and render HTML widgets with error messages. They are the standard gate between request data and your models.
Declare a forms.Form with fields, bind it to request.POST, check is_valid() and read cleaned_data. Use the POST/redirect/GET pattern after success.
ModelForm builds fields from a model; list fields explicitly so new model fields are never exposed by accident, then call save() (with commit=False to adjust first).
Validation runs field to_python() and validators, then clean_<field>() methods, then clean() for cross-field rules. Raise ValidationError or call add_error().
CsrfViewMiddleware rejects unsafe requests without a valid token; include {% csrf_token %} in forms and send the X-CSRFToken header from JavaScript. Use csrf_exempt only with care.
django.contrib.staticfiles finds assets in app static/ folders and STATICFILES_DIRS; collectstatic copies them to STATIC_ROOT. In production use hashed filenames through the STORAGES setting so caches can be long-lived.
Middleware that lets the Python app serve its own compressed, cache-busted static files, removing the need for Nginx or a CDN on simple deployments.
Paginator splits a queryset into pages and page.has_next() and friends drive the template controls; ListView wires it up via paginate_by. For very large tables, OFFSET gets slow — switch to keyset (cursor) pagination.
One-time flash notifications stored across a redirect: messages.success(request, "Saved") in the view, a loop over messages in the base template. Storage can be cookie- or session-based.
python manage.py shell opens Python with settings loaded, ideal for trying queries and fixing data; recent versions auto-import your models. django-extensions' shell_plus adds more conveniences.
An automatic CRUD interface generated from your models, enabled by django.contrib.admin; create a login with createsuperuser. It is built for trusted staff, not as a public-facing UI.
A ModelAdmin sets list_display, list_filter, search_fields, readonly_fields, inlines and custom actions. Add list_select_related to avoid slow changelists.
Hooks that wrap every request and response, listed in MIDDLEWARE and run top-down on the way in and bottom-up on the way out. Built-ins handle security headers, sessions, CSRF, auth and clickjacking protection.
Write a callable that takes get_response and returns a function handling the request, or implement process_view() and process_exception() hooks. Order relative to the built-ins matters.
django.contrib.auth provides users, password hashing, sessions and login/logout views; request.user is available everywhere. Protect views with @login_required or LoginRequiredMixin.
The default User has username, email, names, password hash and is_staff/is_superuser flags, with ready-made views and forms for login and password reset.
Set AUTH_USER_MODEL to your own AbstractUser subclass at the very start of a project — switching later is painful. Always reference users via get_user_model() or settings.AUTH_USER_MODEL.
A popular package adding signup, email verification, social logins (OAuth providers), MFA and account management on top of Django auth.
Deciding what an authenticated user may do. Django ships model-level permissions and groups; object-level rules need your own checks or a package such as django-guardian.
Every model gets add, change, delete and view permissions, assigned to users or groups and checked with user.has_perm("app.change_post"), @permission_required or PermissionRequiredMixin.
The standard toolkit for building JSON APIs on Django, with serializers, authentication and permission classes, throttling, pagination and a browsable API. It builds on Django's ORM and auth rather than replacing them.
Convert model instances to JSON-ready data and validate incoming payloads. ModelSerializer infers fields; nested writes and SerializerMethodField need explicit handling.
APIView and generic views like ListCreateAPIView handle single endpoints; a ModelViewSet bundles list, create, retrieve, update and destroy into one class.
DefaultRouter and SimpleRouter generate URL patterns for viewsets automatically; add extra routes with the @action decorator.
A lighter alternative to DRF inspired by FastAPI: type-hinted function endpoints, Pydantic schemas for validation, automatic OpenAPI docs and async support. Good for new API-first projects.
Django uses Python's logging module, configured through the LOGGING dict in settings. Log with logging.getLogger(__name__) and route django.request errors somewhere you will actually see them.
Named entry points arranged in a dot-separated hierarchy (myapp.payments) with a level; messages propagate to parent loggers unless propagate is false.
Decide where records go: console, files, rotating files, email to admins with AdminEmailHandler, or an external service. Each has its own level.
Extra checks that drop or enrich records, e.g. Django's RequireDebugFalse so error emails only send in production.
Format strings that turn records into text, with fields like %(asctime)s %(levelname)s %(name)s. Use JSON formatting when logs are shipped to an aggregator.
With DEBUG = True Django shows detailed error pages with tracebacks and local variables. Combine them with a real debugger and query inspection tools; never leave DEBUG on in production.
In production, provide 404.html and 500.html templates (and handler404/handler500 if you need custom views). Configure ADMINS or an error tracker to learn about 500s.
django-debug-toolbar adds a panel to each page listing SQL queries with timings and duplicates, templates, cache calls, signals and settings — the fastest way to spot N+1 queries.
Drop breakpoint() into code to pause the dev server in Python's debugger; step with n, s, c and inspect variables. ipdb adds IPython's completion and colours.
A profiling tool that records requests, SQL queries and optional cProfile data to the database and shows them in its own UI, useful for staging environments.
Django extends unittest with a test runner that creates a throwaway database, a test Client for making requests, and assertions for templates, redirects and query counts. Run with python manage.py test.
django.test.TestCase wraps each test in a transaction that rolls back; setUpTestData() creates shared data once per class. Use assertNumQueries to guard against query regressions.
pytest-django lets you write plain assert-style tests with fixtures such as client, db and django_user_model; many teams prefer it for its fixtures and plugins.
Features you reach for once the basics are solid: work outside the request cycle, async views, caching and internationalisation. Each solves real scaling or product problems but adds moving parts.
Configure CACHES with Redis or Memcached, then cache per view (@cache_page), template fragments ({% cache %}) or arbitrary values with the low-level cache.get/cache.set API.
Decoupled notifications such as post_save and pre_delete, connected with @receiver. Handy for cross-app hooks, but they hide control flow and do not fire for bulk operations.
Mark strings with gettext/gettext_lazy and {% translate %}, extract them with makemessages, compile with compilemessages, and add LocaleMiddleware. Format dates and numbers per locale.
async def views run under ASGI servers; the ORM offers async methods like aget() and acount(). Wrap sync-only code with sync_to_async and keep blocking calls off the event loop.
Move slow work — emails, image processing, third-party calls — out of the request. Django 6.0 adds a built-in Tasks framework that defines and enqueues tasks, with a separate worker backend actually running them.
The established distributed task queue: tasks are queued through a broker (Redis or RabbitMQ) and run by worker processes, with retries and periodic jobs through Celery Beat.
Production Django runs behind a WSGI server like Gunicorn (or an ASGI server for async), with a reverse proxy or platform handling TLS and static files, environment-based settings, and migrations run as a deploy step.
Set DEBUG = False, a secret SECRET_KEY, ALLOWED_HOSTS, HTTPS-only cookies and HSTS, then run python manage.py check --deploy to catch what you missed.