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.
To get started with Django in Python Workers, follow these steps:
-
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 -
Run your worker locally:
uv run pywrangler dev
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.
Build the application object with get_wsgi_application() and pass it to workers.wsgi.fetch:
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"].
Build the application object with get_asgi_application() and pass it to workers.asgi.fetch:
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"].
If you need a secret (like SECRET_KEY) in your Django settings, you can read it from a Worker secret:
from workers import env
SECRET_KEY = env.DJANGO_SECRET_KEYCreate the secret with uv run pywrangler secret put DJANGO_SECRET_KEY.
- If you need Django's ORM on Python Workers, use the
django-cfbackends for D1 or SQLite-backed Durable Objects. These backends do not support transactions and have limitations on ORM expressions and lookups. - If you need Django's ORM with PostgreSQL, run Django in a standard Python environment, such as Cloudflare Containers. Use Django's PostgreSQL settings ↗︎ to connect without Hyperdrive. This avoids the SQLite function limitations that affect the Django admin's date hierarchy.
- If you need PostgreSQL from Python Workers without Django's ORM, query PostgreSQL with
asyncpgthrough Hyperdrive. PlanetScale Postgres is one provider option.
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.
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",
]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.
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:
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.
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)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:
DATABASES = {
"default": {
"ENGINE": "django_cf.db.backends.do",
}
}Then, update your Python worker as follows:
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)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, andTruncTime. - Duration arithmetic, such as
F("start") + timedelta(days=1)andF("end") - F("start"). - Regular expression lookups:
__regexand__iregex. - Hash, string, and math functions:
MD5,SHA*,LPad,RPad,Repeat,Reverse,Cot,Power, andCeil. - Statistical aggregates:
StdDevandVariance.
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 withtimestamp__gte=start_utcandtimestamp__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
__startswithor__containsif SQLite'sLIKEbehavior ↗︎ 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.
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.
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:
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 --noinputSet 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.
Clone the cloudflare/python-workers-examples repository and run Django examples: