Django Tutorial
Learn Django 5 and 6 from your first project to models, views, templates, forms, the admin, authentication, REST APIs, testing and deployment. 77 lessons with live examples, quizzes and projects.
Start learning →
of lessons completed
Getting Started
- Django Introduction Meet Django, the batteries-included Python web framework: the MTV pattern, the request and response cycle, what Django 5 and 6 add, and a first live view.
- Installing Django and Your First Project Install Django in a virtual environment, run startproject and startapp, learn what every generated file does, and start the development server.
- Projects, Apps and Settings Understand the difference between a Django project and an app, how INSTALLED_APPS and AppConfig work, and how to manage settings, DEBUG and secrets safely.
- The Request and Response Cycle Follow a request through WSGI or ASGI, middleware, the URL resolver and a view, and learn the HttpRequest and HttpResponse attributes you use every day.
URLs and Views
- URL Routing Learn Django URL routing: urlpatterns, path converters, re_path, include, namespaces, and how resolve() and reverse() map URLs to views and back.
- Function-Based Views Write Django function-based views: return HttpResponse and JsonResponse, raise Http404, redirect, use render and get_object_or_404, and restrict HTTP methods.
- Query Strings, Forms and Request Data Read query strings, form posts, uploaded files, headers, cookies and JSON bodies in Django views. Learn QueryDict, request.META and how to test it all with RequestFactory.
- Class-Based Views Learn how Django class-based views work. Write View subclasses, understand as_view() and dispatch(), use TemplateView and RedirectView, add mixins and choose between CBVs and FBVs.
- Generic Display and Editing Views Build list, detail, create, update and delete pages with Django's generic class-based views. Customize get_queryset, get_context_data, success_url and pagination.
- Error Pages and Exceptions Learn how Django turns exceptions into 404, 403 and 500 responses. Raise Http404 and PermissionDenied, write custom handler404 and handler500 views, and see DEBUG versus production.
Templates
- Django Templates Learn the Django template language. Render variables, apply filters, use if and for tags, write comments, understand autoescaping, and run templates with Engine and Context.
- Built-in Template Tags and Filters Catalog A practical catalog of Django's built-in template tags and filters: regroup, cycle, firstof, with, verbatim, lorem, widthratio, dictsort, filesizeformat, timesince and the in, is operators, all run live.
- Template Inheritance and Includes Stop repeating HTML. Learn Django's extends and block tags, block.super, include with parameters, template loaders and how to organize base templates in a project.
- Custom Template Tags and Filters Write your own Django template filters, simple tags and inclusion tags, load them with the load tag, and keep output safe with autoescape and format_html.
- Static Files and Media Learn how Django handles static files and uploads, from STATIC_URL and collectstatic to MEDIA_ROOT, FileField, the storage API and serving files in development.
Models and the ORM
- Models and Fields Learn how Django models map Python classes to database tables, with field types, field options, choices, Meta options, primary keys, table names and validation.
- Migrations Learn Django migrations: makemigrations and migrate, migration files, operations, dependencies, sqlmigrate, data migrations and squashing.
- QuerySets: Create, Read, Update, Delete Learn Django ORM basics: create, get, filter, exclude, update and delete rows, bulk operations, ordering, slicing and how lazy QuerySets decide when to query.
- Lookups, Q Objects and F Expressions Filter precisely with Django lookups such as __contains, __in and __range, combine conditions with Q objects, and compare or update columns with F expressions.
- Relationships: ForeignKey, ManyToMany, OneToOne Connect Django models with ForeignKey, ManyToManyField and OneToOneField, choose the right on_delete rule, use related_name and query across relations.
- Aggregation and Annotation Summarize data in the Django ORM with aggregate() and annotate(), group rows with values(), label them with Case/When, and use Subquery, Exists and Window.
- ORM Performance: N+1, select_related, prefetch_related Find and fix slow Django queries - count queries, remove the N+1 problem with select_related and prefetch_related, trim columns, stream rows and add indexes.
- Custom Managers, QuerySets and Model Methods Put query logic where it belongs in Django - write custom managers and chainable QuerySets, add model methods and properties, and enforce rules with Meta constraints.
- Transactions and Concurrency Keep Django data consistent with transaction.atomic, ATOMIC_REQUESTS and on_commit, avoid lost updates with F() and locking, and handle IntegrityError safely.
- Raw SQL, Database Functions and JSON Fields Go beyond basic ORM queries - run safe raw SQL, call database functions with Func and Concat, query JSONField keys, and use GeneratedField and db_default.
- Model Inheritance and Abstract Models Share fields and behavior between Django models with abstract base classes, multi-table inheritance, proxy models and mixins, and learn when each one fits.
- Databases: PostgreSQL, MySQL and Multiple Databases Configure Django for PostgreSQL or MySQL, connect to managed databases such as Amazon RDS, and use several databases with DATABASE_ROUTERS, using() and read replicas, with live examples.
- Django and NoSQL (MongoDB) Can Django use MongoDB? Learn what the ORM supports, the official MongoDB backend and other options, how JSONField gives document-style data in SQL, and when relational is the better choice.
Forms
- Django Forms Learn how Django forms define fields, validate user input, expose cleaned_data and errors, pick widgets, set initial values and render safely in templates.
- Django Form Field Reference A tour of Django's built-in form fields and their arguments (strip, empty_value, typed choices, FilePathField, RegexField, IP and duration fields) plus every way to render a form.
- Form Validation Write your own Django form validation with validators, clean_<field> methods, clean() for cross-field rules, ValidationError codes and add_error.
- ModelForms Build Django forms straight from models with ModelForm, customize fields and widgets, use save(commit=False), and edit related rows with inline formsets.
- Handling Forms in Views Handle Django forms in views with the GET/POST pattern, redirect after POST, CSRF protection, the messages framework, file uploads and FormView.
The Admin
- The Django Admin Get a working admin site from your models: create a superuser, register models, then tune the list with ModelAdmin, list_display, search_fields and list_filter.
- Customizing the Admin Shape the Django admin to your data: fieldsets, inlines, readonly fields, custom columns with @admin.display, bulk actions, permissions and template overrides.
Authentication and Security
- Users and Authentication Learn how Django authentication works: the User model, password hashing, authenticate(), login(), logout(), login_required and the built-in auth views.
- Custom User Models Replace Django's default User model the right way: AbstractUser vs AbstractBaseUser, AUTH_USER_MODEL, email login, a custom manager and why to decide early.
- Permissions, Groups and Authorization Control who can do what in Django: model permissions, has_perm(), groups, PermissionRequiredMixin, UserPassesTestMixin and patterns for object-level access.
- Sessions and Cookies Understand Django sessions and cookies: how request.session works, the session backends, signed cookies, cookie attributes and the settings that keep sessions safe.
- Security in Django See how Django defends against CSRF, XSS, SQL injection and clickjacking, which SECURE_* settings to turn on, and how to run the check --deploy checklist.
- Social Login with OAuth (Google) and django-allauth Add Sign in with Google to Django using django-allauth: how the OAuth 2.0 code flow works, how to get credentials, the settings you need, and a live run of the whole login.
Middleware, Signals and Internals
- Middleware Learn how Django middleware wraps every request: function and class middleware, execution order, process_view, exception handling and a timing example.
- Signals Learn Django signals: connect receivers to pre_save, post_save and m2m_changed, define custom signals, and know when explicit code is the better choice.
- Custom Management Commands Write your own manage.py commands with BaseCommand: add arguments and flags, print styled output, raise CommandError, test with call_command and schedule jobs.
- Caching Speed up Django with caching: configure backends, use get, set and get_or_set, cache whole views and template fragments, and invalidate stale data safely.
- Logging, Email and Internationalization Configure Django's LOGGING dict, send and test email with EmailMessage, translate text with gettext, and handle time zones correctly with USE_TZ.
- Internationalization and Localization in Depth Translate a Django site properly: gettext and lazy strings, plurals, template tags, makemessages and compilemessages, LocaleMiddleware, i18n_patterns URLs and localized formats.
- Sitemaps, RSS Feeds and robots.txt Help search engines and readers find your content: build sitemaps with django.contrib.sitemaps, RSS and Atom feeds with the syndication framework, a robots.txt, and use contrib.sites for domains.
- Useful contrib Apps: humanize, flatpages, redirects Use three small Django contrib apps: humanize for friendly numbers and dates, flatpages for editor-managed static pages, and redirects for moved URLs, each with a live example.
REST APIs
- Building JSON APIs with Plain Django Build a JSON API with plain Django: JsonResponse, serializing models, parsing request bodies, status codes, validation, pagination and consistent error responses.
- API Design, Versioning and CORS Design a clean HTTP API in Django: resource URLs, idempotent methods, filtering, sorting, pagination, URL versioning, bearer tokens and a CORS middleware.
- Django REST Framework Overview Understand Django REST Framework: serializers, APIView, ViewSets, routers, permissions, authentication and pagination, with runnable plain-Python stand-ins.
- DRF Serializers in Depth Learn Django REST Framework serializers properly: Serializer vs ModelSerializer vs HyperlinkedModelSerializer, field options, nesting, method fields and validation, all run live.
- DRF ViewSets, Routers and Generic Views Build REST endpoints with Django REST Framework generic views, ModelViewSet and DefaultRouter, add custom @action routes, search, ordering and pagination, with live runnable examples.
- DRF Authentication: Session, Token and JWT Secure a Django REST Framework API: how session, token and JWT authentication differ, how to set up TokenAuthentication and SimpleJWT obtain/refresh endpoints, and protect views.
- DRF Permissions and Object-Level Permissions Control who can do what in a Django REST Framework API: built-in permission classes, DjangoModelPermissions, DjangoObjectPermissions and a custom owner-only has_object_permission.
- Async Django Learn async Django: ASGI, async def views, the async ORM (aget, acreate, async for), sync_to_async, async middleware and where Channels fits in.
- Connecting Django with a React Frontend Connect a React frontend to a Django REST Framework API: CORS with django-cors-headers, fetch with token or session auth, CSRF rules, a Vite proxy and serving the built app.
Testing
- Testing Django Apps Write Django tests with TestCase, setUpTestData, the test Client, fixtures and assertions like assertContains, assertRedirects and assertNumQueries.
- Testing Patterns: Factories, Mocks and pytest-django Level up your Django tests with factory functions, unittest.mock for external services, override_settings, form and permission tests, pytest-django and coverage.
- Debugging Django Applications Find and fix Django bugs faster: read tracebacks, decode common errors (no such table, NoReverseMatch, TemplateDoesNotExist), use the debug 404 page, Debug Toolbar, the shell, breakpoint() and SQL logging.
Deployment and Production
- Deploying Django Deploy Django safely: the production checklist, environment variables, ALLOWED_HOSTS, Gunicorn or Uvicorn, Nginx, WhiteNoise static files, database settings and health checks.
- Docker, Celery and CI for Django Package Django in Docker, run Postgres, Redis, Celery workers and beat with Compose, and test every push with GitHub Actions. Includes a live task-queue stand-in.
- Performance and Scaling Make Django fast and keep it fast: profile first, count queries, add indexes and caches, pool database connections, use a CDN and move slow work to the background.
Projects
- Project: Blog Build a complete Django blog: posts with unique slugs, moderated comments, generic views, templates, the admin site and tests, running live in your browser.
- Project: Todo JSON API Build a Todo JSON API with plain Django: models, token authentication, input validation, per-user data, correct status codes and a test suite, all running live.
- Project: URL Shortener Build a URL shortener in Django: base62 codes, a redirect view, race-free click counting with F(), a cache in front of the database and a test suite.
- Project: Bookstore with Cart Build a Django bookstore: catalog models, a session-based shopping cart, checkout in a transaction that protects stock, aggregation reports and tests.
- Project: Polls App Build a complete Django polls app: Question and Choice models, a vote form, race-free voting with F(), results with annotate and a test suite. Run it live.
- Taking Payments with Stripe-Style Checkout and Webhooks Build a safe payment flow in Django: hosted checkout sessions, signed webhooks, order status, idempotent handlers and test mode, with a runnable gateway stand-in and real signature code.
- Project: Weather App Build a Django weather app that calls an external API: a service layer, a form, timeouts and error handling, caching, and tests with a fake HTTP client, all runnable in the browser.
- Project: Multi-Role Management System (HOD / Staff / Student) Build a multi-role Django system with a custom user model, role-based access mixins, attendance and results models and per-role dashboards, running on real migrations.
- Project: Word Counter and CGPA Calculator Build two small Django apps without a database: a word counter with a form and a CGPA calculator with a formset, learning validation, pure functions and tests.
Practice and Review
- Django Exercises with Solutions 18 graded Django exercises with runnable solutions: queries, aggregation, transactions, views, URLs, forms, authentication, middleware and tests.
- Common Django Mistakes Seven Django mistakes that bite every team, each with a live before and after: N+1 queries, shared defaults, circular imports, migration conflicts and more.
- Django Interview Questions 43 Django interview questions with answers on MTV, the ORM, migrations, middleware, signals, security, performance and async, with runnable examples.
- Django Cheat Sheet A one-page Django cheat sheet: manage.py commands, settings, URL converters, model fields, ORM lookups, template tags, form fields and test assertions.