Skip to content

Django

Django ↗︎ is supported in Python Workers.

Django applications use protocols called the Web Server Gateway Interface (WSGI) ↗︎ or Asynchronous Server Gateway Interface (ASGI) ↗︎.

This means that Django never reads from or writes to a socket itself. A WSGI/ASGI application expects to be hooked up to a WSGI/ASGI server, such as uvicorn ↗︎. The WSGI/ASGI server handles all of the raw sockets on the application’s behalf.

Python Workers provide adaptors for both WSGI and ASGI, so you can choose any based on whether your Django application deploys to WSGI or ASGI.

Quick start

To get started with Django in Python Workers, follow these steps:

  1. Create a Django project using pywrangler init:

    uv run pywrangler init django-worker --template https://github.com/cloudflare/python-workers-examples/tree/main/django
    cd django-worker
  2. Run your worker locally:

    uv run pywrangler dev

Choose between ASGI and WSGI

Your Django application needs to be served using either ASGI or WSGI. While Python workers is optimized for ASGI, you can still use WSGI which is compatible with Django.

Serve a WSGI application

Build the application object with get_wsgi_application() and pass it to workers.wsgi.fetch:

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from workers import wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

app = get_wsgi_application()

Default = wsgi.entrypoint(app)

wsgi.fetch takes the application object, the incoming request, and the environment. It exposes your bindings to the application through scope["env"].

Serve an ASGI application

Build the application object with get_asgi_application() and pass it to workers.asgi.fetch:

src/index.pypython
import os

from django.core.asgi import get_asgi_application
from workers import asgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

app = get_asgi_application()

Default = asgi.entrypoint(app)

asgi.fetch takes the application object, the incoming request, and the environment. It exposes your bindings to the application through scope["env"].

Configure Django settings

Pass secrets

If you need a secret (like SECRET_KEY) in your Django settings, you can read it from a Worker secret:

src/app/settings.pypython
from workers import env

SECRET_KEY = env.DJANGO_SECRET_KEY

Create the secret with uv run pywrangler secret put DJANGO_SECRET_KEY.

Choose a database setup

Django's built-in PostgreSQL backend does not use asyncpg. To use it with psycopg on Python Workers, you need a compatible build of libpq.

Even with a compatible PostgreSQL driver, Django ORM queries can raise SynchronousOnlyOperation under WSGI, and ASGI can fail when Django attempts to start a thread. Do not disable Django's async-safety checks ↗︎ to work around these PostgreSQL errors.

Use Cloudflare storage as Django backends

You can use Cloudflare D1 and Durable Objects as Django database backends. To use them, you need to install the django-cf ↗︎ package.

With django-cf 0.2.17, set DJANGO_ALLOW_ASYNC_UNSAFE=1 before initializing Django in the WSGI examples below. The D1 and Durable Objects backends need this setting to run Django's synchronous ORM in the Worker. It disables Django's async-safety checks for the application. Do not use it as a workaround for other database backends.

Add django-cf to your dependencies:

[project]
dependencies = [
    "django",
    "django-cf",
]

Database backends

django-cf provides two SQLite-compatible backends using Cloudflare's D1 and Durable Objects. Both drive the synchronous Django ORM, so serve your application through the WSGI path when you use them.

D1 backend

To use D1 as a database backend, first setup your D1 database in Wrangler:

{
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "my-database",
      "database_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    }
  ]
}
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Then, configure the backend in your Django settings:

src/app/settings.pypython
DATABASES = {
    "default": {
        "ENGINE": "django_cf.db.backends.d1",
        # should match the binding name in your wrangler.jsonc
        "CLOUDFLARE_BINDING": "DB",
    }
}

You are all set. Your Django application now uses D1 as its database backend.

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from workers import WorkerEntrypoint, wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "1")

application = get_wsgi_application()


class Default(WorkerEntrypoint):
    async def fetch(self, request):
        return await wsgi.fetch(application, request, self.env)

Durable Objects backend

To use Durable Objects as a database backend, first setup your Durable Objects binding in Wrangler:

{
  "durable_objects": {
    "bindings": [
      {
        "name": "DO_STORAGE",
        "class_name": "DjangoDurableObject"
      }
    ]
  },
  "migrations": [
    {
      "tag": "v1",
      "new_sqlite_classes": ["DjangoDurableObject"]
    }
  ]
}
[[durable_objects.bindings]]
name = "DO_STORAGE"
class_name = "DjangoDurableObject"

[[migrations]]
tag = "v1"
new_sqlite_classes = [ "DjangoDurableObject" ]

Then, configure the backend in your Django settings:

src/app/settings.pypython
DATABASES = {
    "default": {
        "ENGINE": "django_cf.db.backends.do",
    }
}

Then, update your Python worker as follows:

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from django_cf.db.backends.do.storage import set_storage
from workers import WorkerEntrypoint, DurableObject, wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "1")

application = get_wsgi_application()


class DjangoDurableObject(DurableObject):
    def __init__(self, ctx, env):
        super().__init__(ctx, env)

        # Tell Django to use the Durable Object storage
        set_storage(self.ctx.storage.sql)

    async def fetch(self, request):
        return await wsgi.fetch(application, request, self.env)


class Default(WorkerEntrypoint):
    async def fetch(self, request):
        id = self.env.DO_STORAGE.idFromName("my-do-backend")
        stub = self.env.DO_STORAGE.get(id)
        return await stub.fetch(request)

SQLite user-defined functions and ORM lookups

Django's standard SQLite backend registers Python user-defined functions (UDFs) on its sqlite3 connection. Django uses these functions for expressions such as TruncDay and lookups such as __regex.

Neither the D1 binding nor the Durable Objects SQL API exposes sqlite3.Connection.create_function(). This applies even when Django runs inside the Durable Object and uses ctx.storage.sql directly. A Durable Object RPC method can run a query or process its results, but SQLite cannot call that method as a SQL function.

In django-cf 0.2.17, the following ORM features fail on both D1 and Durable Objects because the backends do not register the required functions:

  • Date and time lookups and expressions: __month, __day, __week_day, __hour, __date, Extract*, TruncDate, and TruncTime.
  • Duration arithmetic, such as F("start") + timedelta(days=1) and F("end") - F("start").
  • Regular expression lookups: __regex and __iregex.
  • Hash, string, and math functions: MD5, SHA*, LPad, RPad, Repeat, Reverse, Cot, Power, and Ceil.
  • Statistical aggregates: StdDev and Variance.

There is a separate limitation for date expressions that django-cf rewrites to use built-in SQLite functions. In 0.2.17, Trunc* expressions that use this rewrite and QuerySet.datetimes() on a DateTimeField with USE_TZ=True fail on both backends with Wrong number of parameter bindings for SQL query. The rewrite removes two placeholders but still passes their values, and it does not convert the timestamp to the requested time zone.

Lookups that still call unavailable functions can fail with no such function. For example, __regex uses REGEXP, which Django normally registers on its SQLite connection.

These errors reach Python as pyodide.ffi.JsException, not Django's OperationalError.

When using Django with D1 or Durable Objects:

  • Use timestamp ranges to filter by day. With USE_TZ=True, convert the start of the local day and the start of the next local day separately to UTC. Filter with timestamp__gte=start_utc and timestamp__lt=end_utc. This filters rows by day; it does not group them by day.
  • Use simpler text lookups when possible. For a literal prefix or substring match, use __startswith or __contains if SQLite's LIKE behavior ↗︎ meets your needs. These lookups are case-insensitive for ASCII letters.
  • Test queries on each backend you use. Start with uv run pywrangler dev, then verify against your D1 database or SQLite-backed Durable Object in a deployed test environment. Check the returned values, including around local midnight and daylight saving changes.

The built-in Django admin date list filter already uses range comparisons. Test date_hierarchy separately: selecting a date applies a range filter, but building the navigation still uses date truncation.

Static files

Collect Django's static files into the directory you deploy with Workers Static Assets. In the Django example project, update the settings as shown below. If you already have entries in INSTALLED_APPS, keep them and add django.contrib.staticfiles.

src/hello_django/settings.pypython
from pathlib import Path

INSTALLED_APPS = ["django.contrib.staticfiles"]
STATIC_URL = "/static/"
STATICFILES_DIRS = [Path(__file__).resolve().parent / "static"]
STATIC_ROOT = Path(__file__).resolve().parents[2] / "public" / "static"

Add a sample stylesheet so the example has a file to collect:

src/hello_django/static/example.csscss
body {
	font-family: system-ui, sans-serif;
}

From the project directory, run collectstatic before pywrangler dev and before deploying. Wrangler fails if the asset directory does not exist. Replace hello_django.settings with your settings module if it differs.

uv run django-admin collectstatic --settings=hello_django.settings --pythonpath=src --noinput

Set assets.directory to ./public in your Wrangler configuration. collectstatic writes the stylesheet to public/static/example.css. Open /static/example.css on your local Worker and again on your deployed Worker to verify it is served.

By default, requests that match static assets bypass the Python handler. You do not need to forward these requests through ASSETS.fetch(). If your Worker needs to authenticate requests or modify responses for a path, configure Worker-first routing for that path. Use an assets binding to fetch assets from your Worker code.

Keep collected files out of version control. To regenerate the files before deployment, add collectstatic to a custom build command.

More examples

Clone the cloudflare/python-workers-examples repository and run Django examples:

Was this helpful?