Learn Django

Batteries-included Python web framework: ORM, admin, auth, forms and templates

30 lessons · 6 hours · 4 levels · covers Django 6.0

Django is a full-stack Python web framework that ships with an ORM and migrations, an automatic admin, authentication, forms, templates, caching and security protections out of the box. Its conventions let teams build database-backed sites and APIs quickly and keep them maintainable for years. It powers sites such as Instagram and countless business applications.

Before you start

Django builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics9 lessons · 2 hours in total
2. PracticalUse it productively at work, with the usual idioms18 lessons · 4 hours in total
3. AdvancedThe less common features, performance and trade-offs26 lessons · 5 hours in total
4. ExpertInternals and the edge cases experts know30 lessons · 6 hours in total

The Django tree

DjangoProjects, apps and manage.pyProjects, apps andmanage.pyURLconfs and function viewsURLconfs andfunction viewsTemplates and the template languageTemplates and thetemplate languageStatic filesStatic filesDefining modelsDefining modelsMigrationsMigrationsQuerying with QuerySetsQuerying withQuerySetsRelationships: ForeignKey and ManyToManyRelationships:ForeignKey and Ma…The Django adminThe Django adminForms and validationForms and validationModelFormsModelFormsGeneric class-based viewsGeneric class-basedviewsAuthentication and permissionsAuthentication andpermissionsQ, F, annotate and aggregateQ, F, annotate andaggregateAvoiding N+1 queriesAvoiding N+1 queriesManagers, QuerySet methods and MetaManagers, QuerySetmethods and MetaSettings and environmentsSettings andenvironmentsTesting Django appsTesting Django appsModules and importsModules and importsVirtual environments and pipVirtual environmentsand pipCreating and altering tablesCreating and alteringtablesClasses and instancesClasses andinstancesFiltering rows with WHEREFiltering rows withWHEREInheritance, super() and compositionInheritance, super()and compositionAggregate functionsAggregate functionsGROUP BY and HAVINGGROUP BY andHAVING
Essentials and Practical shown (18 of 30 lessons); the full list is below. Click a lesson to read it.

All 30 lessons, in order

Projects, URLs and templates

  1. Projects, apps and manage.py · Essentials · 12 min

    Create a project with django-admin, add apps with startapp, register them in INSTALLED_APPS and run the dev server.

  2. URLconfs and function views · Essentials · 12 min

    Map URL patterns to view functions with path(), capture values with converters, name routes and reverse them.

  3. Templates and the template language · Essentials · 14 min

    Render HTML with render(), use variables, tags, filters and template inheritance, and organize templates per app.

  4. Static files · Essentials · 8 min

    Serve CSS, JavaScript and images with the staticfiles app, the {% static %} tag and collectstatic for production.

Models and the ORM

  1. Defining models · Essentials · 14 min

    Describe database tables as Python classes with typed fields, options like null, blank, default and choices, and __str__.

  2. Migrations · Essentials · 10 min

    Turn model changes into versioned migration files with makemigrations and apply them with migrate.

  3. Querying with QuerySets · Essentials · 14 min

    Create, read, update and delete rows with the ORM: filter, exclude, get, order_by, slicing and field lookups.

  4. Relationships: ForeignKey and ManyToMany · Essentials · 14 min

    Link models with ForeignKey, ManyToManyField and OneToOneField, choose on_delete, and query across relationships.

  5. The Django admin · Essentials · 12 min

    Register models in the admin and customize lists, filters, search, inlines and actions with ModelAdmin.

Forms, views and auth

  1. Forms and validation · Practical · 14 min

    Define Form classes, bind them to request.POST, validate with is_valid and clean methods, and render errors.

  2. ModelForms · Practical · 12 min

    Generate forms from models with ModelForm, save them to create or update rows, and list fields explicitly.

  3. Generic class-based views · Practical · 14 min

    Use ListView, DetailView, CreateView, UpdateView and DeleteView, customize them by overriding methods, and add mixins.

  4. Authentication and permissions · Practical · 14 min

    Log users in and out with Django's auth views, protect views with login_required, and check permissions and groups.

Querying in depth

  1. Q, F, annotate and aggregate · Practical · 15 min

    Build OR/NOT conditions with Q, reference columns with F, and compute per-row annotations and totals with Count, Sum and Avg.

  2. Avoiding N+1 queries · Practical · 12 min

    Load related objects efficiently with select_related and prefetch_related, and detect query explosions in tests.

  3. Managers, QuerySet methods and Meta · Practical · 12 min

    Add reusable query methods with custom QuerySets and managers, and declare indexes and constraints in Meta.

  4. Transactions and concurrency · Advanced · 14 min

    Group writes with transaction.atomic, run side effects with on_commit, and lock rows with select_for_update.

Settings and testing

  1. Settings and environments · Practical · 10 min

    Organize settings.py for development and production, read secrets from the environment, and access settings safely.

  2. Testing Django apps · Practical · 14 min

    Write tests with django.test.TestCase, the test Client and setUpTestData, and check responses, templates and query counts.

  3. Middleware · Advanced · 12 min

    Write middleware that wraps every request and response, understand ordering, and use the process_view and process_exception hooks.

  4. Signals · Advanced · 10 min

    React to model and request events with post_save and friends, register receivers in AppConfig.ready, and know when to avoid them.

  5. Custom user models · Advanced · 12 min

    Start projects with a custom user model, reference it via AUTH_USER_MODEL and get_user_model, and add email login.

Security and production

  1. Security features and hardening · Advanced · 15 min

    Use Django's protections against CSRF, XSS, SQL injection and clickjacking, enable HTTPS settings and a Content Security Policy.

  2. Caching · Advanced · 12 min

    Configure a cache backend such as Redis and cache data, views and template fragments, with a plan for invalidation.

  3. Background tasks · Advanced · 12 min

    Define tasks with Django 6.0's @task decorator, enqueue them, and choose a backend or a queue like Celery to run them.

  4. Deploying Django · Advanced · 14 min

    Serve Django with Gunicorn or an ASGI server behind a proxy, run collectstatic and migrations, and configure databases and logging.

Internals and async

  1. How QuerySets work · Expert · 15 min

    Understand QuerySet laziness, cloning, the result cache, SQL compilation and the multi-valued filter() gotcha.

  2. The request/response lifecycle · Expert · 14 min

    Trace a request through the handler, middleware chain, URL resolver, view and response rendering, and how errors become responses.

  3. Data migrations and zero-downtime changes · Expert · 15 min

    Write RunPython data migrations with historical models, and change schemas safely on live databases in several steps.

  4. Async views and the async ORM · Expert · 15 min

    Write async views and use the async ORM interface, bridge sync code with sync_to_async, and know the performance trade-offs.