---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Django 6's django.tasks framework

How does Django 6's built-in `django.tasks` separate task definition from execution backend, and what actually runs when you call `Task.enqueue` under `ImmediateBackend` vs. `DummyBackend`?

For fifteen years, every Django project had to couple its application code directly to Celery, RQ, Dramatiq, or Huey — making even reusable Django apps unable to enqueue background work without hard-coding a third-party broker API. Starting in Django `6.0` (refined in `6.1`), Django ships **`django/tasks/`**: a standardized task definition, validation, and result protocol backed by pluggable execution backends configured in `"settings.TASKS"` — using the exact same `BaseConnectionHandler` architecture as `DATABASES` and `CACHES`!

## `TaskBackendHandler`, `@task`, and frozen `Task` validation

Open `TaskBackendHandler` (`django/tasks/__init__.py:TaskBackendHandler`): it subclasses `BaseConnectionHandler` with `"settings_name = 'TASKS'"`, exposing `task_backends` and `default_task_backend` (a `ConnectionProxy` to alias `"default"`).

When `"desk/"`'s `"newsroom/tasks.py"` decorates `"build_edition_digest"` with `task` (`django/tasks/base.py:task`):

```python
@task(queue_name="default", priority=0)
def build_edition_digest(edition_id: int) -> dict[str, object]:
    ...
```

Django wraps the function into a frozen, slotted dataclass **`Task`** (`django/tasks/base.py:Task`). Look closely at `Task.__post_init__` (`django/tasks/base.py:Task.__post_init__`) and `BaseTaskBackend.validate_task` (`django/tasks/backends/base.py:BaseTaskBackend.validate_task`):

1. **Module-level importability check:** `validate_task` immediately rejects nested or local functions (`InvalidTask: "Task function must be defined at a module level."`) so external worker processes can always resolve `Task.module_path` via `import_string`!
2. **Backend capability checks:** `validate_task` checks whether the configured backend supports `priority`, `run_after` (`supports_defer`), or `async def` coroutines (`supports_async_task`), failing fast at definition or enqueue time instead of silently ignoring options! Notice too that `@task` explicitly forbids passing a static `"run_after"` at decoration time (`TypeError`) — scheduling a deferred run must be done dynamically per invocation via `Task.using` (`"build_edition_digest.using(priority=5, run_after=...)"`, which returns a new frozen `Task` via `dataclasses.replace`!).
3. **JSON normalization on arguments and return values:** Calling `Task.enqueue` (`django/tasks/base.py:Task.enqueue`) constructs a frozen **`TaskResult`** (`django/tasks/base.py:TaskResult`) whose `__post_init__` passes `args` and `kwargs` through `normalize_json` (`django/utils/json.py:normalize_json`)! That means even when running locally on `ImmediateBackend`, passing an unserializable ORM model instance (like `"build_edition_digest.enqueue(edition)"` instead of `"edition.pk"`) fails *immediately in development* rather than crashing later on a production broker!

## `TaskResultStatus`, `ImmediateBackend` vs. `DummyBackend`, and `on_commit`

Django `6.1` ships two built-in backends (leaving persistent queue storage and worker processes to external backends like database or Redis workers):

- **`ImmediateBackend` (`django/tasks/backends/immediate.py:ImmediateBackend`):** Default development backend (used by `"desk/"`). Inside `ImmediateBackend.enqueue` → `_execute_task`, it constructs a `TaskResult` with status `TaskResultStatus.READY` (`django/tasks/base.py:TaskResultStatus`), sends `task_enqueued` (`django/tasks/signals.py:task_enqueued`), transitions status to `RUNNING`, appends `ImmediateBackend.worker_id`, sends `task_started`, runs `Task.call` **synchronously right inside `enqueue()`**, normalizes the return value as JSON, and transitions to `SUCCESSFUL` (or catches any `BaseException` except `KeyboardInterrupt` into `TaskError` (`django/tasks/base.py:TaskError`), setting status `FAILED`!) before sending `task_finished`. Notice two vital contract details: **task exceptions do NOT propagate out of `enqueue()`**, and accessing `TaskResult.return_value` (`django/tasks/base.py:TaskResult.return_value`) raises `ValueError` unless status is `SUCCESSFUL` (cleanly distinguishing a failed or pending task from a successful task that returned `None`!).
- **`DummyBackend` (`django/tasks/backends/dummy.py:DummyBackend`):** Built for tests. `DummyBackend.enqueue` validates the task, appends the `READY` `TaskResult` to `"self.results"`, fires `task_enqueued`, and returns `copy.deepcopy(result)` without ever executing the function (`attempts == 0`), so tests can assert exact enqueued arguments and priorities via `"task_backends['default'].results"`.

```text figure=tasks-lifecycle
Django 6.1 django.tasks TaskResultStatus lifecycle and backend comparison on desk/

1. TaskResultStatus state machine (frozen dataclass + JSON normalization):
   @task def (validate_task: module-level) -> READY (enqueue, normalize_json, task_enqueued)
   -> RUNNING (task.call, worker_id, task_started)
   -> SUCCESSFUL (task_finished, JSON return_value) | FAILED (task_finished, TaskError, return_value raises)

2. ImmediateBackend vs DummyBackend & transaction.on_commit safety:
   ImmediateBackend: runs sync in enqueue() -> SUCCESSFUL (att=1, 4 stories); DoesNotExist -> FAILED (no raise!)
   DummyBackend:     never runs -> READY (att=0, stored=1, deepcopy returned)
   on_commit safety: rollback -> 0 queued | commit -> 1 queued
```

*Every status transition, error capture, and `on_commit` count is verified directly against `ch12-services`. Notice why pairing `Task.enqueue` with `django.db.transaction.on_commit` is non-negotiable in production: enqueueing directly inside `django.db.transaction.atomic` lets an external worker run before the database `"COMMIT"` finishes — or even after a `"ROLLBACK"`!*

Watch `"desk/"`'s `"build_edition_digest"` execute on `ImmediateBackend` (both success and `"Edition.DoesNotExist"` failure), queue cleanly on `DummyBackend` with `Task.using` (`"priority=5"`), and respect `django.db.transaction.on_commit` rollback safety live:

```text recording=ch12-services
4. Django 6.1 django.tasks: ImmediateBackend vs DummyBackend
  task_meta: name='build_edition_digest' queue='default' priority=0 backend=ImmediateBackend proxy=ConnectionProxy
  immediate_enqueue: status=SUCCESSFUL is_finished=True attempts=1 return_edition='2026-11-25' story_count=4
  immediate_failure: status=FAILED error_class='newsroom.models.Edition.DoesNotExist' return_value_raises='Task failed'
  dummy_backend: status=READY priority=5 attempts=0 stored=1
  on_commit_safety: queued_after_rollback=0 queued_after_commit=1
```

Notice line 21 (`"immediate_failure"`): `"build_edition_digest.enqueue(99999)"` returned cleanly with `status=FAILED` and `error_class='newsroom.models.Edition.DoesNotExist'`, and only reading `"res_fail.return_value"` raised `ValueError('Task failed')`!

With caching, signals, and tasks open, we turn to Django's fourth horizontal service — how `StorageHandler` and `FieldFile` decouple model attributes from filesystems and object stores without opening files prematurely — next in [Storage, FieldFile, and lazy file opening](storage.md).
