ZetCode

Celery with Django

last modified November 21, 2026 Python 3.15

A view should answer quickly. Some work takes too long for a request: sending email through a slow mail server, calling other services, generating reports, or resizing images. Celery is a distributed task queue for Python: the application puts a message describing the work into a broker, such as Redis or RabbitMQ, and separate worker processes take the messages and run the tasks. The view returns as soon as the message is sent. In this article we connect Celery to a Django project, send tasks and read their results, retry tasks that fail, send tasks only after a database transaction commits, run periodic tasks with celery beat, and test the tasks. The examples use Celery 5.7, Django 6.1, and Python 3.15.

Django 6.0 added django.tasks (see Django tasks framework), an API for defining and enqueuing background tasks, but Django itself ships only backends for development and testing (one runs the task immediately, one only records it); a worker that runs tasks in the background comes from third-party packages. Celery is a complete, long-established solution with its own workers, retries, and scheduler.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django together with Celery and its Redis dependencies (the redis extra), generate the project with the configuration package config, start the app orders, and create the folder demos for demo scripts.

$ mkdir shop
$ cd shop
$ uv init --bare
$ uv add django 'celery[redis]'
$ uv run django-admin startproject config .
$ uv run python manage.py startapp orders
$ mkdir demos

The quotes around celery[redis] keep the shell from treating the brackets as a pattern. The new app is added to INSTALLED_APPS in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'orders',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

Starting Redis

Celery needs a broker that stores the messages until a worker takes them. We use Redis, which is easy to run and can also store task results. The server runs in a Docker container; the port is shifted to 6380 so that it does not collide with a Redis server that may already run on the machine. The redis-cli ping command run inside the container checks that the server answers.

$ docker run --rm -d --name zc-redis -p 6380:6379 redis:8
$ docker exec zc-redis redis-cli ping
PONG

The Celery application

A Celery application object holds the configuration and the registry of tasks. The Celery documentation recommends defining it in a module celery.py inside the configuration package.

config/celery.py
import os

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

app = Celery('config')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

The module sets DJANGO_SETTINGS_MODULE, because the worker is started by the celery command and not by manage.py. The config_from_object() call reads the configuration from Django's settings; with namespace='CELERY' only settings starting with CELERY_ are used, and the prefix is removed, so CELERY_BROKER_URL becomes Celery's broker_url. The autodiscover_tasks() call looks for a tasks.py module in every installed app.

config/__init__.py
from .celery import app as celery_app

__all__ = ('celery_app',)

Importing the application in the package's __init__.py loads it whenever Django starts, so that the tasks are bound to this application in the web process as well. At the end of the settings file we add the address of the broker: Redis on port 6380, database 0.

config/settings.py
...

CELERY_BROKER_URL = 'redis://localhost:6380/0'

A first task

A task is a function decorated with @shared_task. The decorator registers the function with the current Celery application without importing it, which suits reusable apps. Our first task counts the words in a text; the two seconds of sleep stand for slow work.

orders/tasks.py
import time

from celery import shared_task


@shared_task
def count_words(text):
    time.sleep(2)
    return len(text.split())

The task is still an ordinary function: calling count_words(text) runs it at once in the current process. Running it in the background is done with the task's methods, shown in the next sections.

Starting a worker

The worker is a separate program. It connects to the broker, waits for messages, and runs the tasks in a pool of child processes. We start it in its own terminal from the project directory. The -A config option tells Celery where to find the application: the package config, which exposes it. The -l info option sets the log level and -c 2 limits the pool to two child processes (the default is one per CPU core).

The banner lists the configuration and, under [tasks], the registered tasks; autodiscover_tasks() has found orders.tasks.count_words. The results line says disabled://, because we have not configured a place to store results yet. The mingle lines show the worker looking for other workers to synchronise with. The worker does not reload code: after changing a task, we stop it with Ctrl+C and start it again. The hostname in the banner is shortened to localhost.

$ uv run celery -A config worker -l info -c 2
 -------------- celery@localhost v5.7.0 (collider)
--- ***** -----
-- ******* ---- Linux-6.8.0-149-generic-x86_64-with-glibc2.35 2026-11-21 20:40:52
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         config:0x7ebbae6c78c0
- ** ---------- .> transport:   redis://:**@localhost:6380/0
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 2 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery


[tasks]
  . orders.tasks.count_words

[2026-11-21 20:40:52,838: INFO/MainProcess] Connected to redis://:**@localhost:6380/0
[2026-11-21 20:40:52,840: INFO/MainProcess] mingle: searching for neighbors
[2026-11-21 20:40:53,852: INFO/MainProcess] mingle: all alone
[2026-11-21 20:40:53,880: INFO/MainProcess] celery@localhost ready.

Sending a task

The delay() method sends a message to the broker and returns without waiting for the task. The demo script compares it with a direct call.

demos/send.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

import time

from orders.tasks import count_words

text = 'The river carried the last leaves of autumn past the old mill.'

start = time.perf_counter()
result = count_words.delay(text)
print(f'delay() returned {result!r} after {time.perf_counter() - start:.3f} s')

start = time.perf_counter()
words = count_words(text)
print(f'direct call returned {words} after {time.perf_counter() - start:.3f} s')

The delay() call returns an AsyncResult object with the task id in a few hundredths of a second. The direct call takes the full two seconds. The arguments are serialized to JSON and stored in the message.

The worker log, from the worker's terminal, shows that the main process received the message and that the child process ForkPoolWorker-1 finished the task two seconds later with the result 12. The result is only printed; nothing stores it yet.

$ uv run python -m demos.send
delay() returned <AsyncResult: 7717884c-7027-47d9-9ee9-fc854495cbc9> after 0.049 s
direct call returned 12 after 2.000 s
[2026-11-21 20:40:57,116: INFO/MainProcess] Task orders.tasks.count_words[7717884c-7027-47d9-9ee9-fc854495cbc9] received
[2026-11-21 20:40:59,118: INFO/ForkPoolWorker-1] Task orders.tasks.count_words[7717884c-7027-47d9-9ee9-fc854495cbc9] succeeded in 2.0006153209978947s: 12

Task results

To read a result in the program that sent the task, Celery needs a result backend. Redis can serve as both; we use database 1 for the results so that they are kept apart from the messages. The setting is added to the end of config/settings.py and the worker is restarted.

config/settings.py
...

CELERY_BROKER_URL = 'redis://localhost:6380/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6380/1'
demos/results.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from celery.result import AsyncResult

from orders.tasks import count_words

result = count_words.delay('one two three four')
print('state:', result.state)
print('ready:', result.ready())

print('result:', result.get(timeout=10))
print('state:', result.state)
print('ready:', result.ready())

same = AsyncResult(result.id)
print('looked up by id:', same.state, same.result)

The state attribute and the ready() method ask the backend without blocking. The get() method waits for the result; the timeout limits the wait. An AsyncResult created from the id alone finds the same result, so a web page can store the id and check the task later. Results expire after one day by default.

Waiting with get() inside a view would bring back the delay that the task was meant to remove. Views send tasks and return; results are read later or not at all.

$ uv run python -m demos.results
state: PENDING
ready: False
result: 4
state: SUCCESS
ready: True
looked up by id: SUCCESS 4

Failed tasks

When a task raises an exception, the worker logs it with the traceback and stores the exception in the result backend. The demo sends None instead of a text.

demos/failure.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from orders.tasks import count_words

result = count_words.delay(None)

try:
    result.get(timeout=10)
except AttributeError as exc:
    print('get() raised:', repr(exc))

print('state:', result.state)
print('last traceback line:', result.traceback.strip().splitlines()[-1])

result = count_words.delay(None)
print('propagate=False:', repr(result.get(timeout=10, propagate=False)))

The get() method raises the task's exception again in the caller, and the state is FAILURE. The traceback from the worker is available as a string in the traceback attribute. With propagate=False, get() returns the exception instead of raising it.

The second block shows the worker's log lines for the two failing tasks (the tracebacks that follow each ERROR line are left out).

$ uv run python -m demos.failure
get() raised: AttributeError("'NoneType' object has no attribute 'split'")
state: FAILURE
last traceback line: AttributeError: 'NoneType' object has no attribute 'split'
propagate=False: AttributeError("'NoneType' object has no attribute 'split'")
[2026-11-21 20:41:06,598: INFO/MainProcess] Task orders.tasks.count_words[01c63089-db7a-4391-a8f8-d07b02ed3734] received
[2026-11-21 20:41:08,611: ERROR/ForkPoolWorker-1] Task orders.tasks.count_words[01c63089-db7a-4391-a8f8-d07b02ed3734] raised unexpected: AttributeError("'NoneType' object has no attribute 'split'")
[2026-11-21 20:41:08,614: INFO/MainProcess] Task orders.tasks.count_words[389b7f8b-17ff-4c27-a534-37afdedb8de4] received
[2026-11-21 20:41:10,620: ERROR/ForkPoolWorker-1] Task orders.tasks.count_words[389b7f8b-17ff-4c27-a534-37afdedb8de4] raised unexpected: AttributeError("'NoneType' object has no attribute 'split'")

The order model

From now on the tasks work with a shop's orders. An order has a customer email, a product, a quantity, a status, a flag telling whether the confirmation email was sent, and a creation time.

orders/models.py
from django.db import models
from django.utils import timezone


class Order(models.Model):

    class Status(models.TextChoices):
        PENDING = 'pending'
        PAID = 'paid'
        CANCELLED = 'cancelled'

    email = models.EmailField()
    product = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField(default=1)
    status = models.CharField(max_length=10, choices=Status, default=Status.PENDING)
    confirmed = models.BooleanField(default=False)
    created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'#{self.pk} {self.quantity} x {self.product} ({self.status})'

The creation time uses default=timezone.now rather than auto_now_add, so that a demo script can create old orders for the periodic task later in the article. We create the migration and the table.

$ uv run python manage.py makemigrations orders
Migrations for 'orders':
  orders/migrations/0001_initial.py
    + Create model Order
$ uv run python manage.py migrate orders
Operations to perform:
  Apply all migrations: orders
Running migrations:
  Applying orders.0001_initial... OK

Calling a task from a view

Sending a confirmation email is a typical background job: a mail server can be slow or unreachable, and the customer does not need to wait for it. The new task send_confirmation loads the order, sends the email, and marks the order as confirmed. The sleep stands for a slow mail server.

orders/tasks.py
import time

from celery import shared_task
from django.core.mail import send_mail

from .models import Order


@shared_task
def count_words(text):
    time.sleep(2)
    return len(text.split())


@shared_task
def send_confirmation(order_id):
    order = Order.objects.get(pk=order_id)
    time.sleep(2)

    send_mail(f'Order #{order.pk} received',
              f'We have received your order: {order.quantity} x {order.product}.',
              'shop@example.com', [order.email])

    order.confirmed = True
    order.save(update_fields=['confirmed'])
    return f'confirmation sent to {order.email}'

The send_mail() function uses the default mailer. Django 6.1 generates a MAILERS setting with the console backend, which prints the message to standard output; in the worker it ends up in the log. Sending email is covered in Django email.

orders/views.py
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import Order
from .tasks import send_confirmation


@csrf_exempt
@require_POST
def create_order(request):
    order = Order.objects.create(email=request.POST['email'], product=request.POST['product'],
                                 quantity=int(request.POST.get('quantity', 1)))
    send_confirmation.delay(order.pk)
    return JsonResponse({'order': order.pk, 'status': order.status}, status=201)


def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return JsonResponse({'order': order.pk, 'status': order.status, 'confirmed': order.confirmed})

The view creates an order from the POST data, sends the task, and returns the new order with status code 201. To keep the curl commands short, the view is exempt from CSRF protection; a form on a web page would send the token instead. The second view returns an order, including the confirmed flag.

orders/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('orders/', views.create_order),
    path('orders/<int:pk>/', views.order_detail),
]
config/urls.py
from django.urls import include, path

urlpatterns = [
    path('', include('orders.urls')),
]

The app's URLconf maps the two views and the root URLconf includes it. With the worker restarted, we start the development server in another terminal with uv run python manage.py runserver and create an order.

The response arrives in less than a tenth of a second, while the task takes over two. Right after the order is created it is not confirmed yet; three seconds later the worker has sent the email and set the flag. The worker log (from the first task line on) contains the printed message; the console backend writes to standard output, which the worker redirects to its logger at the WARNING level.

$ curl -s -d email=jane@example.com -d product='Chess set' -d quantity=2 localhost:8000/orders/ -w '\ntime: %{time_total} s\n'
{"order": 1, "status": "pending"}
time: 0.077286 s
$ curl -s localhost:8000/orders/1/
{"order": 1, "status": "pending", "confirmed": false}
$ sleep 3
$ curl -s localhost:8000/orders/1/
{"order": 1, "status": "pending", "confirmed": true}
[2026-11-21 20:41:15,219: INFO/MainProcess] Task orders.tasks.send_confirmation[d86cce1c-6b04-4f4e-883a-39a4ee52481f] received
[2026-11-21 20:41:17,237: WARNING/ForkPoolWorker-1] Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Subject: Order #1 received
From: shop@example.com
To: jane@example.com
Date: Sat, 21 Nov 2026 20:41:17 +0000
Message-ID: <179529367723.51504.5003136087200468807@localhost>

We have received your order: 2 x Chess set.
[2026-11-21 20:41:17,237: WARNING/ForkPoolWorker-1] -------------------------------------------------------------------------------
[2026-11-21 20:41:17,256: INFO/ForkPoolWorker-1] Task orders.tasks.send_confirmation[d86cce1c-6b04-4f4e-883a-39a4ee52481f] succeeded in 2.036988816002122s: 'confirmation sent to jane@example.com'

Task arguments

The task receives the order id, not the order. Arguments travel through the broker as JSON, so they must be simple values: strings, numbers, lists, and dictionaries. The demo tries to send a model instance.

demos/instance.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from orders.models import Order
from orders.tasks import send_confirmation

order = Order.objects.first()

try:
    send_confirmation.delay(order)
except Exception as exc:
    print(f'{type(exc).__module__}.{type(exc).__name__}: {exc}')

The message cannot be encoded and delay() raises EncodeError. Passing the id is better anyway: the task loads the current row when it runs, not a copy that may be outdated by then.

$ uv run python -m demos.instance
kombu.exceptions.EncodeError: Object of type Order is not JSON serializable

Retrying a task

Tasks that talk to other services fail now and then, and running them again a moment later often helps. The module orders/warehouse.py imitates a warehouse service that does not respond to the first two attempts.

orders/warehouse.py
class ServiceUnavailable(Exception):
    pass


def reserve_stock(order, attempt):
    # the warehouse service fails twice before it answers
    if attempt < 2:
        raise ServiceUnavailable('warehouse service is not responding')

    return f'{order.quantity} x {order.product}'

The reserve_stock() function receives the number of the attempt, so that the failures are predictable. A real client would raise its error when the network call fails.

orders/tasks.py
import time

from celery import shared_task
from django.core.mail import send_mail

from .models import Order
from .warehouse import ServiceUnavailable, reserve_stock


@shared_task
def count_words(text):
    time.sleep(2)
    return len(text.split())


@shared_task
def send_confirmation(order_id):
    order = Order.objects.get(pk=order_id)
    time.sleep(2)

    send_mail(f'Order #{order.pk} received',
              f'We have received your order: {order.quantity} x {order.product}.',
              'shop@example.com', [order.email])

    order.confirmed = True
    order.save(update_fields=['confirmed'])
    return f'confirmation sent to {order.email}'


@shared_task(bind=True, max_retries=3)
def notify_warehouse(self, order_id):
    order = Order.objects.get(pk=order_id)

    try:
        reserved = reserve_stock(order, attempt=self.request.retries)
    except ServiceUnavailable as exc:
        raise self.retry(exc=exc, countdown=2)

    return f'reserved {reserved} for order #{order.pk}'

With bind=True the task receives itself as the first argument, self. The self.request.retries attribute holds the number of retries so far. The self.retry() method sends the task again with the same id and arguments, to be run after countdown seconds; it raises a Retry exception that ends the current attempt, so it is used with raise. After max_retries retries the exception passed as exc is raised and the task fails. The decorator options autoretry_for and retry_backoff do the same without the try block.

orders/views.py
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import Order
from .tasks import notify_warehouse, send_confirmation


@csrf_exempt
@require_POST
def create_order(request):
    order = Order.objects.create(email=request.POST['email'], product=request.POST['product'],
                                 quantity=int(request.POST.get('quantity', 1)))
    send_confirmation.delay(order.pk)
    notify_warehouse.delay(order.pk)
    return JsonResponse({'order': order.pk, 'status': order.status}, status=201)


def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return JsonResponse({'order': order.pk, 'status': order.status, 'confirmed': order.confirmed})

The view now sends both tasks. We restart the worker and create another order.

The worker log, with the email lines left out, shows both tasks received at the same time; the two child processes run them in parallel. Each retry is a new message that the worker receives at once and holds until its countdown expires, which is why received appears before each retry line. The third attempt succeeds four seconds after the first.

$ curl -s -d email=jane@example.com -d product='Chess set' -d quantity=2 localhost:8000/orders/
{"order": 2, "status": "pending"}
[2026-11-21 20:41:21,871: INFO/MainProcess] Task orders.tasks.send_confirmation[1158a9f7-d022-4903-bfda-77d38cb58830] received
[2026-11-21 20:41:21,872: INFO/MainProcess] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] received
[2026-11-21 20:41:21,887: INFO/MainProcess] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] received
[2026-11-21 20:41:21,900: INFO/ForkPoolWorker-2] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] retry: Retry in 2s: ServiceUnavailable('warehouse service is not responding')
[2026-11-21 20:41:23,884: INFO/MainProcess] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] received
[2026-11-21 20:41:23,885: INFO/ForkPoolWorker-2] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] retry: Retry in 2s: ServiceUnavailable('warehouse service is not responding')
[2026-11-21 20:41:23,903: INFO/ForkPoolWorker-1] Task orders.tasks.send_confirmation[1158a9f7-d022-4903-bfda-77d38cb58830] succeeded in 2.0311020929984807s: 'confirmation sent to jane@example.com'
[2026-11-21 20:41:25,890: INFO/ForkPoolWorker-1] Task orders.tasks.notify_warehouse[7604325c-a222-49b9-b7f5-012258767199] succeeded in 0.004505255001276964s: 'reserved 2 x Chess set for order #2'

Tasks and transactions

Views often run in a database transaction, either through ATOMIC_REQUESTS or transaction.atomic. A task sent inside a transaction can start before the transaction commits. The worker uses its own database connection, so it does not see the new row yet. To make the gap visible, the view sleeps for a second after sending the tasks, standing for more work done in the same transaction.

orders/views.py
import time

from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import Order
from .tasks import notify_warehouse, send_confirmation


@csrf_exempt
@require_POST
@transaction.atomic
def create_order(request):
    order = Order.objects.create(email=request.POST['email'], product=request.POST['product'],
                                 quantity=int(request.POST.get('quantity', 1)))
    send_confirmation.delay(order.pk)
    notify_warehouse.delay(order.pk)

    time.sleep(1)  # more work inside the transaction
    return JsonResponse({'order': order.pk, 'status': order.status}, status=201)


def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return JsonResponse({'order': order.pk, 'status': order.status, 'confirmed': order.confirmed})

The @transaction.atomic decorator runs the whole view in one transaction, which commits when the view returns (see Django raw SQL and transactions).

The order exists after the request, but it was never confirmed. The worker started both tasks within milliseconds, while the transaction was still open, and both failed with DoesNotExist (tracebacks left out).

$ curl -s -d email=jane@example.com -d product='Chess set' -d quantity=2 localhost:8000/orders/
{"order": 3, "status": "pending"}
$ curl -s localhost:8000/orders/3/
{"order": 3, "status": "pending", "confirmed": false}
[2026-11-21 20:41:32,151: INFO/MainProcess] Task orders.tasks.send_confirmation[e87eac54-c4a7-4ce8-9dae-b7ae6d052941] received
[2026-11-21 20:41:32,152: INFO/MainProcess] Task orders.tasks.notify_warehouse[beb93f5f-6dd3-4fd0-94c0-15992c5725eb] received
[2026-11-21 20:41:32,172: ERROR/ForkPoolWorker-2] Task orders.tasks.notify_warehouse[beb93f5f-6dd3-4fd0-94c0-15992c5725eb] raised unexpected: DoesNotExist('Order matching query does not exist.')
[2026-11-21 20:41:32,172: ERROR/ForkPoolWorker-1] Task orders.tasks.send_confirmation[e87eac54-c4a7-4ce8-9dae-b7ae6d052941] raised unexpected: DoesNotExist('Order matching query does not exist.')

Sending tasks after commit

Django's transaction.on_commit() registers a function that runs after the current transaction commits, and is skipped if it rolls back. Celery's Django integration makes every task an instance of a class with the shortcut delay_on_commit(), which wraps delay() in on_commit().

orders/views.py
import time

from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import Order
from .tasks import notify_warehouse, send_confirmation


@csrf_exempt
@require_POST
@transaction.atomic
def create_order(request):
    order = Order.objects.create(email=request.POST['email'], product=request.POST['product'],
                                 quantity=int(request.POST.get('quantity', 1)))
    send_confirmation.delay_on_commit(order.pk)
    notify_warehouse.delay_on_commit(order.pk)

    time.sleep(1)  # more work inside the transaction
    return JsonResponse({'order': order.pk, 'status': order.status}, status=201)


def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return JsonResponse({'order': order.pk, 'status': order.status, 'confirmed': order.confirmed})

The two calls are the same as transaction.on_commit(partial(send_confirmation.delay, order.pk)). Since the task is sent later, delay_on_commit() returns None rather than an AsyncResult. Outside a transaction the task is sent at once.

This time the tasks are sent when the transaction commits, they find the order, and the order is confirmed. The warehouse task goes through its two retries as before.

$ curl -s -d email=jane@example.com -d product='Chess set' -d quantity=2 localhost:8000/orders/
{"order": 4, "status": "pending"}
$ curl -s localhost:8000/orders/4/
{"order": 4, "status": "pending", "confirmed": true}
[2026-11-21 20:41:40,971: INFO/MainProcess] Task orders.tasks.send_confirmation[45b2491c-f5e5-4ce3-8b50-56264aecec48] received
[2026-11-21 20:41:40,972: INFO/MainProcess] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] received
[2026-11-21 20:41:40,985: INFO/MainProcess] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] received
[2026-11-21 20:41:40,998: INFO/ForkPoolWorker-2] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] retry: Retry in 2s: ServiceUnavailable('warehouse service is not responding')
[2026-11-21 20:41:42,982: INFO/MainProcess] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] received
[2026-11-21 20:41:42,985: INFO/ForkPoolWorker-2] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] retry: Retry in 2s: ServiceUnavailable('warehouse service is not responding')
[2026-11-21 20:41:43,002: INFO/ForkPoolWorker-1] Task orders.tasks.send_confirmation[45b2491c-f5e5-4ce3-8b50-56264aecec48] succeeded in 2.0299466729993583s: 'confirmation sent to jane@example.com'
[2026-11-21 20:41:44,988: INFO/ForkPoolWorker-1] Task orders.tasks.notify_warehouse[99cd23d2-ed0b-41d4-a98f-7b168d61e6fe] succeeded in 0.0044225420024304185s: 'reserved 2 x Chess set for order #4'

Periodic tasks

Some tasks run on a schedule rather than in response to a request. Orders that stay unpaid for half an hour should be cancelled. The new task cancel_unpaid does it with one UPDATE statement and returns the number of cancelled orders.

orders/tasks.py
import time
from datetime import timedelta

from celery import shared_task
from django.core.mail import send_mail
from django.utils import timezone

from .models import Order
from .warehouse import ServiceUnavailable, reserve_stock


@shared_task
def count_words(text):
    time.sleep(2)
    return len(text.split())


@shared_task
def send_confirmation(order_id):
    order = Order.objects.get(pk=order_id)
    time.sleep(2)

    send_mail(f'Order #{order.pk} received',
              f'We have received your order: {order.quantity} x {order.product}.',
              'shop@example.com', [order.email])

    order.confirmed = True
    order.save(update_fields=['confirmed'])
    return f'confirmation sent to {order.email}'


@shared_task(bind=True, max_retries=3)
def notify_warehouse(self, order_id):
    order = Order.objects.get(pk=order_id)

    try:
        reserved = reserve_stock(order, attempt=self.request.retries)
    except ServiceUnavailable as exc:
        raise self.retry(exc=exc, countdown=2)

    return f'reserved {reserved} for order #{order.pk}'


@shared_task
def cancel_unpaid(minutes=30):
    limit = timezone.now() - timedelta(minutes=minutes)
    pending = Order.objects.filter(status=Order.Status.PENDING, created__lt=limit)
    count = pending.update(status=Order.Status.CANCELLED)
    return f'{count} unpaid orders cancelled'

The schedule lives in the setting CELERY_BEAT_SCHEDULE, added to the end of config/settings.py. Each entry has a name, the task name, and a schedule: a number of seconds, a timedelta, or a crontab() from celery.schedules, such as crontab(minute='*/15'). We run the task every ten seconds to see it at work.

config/settings.py
...

CELERY_BEAT_SCHEDULE = {
    'cancel-unpaid-orders': {
        'task': 'orders.tasks.cancel_unpaid',
        'schedule': 10.0,
    },
}
demos/seed.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from datetime import timedelta

from django.utils import timezone

from orders.models import Order

Order.objects.all().delete()
now = timezone.now()

Order.objects.create(email='paul@example.com', product='Go board', created=now - timedelta(hours=2),
                     status=Order.Status.PAID)
Order.objects.create(email='lucy@example.com', product='Puzzle', created=now - timedelta(hours=1))
Order.objects.create(email='mark@example.com', product='Dice set', created=now - timedelta(minutes=45))
Order.objects.create(email='anna@example.com', product='Chess clock', created=now - timedelta(minutes=5))

for order in Order.objects.all():
    print(order, order.created.strftime('%H:%M'))

The seed script replaces the orders with four orders of different ages: a paid one, two pending ones older than half an hour, and a pending one five minutes old. The times are in UTC.

$ uv run python -m demos.seed
#5 1 x Go board (paid) 18:41
#6 1 x Puzzle (pending) 19:41
#7 1 x Dice set (pending) 19:56
#8 1 x Chess clock (pending) 20:36

Running celery beat

The schedule is run by celery beat, a separate process that sends the due tasks to the broker; a worker runs them. Only one beat process may run for a schedule, otherwise every task would be sent several times. We start beat in a third terminal, next to the restarted worker.

demos/orders.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from orders.models import Order

for order in Order.objects.all():
    print(order)

The short demo script lists the orders after beat has run for twenty seconds.

Beat sent the task ten seconds after it started and again ten seconds later. The first run cancelled the two old pending orders, the second found nothing to do. The paid order and the recent one are untouched. Beat stores the time of the last run of each entry in the file celerybeat-schedule in the current directory, so that a restart does not lose track. For development, celery worker -B runs beat inside the worker.

$ uv run celery -A config beat -l info
celery beat v5.7.0 (collider) is starting.
__    -    ... __   -        _
LocalTime -> 2026-11-21 20:41:50
Configuration ->
    . broker -> redis://:**@localhost:6380/0
    . loader -> celery.loaders.app.AppLoader
    . scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-schedule
    . logfile -> [stderr]@%INFO
    . maxinterval -> 5.00 minutes (300s)

[2026-11-21 20:41:50,384: INFO/MainProcess] beat: Starting...
[2026-11-21 20:42:00,413: INFO/MainProcess] Scheduler: Sending due task cancel-unpaid-orders (orders.tasks.cancel_unpaid)
[2026-11-21 20:42:10,410: INFO/MainProcess] Scheduler: Sending due task cancel-unpaid-orders (orders.tasks.cancel_unpaid)
[2026-11-21 20:42:00,420: INFO/MainProcess] Task orders.tasks.cancel_unpaid[8725693c-11eb-4709-bfee-43001123d28f] received
[2026-11-21 20:42:00,438: INFO/ForkPoolWorker-1] Task orders.tasks.cancel_unpaid[8725693c-11eb-4709-bfee-43001123d28f] succeeded in 0.016093117999844253s: '2 unpaid orders cancelled'
[2026-11-21 20:42:10,415: INFO/MainProcess] Task orders.tasks.cancel_unpaid[131bb0bc-7b6d-4b75-8476-b1be7e4e3e16] received
[2026-11-21 20:42:10,420: INFO/ForkPoolWorker-1] Task orders.tasks.cancel_unpaid[131bb0bc-7b6d-4b75-8476-b1be7e4e3e16] succeeded in 0.004173580997303361s: '0 unpaid orders cancelled'
$ uv run python -m demos.orders
#5 1 x Go board (paid)
#6 1 x Puzzle (cancelled)
#7 1 x Dice set (cancelled)
#8 1 x Chess clock (pending)

Testing tasks

Tests should not depend on a running broker and worker. A task called as a function runs in the test process, so its logic is tested like any other code. For views, we check that they send the right tasks, replacing delay() with a mock. Testing in Django is covered in Django testing.

orders/tests.py
from datetime import timedelta
from unittest import mock

from django.core import mail
from django.test import TestCase
from django.utils import timezone

from .models import Order
from .tasks import cancel_unpaid, notify_warehouse, send_confirmation


class TaskTests(TestCase):

    @mock.patch('orders.tasks.time.sleep')
    def test_send_confirmation(self, sleep):
        order = Order.objects.create(email='jane@example.com', product='Chess set')

        result = send_confirmation(order.pk)

        self.assertEqual(result, 'confirmation sent to jane@example.com')
        self.assertEqual(mail.outbox[0].subject, f'Order #{order.pk} received')
        order.refresh_from_db()
        self.assertTrue(order.confirmed)

    def test_cancel_unpaid(self):
        old = timezone.now() - timedelta(hours=1)
        Order.objects.create(email='lucy@example.com', product='Puzzle', created=old)
        Order.objects.create(email='anna@example.com', product='Chess clock')

        self.assertEqual(cancel_unpaid(), '1 unpaid orders cancelled')


class ViewTests(TestCase):

    @mock.patch.object(notify_warehouse, 'delay')
    @mock.patch.object(send_confirmation, 'delay')
    def test_tasks_sent_after_commit(self, confirm, notify):
        with self.captureOnCommitCallbacks(execute=True):
            response = self.client.post('/orders/', {'email': 'jane@example.com',
                                                     'product': 'Chess set'})
            confirm.assert_not_called()

        order_id = response.json()['order']
        confirm.assert_called_once_with(order_id)
        notify.assert_called_once_with(order_id)

The first test patches time.sleep in the tasks module, so that it does not wait two seconds, and calls the task directly. The test runner replaces the mailers with an in-memory backend, so the email appears in mail.outbox. The second test checks that only old pending orders are cancelled.

The view test patches the delay() methods of both tasks. A TestCase runs each test in a transaction that is never committed, so on_commit() callbacks would never run; captureOnCommitCallbacks(execute=True) collects them and runs them when the block ends. Inside the block the task has not been sent yet, which proves that it waits for the commit. Celery also has the setting task_always_eager, which makes delay() run the task in the caller.

We stop the Redis container before running the tests, to show that they need neither the broker nor a worker. The test run takes about a second because of the sleep in the view.

$ docker stop zc-redis
zc-redis
$ uv run python manage.py test -v 2
Found 3 test(s).
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
Operations to perform:
  Synchronize unmigrated apps: messages, staticfiles
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
Running migrations:
System check identified no issues (0 silenced).
test_cancel_unpaid (orders.tests.TaskTests.test_cancel_unpaid) ... ok
test_send_confirmation (orders.tests.TaskTests.test_send_confirmation) ... ok
test_tasks_sent_after_commit (orders.tests.ViewTests.test_tasks_sent_after_commit) ... ok

----------------------------------------------------------------------
Ran 3 tests in 1.010s

OK
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...

Source

Celery documentation: First steps with Django

Celery documentation: Tasks

Celery documentation: Calling tasks

Celery documentation: Periodic tasks

Django documentation: Performing actions after commit

Django documentation: Tasks framework

In this article we have run background tasks in Django with Celery: we configured Celery with Redis as the broker and result backend, started a worker, sent tasks with delay() and read their results, retried a failing task, sent tasks only after the transaction committed with delay_on_commit(), scheduled a periodic task with celery beat, and tested the tasks without a worker. Related articles are Django email, Django raw SQL and transactions, Async Django, and Django testing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.