Django Advanced
This chapter explains the extension points around Django's request and model lifecycles and shows how to connect them safely to Celery, Redis-backed Channels, monitoring, and management automation.
- Explain Signals by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Middleware by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom management commands by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Celery integration by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Django Channels (WebSockets) by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Django Advanced, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the framework learning arc appropriate to this subject.
The problem this chapter solves
This chapter explains the extension points around Django's request and model lifecycles and shows how to connect them safely to Celery, Redis-backed Channels, monitoring, and management automation.
It removes repeated infrastructure work and gives teams conventions for evolving a database-backed product safely. DRF extends the same model to HTTP APIs.
Learning outcomes
- Explain Signals by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Middleware by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom management commands by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Celery integration by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Django Channels (WebSockets) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
A server adapts an HTTP or ASGI event into HttpRequest, middleware wraps the request in configured order, URL resolution selects a view, the view coordinates forms or serializers and lazy QuerySets, and a response unwinds through middleware. The ORM compiles QuerySet expressions into parameterized SQL; evaluation materializes model instances and may populate relation caches. In Django Advanced, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Django loads settings, initializes the app registry, composes middleware, and registers URL patterns before accepting the request.
- The URL resolver selects a view; authentication, permission, form, or serializer code converts untrusted request data into validated Python values.
- The view or service constructs a lazy QuerySet or enters a transaction; SQL is generated, planned by PostgreSQL, executed, and mapped back into model or projection values.
- On success the transaction commits and the response is rendered or serialized; on failure it rolls back and Django's exception path produces the documented error contract.
- Middleware unwinds around the response, while tests assert status, body, durable rows, query count, permissions, and any on-commit asynchronous handoff.
Memory and performance lens
Django model instances and serializer data are ordinary Python heap objects scoped to a request unless cached. QuerySets are lazy and hold a query plan, not rows, until evaluated. Careless list conversion, prefetching, or template iteration can materialize large result sets and create high per-worker memory pressure. For Django Advanced, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Django Advanced, measure request p50/p95/p99, validation failures, database query count, pool saturation, response size, and error rate by contract rather than optimizing from source-code appearance.
1. Signals
The Signals unit begins with pre/post_save, pre/post_delete, m2m_changed: Signals broadcast lifecycle events inside a process so loosely coupled handlers can react. Use signals sparingly for secondary effects and make receivers idempotent. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Signals
| Concept | Meaning | Engineering decision |
|---|---|---|
| pre/post_save, pre/post_delete, m2m_changed | Signals broadcast lifecycle events inside a process so loosely coupled handlers can react. | Use signals sparingly for secondary effects and make receivers idempotent. |
| @receiver decorator vs connect() | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| infinite loop prevention (update_fields guard) | Signals broadcast lifecycle events inside a process so loosely coupled handlers can react. | Use signals sparingly for secondary effects and make receivers idempotent. |
Follow the request through the framework: Signals
pre/post_save, pre/post_delete, m2m_changed. Django dispatches to registered receivers; transaction state is still in the caller. transaction.on_commit delays external work until the write commits.
@receiver decorator vs connect(). Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
infinite loop prevention (update_fields guard). Django dispatches to registered receivers; transaction state is still in the caller. transaction.on_commit delays external work until the write commits.
Read these as one system: pre/post_save, pre/post_delete, m2m_changed establishes the starting contract, @receiver decorator vs connect() changes how that contract is executed or represented, and infinite loop prevention (update_fields guard) exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Signals
1@transaction.atomic2def pre_post_save_pre_post_delete_m2m_changed(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_pre_post_save_pre_post_delete_m2m_changed(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Signals slice makes pre/post_save, pre/post_delete, m2m_changed observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward infinite loop prevention (update_fields guard), predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Signals
| Risk | Why it matters |
|---|---|
| pre/post_save, pre/post_delete, m2m_changed | Recursive saves, hidden control flow, and work published before commit cause subtle failures. |
| @receiver decorator vs connect() | Keep retries bounded and restricted to transient, idempotent operations. |
| infinite loop prevention (update_fields guard) | Recursive saves, hidden control flow, and work published before commit cause subtle failures. |
Framework lab: Signals
- Foundation: implement or demonstrate pre/post_save, pre/post_delete, m2m_changed with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine pre/post_save, pre/post_delete, m2m_changed with @receiver decorator vs connect(). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for infinite loop prevention (update_fields guard). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Middleware
The Middleware unit begins with middleware order and onion model: Middleware wraps every request and response to apply cross-cutting policy at a controlled boundary. Use it for correlation, security headers, timing, and protocol-level concerns. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Middleware
| Concept | Meaning | Engineering decision |
|---|---|---|
| middleware order and onion model | Middleware wraps every request and response to apply cross-cutting policy at a controlled boundary. | Use it for correlation, security headers, timing, and protocol-level concerns. |
| class-based middleware | Middleware wraps every request and response to apply cross-cutting policy at a controlled boundary. | Use it for correlation, security headers, timing, and protocol-level concerns. |
| RequestLoggingMiddleware/CorrelationIDMiddleware | Middleware wraps every request and response to apply cross-cutting policy at a controlled boundary. | Use it for correlation, security headers, timing, and protocol-level concerns. |
Follow the request through the framework: Middleware
middleware order and onion model. Request processing follows configured order inward; response and exception handling unwind outward. ASGI middleware passes scope and send/receive callables.
class-based middleware. Request processing follows configured order inward; response and exception handling unwind outward. ASGI middleware passes scope and send/receive callables.
RequestLoggingMiddleware/CorrelationIDMiddleware. Request processing follows configured order inward; response and exception handling unwind outward. ASGI middleware passes scope and send/receive callables.
Read these as one system: middleware order and onion model establishes the starting contract, class-based middleware changes how that contract is executed or represented, and RequestLoggingMiddleware/CorrelationIDMiddleware exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Middleware
1@transaction.atomic2def middleware_order_and_onion_model(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_middleware_order_and_onion_model(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Middleware slice makes middleware order and onion model observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward RequestLoggingMiddleware/CorrelationIDMiddleware, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Middleware
| Risk | Why it matters |
|---|---|
| middleware order and onion model | Order matters; broad exception swallowing and body buffering can break streaming. |
| class-based middleware | Order matters; broad exception swallowing and body buffering can break streaming. |
| RequestLoggingMiddleware/CorrelationIDMiddleware | Order matters; broad exception swallowing and body buffering can break streaming. |
Framework lab: Middleware
- Foundation: implement or demonstrate middleware order and onion model with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine middleware order and onion model with class-based middleware. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for RequestLoggingMiddleware/CorrelationIDMiddleware. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Custom management commands
The Custom management commands unit begins with BaseCommand/handle()/add_arguments(): A management command runs application-aware administrative work through a testable command interface. Make reruns safe, support dry-run and batching, and emit progress. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Custom management commands
| Concept | Meaning | Engineering decision |
|---|---|---|
| BaseCommand/handle()/add_arguments() | A management command runs application-aware administrative work through a testable command interface. | Make reruns safe, support dry-run and batching, and emit progress. |
| tqdm progress bars | A management command runs application-aware administrative work through a testable command interface. | Make reruns safe, support dry-run and batching, and emit progress. |
| expire_old_listings example | A management command runs application-aware administrative work through a testable command interface. | Make reruns safe, support dry-run and batching, and emit progress. |
Follow the request through the framework: Custom management commands
BaseCommand/handle()/add_arguments(). Django discovers command modules in installed apps and initializes the same settings and app registry used by the server.
tqdm progress bars. Django discovers command modules in installed apps and initializes the same settings and app registry used by the server.
expire_old_listings example. Django discovers command modules in installed apps and initializes the same settings and app registry used by the server.
Read these as one system: BaseCommand/handle()/add_arguments() establishes the starting contract, tqdm progress bars changes how that contract is executed or represented, and expire_old_listings example exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Custom management commands
1@transaction.atomic2def basecommand_handle_add_arguments(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_basecommand_handle_add_arguments(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Custom management commands slice makes BaseCommand/handle()/add_arguments() observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward expire_old_listings example, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Custom management commands
| Risk | Why it matters |
|---|---|
| BaseCommand/handle()/add_arguments() | Do not load an unbounded table into memory or make partial failure impossible to resume. |
| tqdm progress bars | Do not load an unbounded table into memory or make partial failure impossible to resume. |
| expire_old_listings example | Do not load an unbounded table into memory or make partial failure impossible to resume. |
Framework lab: Custom management commands
- Foundation: implement or demonstrate BaseCommand/handle()/add_arguments() with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine BaseCommand/handle()/add_arguments() with tqdm progress bars. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for expire_old_listings example. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Celery integration
The Celery integration unit begins with CELERY_BROKER_URL/RESULT_BACKEND setup: The broker transports work; the result backend stores task metadata or return values. They solve different problems. Expire unneeded results and encrypt or avoid sensitive payloads. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Celery integration
| Concept | Meaning | Engineering decision |
|---|---|---|
| CELERY_BROKER_URL/RESULT_BACKEND setup | The broker transports work; the result backend stores task metadata or return values. They solve different problems. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| @shared_task decorator | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| Flower monitoring | Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. | Alert on sustained backlog age and failure rate, not on a single retry. |
| Celery Beat crontab | Beat is a scheduler that publishes due tasks; workers still execute them. | Make periodic tasks idempotent and protect against overlapping runs. |
| autoretry_for + exponential backoff | Retries repeat a failed operation after a controlled delay; idempotency makes repeated attempts produce one logical effect. | Retry transient failures only and cap attempts and total age. |
Follow the request through the framework: Celery integration
CELERY_BROKER_URL/RESULT_BACKEND setup. Delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record.
@shared_task decorator. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
Flower monitoring. Workers emit an event stream when enabled; exporters translate broker and process state into metrics.
Celery Beat crontab. Only one active scheduler should own a schedule unless the scheduler itself coordinates leadership. Database schedulers turn rows into publish decisions.
autoretry_for + exponential backoff. Exponential backoff increases delay and jitter prevents synchronized retry storms. A stable operation key or database constraint deduplicates effects.
Read these as one system: CELERY_BROKER_URL/RESULT_BACKEND setup establishes the starting contract, @shared_task decorator changes how that contract is executed or represented, and autoretry_for + exponential backoff exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Celery integration
1@transaction.atomic2def celery_broker_url_result_backend_setup(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_celery_broker_url_result_backend_setup(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Celery integration slice makes CELERY_BROKER_URL/RESULT_BACKEND setup observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward autoretry_for + exponential backoff, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Celery integration
| Risk | Why it matters |
|---|---|
| CELERY_BROKER_URL/RESULT_BACKEND setup | Do not use a result backend as the only system of record. |
| @shared_task decorator | Keep retries bounded and restricted to transient, idempotent operations. |
| Flower monitoring | Event monitoring adds overhead and may be incomplete; reconcile with domain records. |
| Celery Beat crontab | Multiple beat instances can duplicate work. |
| autoretry_for + exponential backoff | Retrying validation errors or non-idempotent external writes can amplify damage. |
Framework lab: Celery integration
- Foundation: implement or demonstrate CELERY_BROKER_URL/RESULT_BACKEND setup with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine CELERY_BROKER_URL/RESULT_BACKEND setup with @shared_task decorator. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for autoretry_for + exponential backoff. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Django Channels (WebSockets)
The Django Channels (WebSockets) unit begins with ASGI vs WSGI: WebSockets create a long-lived bidirectional connection; Channels maps ASGI events to consumers and uses a channel layer for cross-process fan-out. Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Django Channels (WebSockets)
| Concept | Meaning | Engineering decision |
|---|---|---|
| ASGI vs WSGI | WebSockets create a long-lived bidirectional connection; Channels maps ASGI events to consumers and uses a channel layer for cross-process fan-out. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
| channel layers with Redis | WebSockets create a long-lived bidirectional connection; Channels maps ASGI events to consumers and uses a channel layer for cross-process fan-out. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
| WebSocketConsumer: connect/disconnect/receive | WebSockets create a long-lived bidirectional connection; Channels maps ASGI events to consumers and uses a channel layer for cross-process fan-out. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
| Groups and broadcasting | WebSockets create a long-lived bidirectional connection; Channels maps ASGI events to consumers and uses a channel layer for cross-process fan-out. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
Follow the request through the framework: Django Channels (WebSockets)
ASGI vs WSGI. A handshake upgrades HTTP, a consumer joins groups, Redis routes group messages to process-local connections, and disconnect cleanup removes presence state.
channel layers with Redis. A handshake upgrades HTTP, a consumer joins groups, Redis routes group messages to process-local connections, and disconnect cleanup removes presence state.
WebSocketConsumer: connect/disconnect/receive. A handshake upgrades HTTP, a consumer joins groups, Redis routes group messages to process-local connections, and disconnect cleanup removes presence state.
Groups and broadcasting. A handshake upgrades HTTP, a consumer joins groups, Redis routes group messages to process-local connections, and disconnect cleanup removes presence state.
Read these as one system: ASGI vs WSGI establishes the starting contract, channel layers with Redis changes how that contract is executed or represented, and Groups and broadcasting exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Django Channels (WebSockets)
1@transaction.atomic2def asgi_vs_wsgi(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_asgi_vs_wsgi(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Django Channels (WebSockets) slice makes ASGI vs WSGI observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Groups and broadcasting, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Django Channels (WebSockets)
| Risk | Why it matters |
|---|---|
| ASGI vs WSGI | Never assume one process owns every room or trust a room identifier supplied by the client. |
| channel layers with Redis | Never assume one process owns every room or trust a room identifier supplied by the client. |
| WebSocketConsumer: connect/disconnect/receive | Never assume one process owns every room or trust a room identifier supplied by the client. |
| Groups and broadcasting | Never assume one process owns every room or trust a room identifier supplied by the client. |
Framework lab: Django Channels (WebSockets)
- Foundation: implement or demonstrate ASGI vs WSGI with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine ASGI vs WSGI with channel layers with Redis. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Groups and broadcasting. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1# signals.py2from django.db import transaction3from django.db.models.signals import post_save4from django.dispatch import receiver5
6@receiver(post_save, sender=Task)7def publish_assignment(sender, instance: Task, created: bool, **kwargs):8 if not instance.assignee_id:9 return10 transaction.on_commit(11 lambda: notify_assignment.delay(str(instance.pk), instance.assignee_id)12 )13
14# tasks.py15@shared_task(autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=5)16def notify_assignment(task_id: str, user_id: int) -> None:17 notification, created = Notification.objects.get_or_create(18 event_key=f"task-assigned:{task_id}:{user_id}",19 defaults={"user_id": user_id, "message": "A task was assigned"},20 )21 if created:22 send_realtime(notification)Expected result
1After commit, one idempotent notification is stored and broadcast; transient failures retry.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | # signals.py | Implements the next python statement in the example's data flow. |
| 2 | from django.db import transaction | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | from django.db.models.signals import post_save | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | from django.dispatch import receiver | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 6 | @receiver(post_save, sender=Task) | Applies a decorator or framework annotation before the following definition is bound. |
| 7 | def publish_assignment(sender, instance: Task, created: bool, **kwargs): | Defines a function; its parameters form the explicit input boundary. |
| 8 | if not instance.assignee_id: | Evaluates the condition and enters this branch only when it is truthy. |
| 9 | return | Returns the observable result to the caller and ends this invocation. |
| 10 | transaction.on_commit( | Implements the next python statement in the example's data flow. |
| 11 | lambda: notify_assignment.delay(str(instance.pk), instance.assignee_id) | Implements the next python statement in the example's data flow. |
| 12 | ) | Implements the next python statement in the example's data flow. |
| 14 | # tasks.py | Implements the next python statement in the example's data flow. |
| 15 | @shared_task(autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=5) | Applies a decorator or framework annotation before the following definition is bound. |
| 16 | def notify_assignment(task_id: str, user_id: int) -> None: | Defines a function; its parameters form the explicit input boundary. |
| 17 | notification, created = Notification.objects.get_or_create( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 18 | event_key=f"task-assigned:{task_id}:{user_id}", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 19 | defaults={"user_id": user_id, "message": "A task was assigned"}, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 20 | ) | Implements the next python statement in the example's data flow. |
| 21 | if created: | Evaluates the condition and enters this branch only when it is truthy. |
| 22 | send_realtime(notification) | Implements the next python statement in the example's data flow. |
Step-by-step execution
- Django loads settings, initializes the app registry, composes middleware, and registers URL patterns before accepting the request.
- The URL resolver selects a view; authentication, permission, form, or serializer code converts untrusted request data into validated Python values.
- The view or service constructs a lazy QuerySet or enters a transaction; SQL is generated, planned by PostgreSQL, executed, and mapped back into model or projection values.
- On success the transaction commits and the response is rendered or serialized; on failure it rolls back and Django's exception path produces the documented error contract.
- Middleware unwinds around the response, while tests assert status, body, durable rows, query count, permissions, and any on-commit asynchronous handoff.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Signals | Recursive saves, hidden control flow, and work published before commit cause subtle failures. | Use signals sparingly for secondary effects and make receivers idempotent. |
| Middleware | Order matters; broad exception swallowing and body buffering can break streaming. | Use it for correlation, security headers, timing, and protocol-level concerns. |
| Custom management commands | Do not load an unbounded table into memory or make partial failure impossible to resume. | Make reruns safe, support dry-run and batching, and emit progress. |
| Celery integration | Do not use a result backend as the only system of record. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| Django Channels (WebSockets) | Never assume one process owns every room or trust a room identifier supplied by the client. | Authenticate during connection establishment and design reconnect, heartbeat, and backpressure behavior. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Real-time Notifications project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Signals: pre/post_save, pre/post_delete, m2m_changed
- To do: Signals: @receiver decorator vs connect()
- To do: Signals: infinite loop prevention (update_fields guard)
- To do: Middleware: middleware order and onion model
- To do: Middleware: class-based middleware
- To do: Middleware: RequestLoggingMiddleware/CorrelationIDMiddleware
- To do: Custom management commands: BaseCommand/handle()/add_arguments()
- To do: Custom management commands: tqdm progress bars
- To do: Custom management commands: expire_old_listings example
- To do: Celery integration: CELERY_BROKER_URL/RESULT_BACKEND setup
- To do: Celery integration: @shared_task decorator
- To do: Celery integration: Flower monitoring
- To do: Celery integration: Celery Beat crontab
- To do: Celery integration: autoretry_for + exponential backoff
- To do: Django Channels (WebSockets): ASGI vs WSGI
- To do: Django Channels (WebSockets): channel layers with Redis
- To do: Django Channels (WebSockets): WebSocketConsumer: connect/disconnect/receive
- To do: Django Channels (WebSockets): Groups and broadcasting
Quick revision
- Signals: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Middleware: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Custom management commands: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Celery integration: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Django Channels (WebSockets): connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?