Skip to content

Commit 50630d3

Browse files
committed
Add django with d1 template
1 parent 4e8066e commit 50630d3

27 files changed

+1112
-0
lines changed

16-django-with-d1/.gitignore

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Logs
2+
3+
logs
4+
_.log
5+
npm-debug.log_
6+
yarn-debug.log*
7+
yarn-error.log*
8+
lerna-debug.log*
9+
.pnpm-debug.log*
10+
11+
# Diagnostic reports (https://nodejs.org/api/report.html)
12+
13+
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
14+
15+
# Runtime data
16+
17+
pids
18+
_.pid
19+
_.seed
20+
\*.pid.lock
21+
22+
# Dependency directories
23+
24+
node_modules/
25+
jspm_packages/
26+
27+
# TypeScript cache
28+
29+
\*.tsbuildinfo
30+
31+
# Optional npm cache directory
32+
33+
.npm
34+
35+
# Optional eslint cache
36+
37+
.eslintcache
38+
39+
# Optional stylelint cache
40+
41+
.stylelintcache
42+
43+
# Optional REPL history
44+
45+
.node_repl_history
46+
47+
# Output of 'npm pack'
48+
49+
\*.tgz
50+
51+
# dotenv environment variable files
52+
53+
.env
54+
.env.development.local
55+
.env.test.local
56+
.env.production.local
57+
.env.local
58+
59+
# public
60+
61+
# Stores VSCode versions used for testing VSCode extensions
62+
63+
.vscode-test
64+
65+
# wrangler project
66+
67+
.dev.vars
68+
.wrangler/
69+
.idea
70+
node_modules
71+
staticfiles
72+
python_modules
73+
.venv
74+
.venv-workers

16-django-with-d1/README.md

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# Django D1 Template for Cloudflare Workers
2+
3+
This template provides a starting point for running a Django application on Cloudflare Workers, utilizing Cloudflare D1 for serverless SQL database.
4+
5+
[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/G4brym/django-cf/tree/main/templates/d1)
6+
7+
## Overview
8+
9+
This template is pre-configured to:
10+
- Use `django-cf` to bridge Django with Cloudflare's environment.
11+
- Employ Cloudflare D1 as the primary data store through the `django_cf.db.backends.d1` database engine.
12+
- Include a basic Django project structure within the `src/` directory.
13+
- Provide example worker entrypoint (`src/index.py`).
14+
15+
## Project Structure
16+
17+
```
18+
template-root/
19+
|-> src/
20+
| |-> manage.py # Django management script
21+
| |-> index.py # Cloudflare Worker entrypoint
22+
| |-> app/ # Your Django project (rename as needed)
23+
| | |-> settings.py # Django settings, configured for D1
24+
| | |-> urls.py # Django URLs, includes management endpoints
25+
| | |-> wsgi.py # WSGI application
26+
| |-> your_django_apps/ # Add your Django apps here
27+
| |-> vendor/ # Project dependencies (managed by vendor.txt)
28+
|-> staticfiles/ # Collected static files (after build)
29+
|-> .gitignore
30+
|-> package.json # For Node.js dependencies like wrangler
31+
|-> uv.lock # Python dependencies lock file
32+
|-> pyproject.toml # Python project configuration
33+
|-> wrangler.jsonc # Wrangler configuration
34+
```
35+
36+
## Setup and Deployment
37+
38+
1. **Install Dependencies:**
39+
Ensure you have Node.js, npm, and Python installed. Then:
40+
41+
```bash
42+
# Install Node.js dependencies
43+
npm install
44+
45+
# Install Python dependencies
46+
uv sync
47+
```
48+
49+
If you don't have `uv` installed, install it first:
50+
```bash
51+
pip install uv
52+
```
53+
54+
2. **Configure `wrangler.jsonc`:**
55+
Review and update `wrangler.jsonc` for your project. Key sections:
56+
* `name`: Your worker's name.
57+
* `compatibility_date`: Keep this up-to-date.
58+
* `d1_databases`:
59+
* `binding`: The name used to access the D1 database in your worker (e.g., "DB").
60+
* `database_name`: The name of your D1 database in the Cloudflare dashboard.
61+
* `database_id`: The ID of your D1 database.
62+
63+
Example `d1_databases` configuration in `wrangler.jsonc`:
64+
```jsonc
65+
{
66+
"d1_databases": [
67+
{
68+
"binding": "DB",
69+
"database_name": "my-django-db",
70+
"database_id": "your-d1-database-id-here"
71+
}
72+
]
73+
}
74+
```
75+
76+
3. **Django Settings (`src/app/settings.py`):**
77+
The template should be configured to use D1 binding:
78+
```python
79+
# src/app/settings.py
80+
DATABASES = {
81+
'default': {
82+
'ENGINE': 'django_cf.db.backends.d1',
83+
# This name 'DB' must match the 'binding' in your wrangler.jsonc d1_databases section
84+
'CLOUDFLARE_BINDING': 'DB',
85+
}
86+
}
87+
```
88+
89+
4. **Worker Entrypoint (`src/index.py`):**
90+
This file contains the main worker handler for your Django application.
91+
```python
92+
from workers import WorkerEntrypoint
93+
from django_cf import DjangoCF
94+
95+
class Default(DjangoCF, WorkerEntrypoint):
96+
async def get_app(self):
97+
from app.wsgi import application
98+
return application
99+
```
100+
101+
5. **Run Development Server:**
102+
```bash
103+
npm run dev
104+
```
105+
This starts the local development server using Wrangler.
106+
107+
6. **Deploy to Cloudflare:**
108+
```bash
109+
npm run deploy
110+
```
111+
This command installs system dependencies and deploys your worker to Cloudflare.
112+
113+
## Running Management Commands
114+
115+
For D1, you can use the special management endpoints provided in the template:
116+
117+
* **`/__run_migrations__/`**: Triggers the `migrate` command.
118+
* **`/__create_admin__/`**: Creates a superuser (username: 'admin', password: 'password').
119+
120+
These endpoints are defined in `src/app/urls.py` and are protected by `user_passes_test(is_superuser)`. This means you must first create an admin user and be logged in as that user to access these endpoints.
121+
122+
**Initial Admin User Creation:**
123+
For the very first admin user creation, you might need to temporarily remove the `@user_passes_test(is_superuser)` decorator from `create_admin_view` in `src/app/urls.py`, deploy, access `/__create_admin__/`, and then reinstate the decorator and redeploy. Alternatively, modify the `create_admin_view` to accept a secure token or other mechanism for the initial setup if direct unauthenticated access is undesirable.
124+
125+
**Accessing the Endpoints:**
126+
Once deployed and an admin user exists (and you are logged in as them):
127+
- Visit `https://your-worker-url.com/__run_migrations__/` to apply migrations.
128+
- Visit `https://your-worker-url.com/__create_admin__/` to create the admin user if needed.
129+
130+
Check the JSON response in your browser to see the status of the command.
131+
132+
## Development Notes
133+
134+
* **D1 Limitations:**
135+
* **Transactions are disabled** for D1. Every query is committed immediately. This is a fundamental aspect of D1.
136+
* The D1 backend has some limitations compared to traditional SQLite or other SQL databases. Many advanced ORM features or direct SQL functions (especially those used in Django Admin) might not be fully supported. Refer to the `django-cf` README and official Cloudflare D1 documentation.
137+
* Django Admin functionality might be limited.
138+
* **Local Testing with D1:**
139+
* Wrangler allows local development and can simulate D1 access. `npx wrangler dev --remote` can connect to your actual D1 database for more accurate testing.
140+
* **Security:**
141+
* The management command endpoints are protected by Django's `user_passes_test(is_superuser)`. Ensure they are properly secured before deploying to production.
142+
* Protect your Cloudflare credentials and API tokens.
143+
144+
---
145+
*For more details on `django-cf` features and configurations, refer to the main [django-cf GitHub repository](https://github.com/G4brym/django-cf).*

16-django-with-d1/package.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "django-with-d1",
3+
"version": "0.0.0",
4+
"private": true,
5+
"scripts": {
6+
"deploy": "uv run pywrangler deploy",
7+
"dev": "uv run pywrangler dev",
8+
"start": "uv run pywrangler dev"
9+
},
10+
"devDependencies": {
11+
"wrangler": "^4.51.0"
12+
}
13+
}

16-django-with-d1/pyproject.toml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[project]
2+
name = "django-on-workers-with-d1"
3+
version = "0.1.0"
4+
description = "This template provides a starting point for running a Django application on Cloudflare Workers, utilizing Cloudflare D1 for serverless SQL database."
5+
requires-python = ">=3.12"
6+
readme = "README.md"
7+
dependencies = [
8+
"django-cf",
9+
"django==5.2.6",
10+
"tzdata",
11+
]
12+
13+
[dependency-groups]
14+
dev = [
15+
"workers-py",
16+
"workers-runtime-sdk"
17+
]

16-django-with-d1/src/__init__.py

Whitespace-only changes.

16-django-with-d1/src/app/__init__.py

Whitespace-only changes.

16-django-with-d1/src/app/asgi.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
ASGI config for app project.
3+
4+
It exposes the ASGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.asgi import get_asgi_application
13+
14+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
15+
16+
application = get_asgi_application()

0 commit comments

Comments
 (0)