Skip to main content

django-logic

CI Coverage Status License

Django Logic is a workflow library for Django. You declare the states of a model, the transitions between them, and the code each transition runs. The declaration lives in one place, away from views, models and forms.

Work that is slow, external or retriable is a background transition. django-logic saves it as a database row. A worker process claims the row and runs it.

Requirements

  • Python 3.11 or later.
  • Django 5.2 or later. CI tests 5.2, 6.0 and 6.1.
  • PostgreSQL for background transitions. The worker claims a row with SELECT FOR UPDATE SKIP LOCKED, and SQLite has no row locks. Use psycopg 3.2 or later, or Django’s supported psycopg2 driver. The postgres installation extra installs psycopg 3.
  • A cross-process default cache. The web processes and the worker processes share the state lock through it. django-logic locks through Django's cache API and imports no backend, so django.core.cache.backends.redis.RedisCache is enough. manage.py check refuses a per-process cache (locmem, dummy) when DEBUG=False and a background transition is bound.

Install

The current release is 5.1.0. See the changelog for its fixes. Before upgrading, follow the upgrade and rollback requirements.

pip install "django-logic[postgres]" redis

Add one entry to INSTALLED_APPS and create the table:

INSTALLED_APPS = [
    ...,
    'django_logic',
]

That one entry is the whole library: the TransitionMessage table and its migrations, the dl_worker and dl_transitions commands, and every system check. Configure the database and cache described below.

Running no background transitions? The same entry. The PostgreSQL and shared-cache rules below apply only when a background transition is bound — manage.py check tells you the moment one is — so a synchronous-only project runs on SQLite with Django's default cache. By default, a synchronous transition on other databases takes its cache lock but opens no transaction. Without a caller transaction, earlier writes survive an interruption, and swallowed database errors may not be detected. Use PostgreSQL to verify the transaction and concurrent-state guarantees described below.

python manage.py migrate

Point the default cache at a backend the web processes and the workers share:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': os.environ['REDIS_URL'],
    }
}

Every DJANGO_LOGIC key has a default, so you need no other configuration to start.

Upgrading to version 5

Version 5 removes obsolete APIs and saved-job restoration fallbacks. Start from 4.3.2, update application declarations, and finish jobs whose action or process names will change before stopping the old producers and workers. Apply migrations with the new application installed, then start only the new version’s processes. Migration 0017 refuses unresolved jobs that the new code cannot restore; it does not discard them. Mixed versions are unsupported. See the upgrade checklist.

Declare a process

A process lists the transitions of one state field. A transition names the states it starts from, the state it ends in, and the functions it runs.

# models.py
from django.db import models


class Order(models.Model):
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('approved', 'Approved'),
        ('fulfilling', 'Fulfilling'),
        ('fulfilled', 'Fulfilled'),
        ('fulfilment_failed', 'Fulfilment failed'),
        ('cancelled', 'Cancelled'),
    ]
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default='draft')
# process.py
from django_logic import Process, Transition


def has_stock(instance, **kwargs):
    return all(item.product.stock >= item.quantity for item in instance.items.all())


def is_staff_member(instance, user, **kwargs):
    return user.is_staff


def reserve_stock(instance, **kwargs):
    for item in instance.items.all():
        item.product.stock -= item.quantity
        item.product.save()


def send_approval_email(instance, **kwargs):
    ...


class OrderProcess(Process):
    process_name = 'process'
    transitions = [
        Transition(
            action_name='approve',
            sources=['draft'],
            target='approved',
            conditions=[has_stock],
            permissions=[is_staff_member],
            side_effects=[reserve_stock],
            callbacks=[send_approval_email],
        ),
        Transition(
            action_name='cancel',
            sources=['draft', 'approved'],
            target='cancelled',
        ),
    ]

Each declaration slot has one job:

  • conditions — functions that answer True or False. Every one must answer True, or the transition is not available.
  • permissions — functions that answer whether this user may run the transition. They receive user.
  • side_effects — the work of the transition. It runs before the object reaches the target state. A failure stops the state change, and django-logic writes failed_state when you declare one.
  • callbacks — functions that run after the object reaches the target state. They are best-effort: django-logic swallows ordinary exceptions they raise. A callback that fails keeps what it saved before the error. Only a database error discards its writes. A transition that a callback starts keeps its failed state when it fails. Put required work in side_effects.
  • failure_callbacks — functions that run after a side-effect fails. They receive exception= and are best-effort. Use them for optional reporting. Required compensation belongs in a saved business job.

Required database changes can use atomic=True. Use DatabaseTransition when all work can be rolled back by PostgreSQL. See locks and transactions for callback timing, nested actions and external-request limits.

Declare a Transition with no target for work that needs conditions, permissions and side-effects but writes no state on success. It follows the same rules as every transition: it takes the state lock, it is refused while a background transition is uncompleted, and it runs callbacks after success.

An explicit target='' saves an empty state. Use target=None to leave the state unchanged. Before upgrading, change declarations that used target='' to mean no state change. An empty target keeps the usual source checks and state locks, including for background transitions.

Add lock=False when the unit of work is not the bound row. A store process that posts one parcel's tracking is the example: the row is the store, the work is the parcel, and two parcels must not wait for each other. A lock=False transition takes no state lock and is not refused while a background transition is uncompleted. It keeps conditions, permissions, side_effects, callbacks and failure_callbacks. A callback is best-effort; a transition it starts can be refused while the row is locked. It cannot declare a target or a failed_state — a state write must serialise on that state — and BackgroundTransition refuses it. get_available_actions() lists it while the row is locked, because it can be called.

def post_tracking(instance, **kwargs):
    ...  # tell the store about the parcel in kwargs['parcel']


Transition(
    action_name='post_tracking',
    sources=['approved', 'fulfilled'],
    lock=False,
    side_effects=[post_tracking],
)

permissions treat a call with no user as permitted. When one action name is split across nested processes by who is asking, give the person's branch permissions_class = StrictPermissions (refuses a call with no user) and the automation branch permissions_class = NoUserPermissions (refuses a call with one), both from django_logic.commands, so no caller matches two branches.

Bind the model to the process

Bind in your app's AppConfig.ready(). This is the one supported place.

# apps.py
from django.apps import AppConfig
from django_logic import ProcessManager


class ShopConfig(AppConfig):
    name = 'shop'

    def ready(self):
        from .models import Order
        from .process import OrderProcess
        ProcessManager.bind_model_process(Order, OrderProcess, state_field='status')

Import the model and the process inside ready(). A process references its model, and so do its condition, permission and side-effect functions. Binding at module import time therefore builds the import cycle models.py → process.py → actions.py → models.py. Django loads every app's models before it runs any ready(), so binding here cannot build that cycle, and your action modules import the model at the top level like normal code.

List the app in INSTALLED_APPS, or Django never runs ready().

One physical model and process name must identify one state field, including bindings through proxy models. Give independent fields distinct process names. Binding sibling proxies with the same process name to different fields is unsupported. The library does not validate that combination.

For an inherited state field on a multi-table model, drive the process through the parent model that owns the field. Mixing parent and child process access is unsupported. Their background identities and pending-work probes do not share one gate. Use a separate concrete model for an independent workflow.

Run a transition

order = Order.objects.get(pk=pk)
order.process.approve(user=request.user)

The engine manages tr_id, root_id, parent_id, process_class and owning_process_class. Use other names for business data. A process action always records its actual bound root and declaring class, replacing forwarded process_class and owning_process_class values. These arguments cannot select a different process. Validate request fields at the application boundary. Background transitions rebuild context; they do not save a caller's context. They also refuse user_id; pass user= instead. Calls refuse state and exception because those names belong to engine internals. Failure callbacks receive exception=; ordinary hooks do not receive a state argument.

  • The accessor is the process class's process_name. It is process by default.
  • Pass user= in a request handler. A call without user= is a system call, and it skips every permission check.
  • Never pass the request. A transition refuses request= at the call: side effects and callbacks accept fn(instance, **kwargs) and can run on a worker. Conditions receive instance; permissions receive instance, user. Neither receives business arguments. Resolve what a hook needs in the view and pass plain values.
  • order.process.get_available_actions(user=request.user) lists what this user may run right now.
  • A refused transition raises TransitionNotAllowed from django_logic.exceptions. Its subclass TransitionTemporarilyUnavailable means the instance is busy, so the caller may retry shortly. Catch the subclass first.

See refused actions for reason codes, temporary refusals and messages for users.

Background transitions

BackgroundTransition runs its side-effects on a worker process, and retries them. Declared with no target, it changes no state on success — same durability, same rules. Import it from django_logic.background.

# process.py
from django_logic import Process, Transition
from django_logic.background import BackgroundTransition


class OrderProcess(Process):
    transitions = [
        Transition(action_name='approve', sources=['draft'], target='approved'),
        BackgroundTransition(
            action_name='fulfil',
            sources=['approved'],
            target='fulfilled',
            in_progress_state='fulfilling',
            failed_state='fulfilment_failed',
            queue='django_logic.critical',
            timeout=600,
            side_effects=[book_courier, print_labels],
            callbacks=[send_tracking_email],
        ),
    ]
# views.py — returns as soon as django-logic saves the row.
order.process.fulfil(user=request.user)

The call writes in_progress_state and one TransitionMessage row in a single transaction, then returns. By default, a worker runs the side-effects and writes the target state in one transaction. A failed attempt rolls back its own database writes and becomes claimable again after TRANSITION_MESSAGE_RETRY_MINUTES. After TRANSITION_MESSAGE_MAX_ERRORS attempts django-logic writes failed_state, runs failure_callbacks and completes the row.

in_progress_state is available only on background transitions with a target. Several transitions may share it; each saved job records its exact transition. A synchronous transition cannot declare it. Use submission_context for required database preparation that must commit together with the background job and its in-progress state. A failed submission rolls all of them back. See the submission contract.

If another action changes the model's state while a job waits, that change wins. The worker completes the job as superseded and skips its side effects.

  • Side-effects must be idempotent against external systems. A retry runs them again from the start, so a payment or an email can happen twice.
  • atomic=False preserves committed model writes when later work fails. Use it for provider receipts that must survive a report or state-write failure. See provider receipts for restrictions and retry safety.
  • queue= is optional. A transition without it runs on DJANGO_LOGIC['DEFAULT_QUEUE'], which is django_logic. Name a queue per service level and give it its own worker.
  • timeout= is optional. The worker kills an attempt that runs past it and records one error on the row.
  • Raise PermanentFailure from django_logic.background when a retry cannot help. The worker then takes the failure path on the first attempt. For an exception type you do not own, list it in no_retry_on=(CustomsRefusal,).
  • While a row is uncompleted, a second background transition on the same instance and process raises AlreadyInProgress, and a synchronous transition on it raises TransitionTemporarilyUnavailable. Keep required functions in the owning job, or save ordinary business jobs with the result that requests them. Callbacks run after completion and are suitable only for optional work.

docs/workers.md explains how a worker claims a row and what happens when one dies.

Run the workers

One dl_worker process serves one group of queues.

If logging or telemetry buffers reports, configure DJANGO_LOGIC['JOB_PROCESS_FINISH'] with an application function's dotted path. The function sends this job process's reports before exit, with a separate two-second limit. See buffered reporting for process-local state requirements and delivery limits.

python manage.py dl_worker --queues django_logic.critical,django_logic.fast
python manage.py dl_worker --queues django_logic.slow --concurrency=4

--concurrency=N says how many attempts one worker runs at a time. The default is 1. Each attempt runs in its own forked process and holds its own database connection. Read "Sizing a deployment" in docs/workers.md for the memory and connection budget.

A worker that dies releases its row lock with its database connection, and the next claim takes the row. A job process can stop while it saves another background job. On PostgreSQL that save holds the business row and writes no cache lock, so the record is not left locked.

See running workers for queue diagnostics, retry commands, retained statistics and maintenance.

Test your process

django_logic.testing gives you ProcessScenario, a test base class that runs a whole workflow inline, background transitions included. A test reads like the business process.

from django_logic.testing import ProcessScenario


class TestOrderFulfilment(ProcessScenario):
    process_class = OrderProcess
    model = Order
    state_field = 'status'

    def test_happy_path(self):
        order = self.create_instance(status='approved')
        self.background_transition(order, 'fulfil')
        self.assert_state(order, 'fulfilled')
        self.assert_side_effects_ran(['book_courier'])

For deployment-wide inline tests, call django_logic.conf.enable_sync() in test settings and set DJANGO_LOGIC['BACKGROUND_EXECUTION'] = 'sync'. Boot refuses that setting without the explicit opt-in. Production deployments normally use pull. Business code can use django_logic.background.sync_execution() for one block that needs an immediate result. That block runs in the caller's process and starts no retry loop. A committed unfinished job can still be claimed by workers serving its queue. SQLite supports synchronous process tests and default atomic background tests. DatabaseTransition and BackgroundTransition(atomic=False) tests require PostgreSQL. An atomic background transition can join a caller transaction. Outside the test runtime, atomic=False still requires PostgreSQL autocommit. In the test runtime, an atomic=False job called inside a transaction runs in that transaction, so TestCase can run it. Its writes stay when a later step fails, unless the test's own transaction rolls back. docs/TESTING_GUIDE.md has the test setup and scenario catalog.

More documentation

Contributing

Pull requests are welcome. Open an issue first for a major change.

pip install -e '.[dev]'
python tests/manage.py test          # SQLite suite
python tests/manage.py test tests.test_transition

Test changed behavior and update the affected documentation.

Report a bug in the issue tracker.

License

MIT

Metadata

Release files for django-logic 5.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-logic 5.1.0
File Size Uploaded Provenance Actions
django_logic-5.1.0.tar.gz 187.1 kB With provenance Details for django_logic-5.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-logic 5.1.0
File Interpreter ABI Platform Actions
django_logic-5.1.0-py3-none-any.whl Python 3 none any Details for django_logic-5.1.0-py3-none-any.whl

Total release size: 315.4 kB

Release files / django_logic-5.1.0.tar.gz

Download URL django_logic-5.1.0.tar.gz
Size 187.1 kB
Tags Source
SHA-256 checksum
How to use checksums
75a25c76e96d8bba2c24b9a08db8210d59b8bdf35ed5cfb2cba15a1be9e2a41e
BLAKE2b-256 checksum
How to use checksums
5f2423a669704d8ddcb3a7949d696ed35b398e2c6e5256851ae41bec0149809d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / django_logic-5.1.0-py3-none-any.whl

Download URL django_logic-5.1.0-py3-none-any.whl
Size 128.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e51e75d3162c9edda6c9bd6d0c9a21609f32bdd5be82ed13ca2f75aeb7b3b66
BLAKE2b-256 checksum
How to use checksums
f9b9f91ad0149f4799a0ef9e8cc8ea3e37412e72bf37b9af2b381d0e22f44312
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for django-logic 5.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_logic-5.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

5.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page