Skip to content

Commit b2481fc

Browse files
committed
Update README.md
1 parent 1c60d96 commit b2481fc

File tree

5 files changed

+91
-185
lines changed

5 files changed

+91
-185
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ Utilize Durable Objects for stateful data persistence directly within your Cloud
131131
```python
132132
DATABASES = {
133133
'default': {
134-
'ENGINE': 'django_cf.do_binding',
134+
'ENGINE': 'django_cf.db.backends.do',
135135
}
136136
}
137137
```

django_cf/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __init__(self, ctx, env):
8181
self.ctx = ctx
8282
self.env = env
8383

84-
from django_cf.do_binding.storage import set_storage
84+
from django_cf.db.backends.do.storage import set_storage
8585
set_storage(self.ctx.storage.sql)
8686

8787
async def fetch(self, request):

templates/d1/README.md

Lines changed: 63 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ This template provides a starting point for running a Django application on Clou
88

99
This template is pre-configured to:
1010
- Use `django-cf` to bridge Django with Cloudflare's environment.
11-
- Employ Cloudflare D1 as the primary data store through the `django_cf.d1_binding` database engine.
11+
- Employ Cloudflare D1 as the primary data store through the `django_cf.db.backends.d1` database engine.
1212
- Include a basic Django project structure within the `src/` directory.
13-
- Provide example worker entrypoint (`src/worker.py`).
13+
- Provide example worker entrypoint (`src/index.py`).
1414

1515
## Project Structure
1616

1717
```
1818
template-root/
1919
|-> src/
2020
| |-> manage.py # Django management script
21-
| |-> worker.py # Cloudflare Worker entrypoint
21+
| |-> index.py # Cloudflare Worker entrypoint
2222
| |-> app/ # Your Django project (rename as needed)
2323
| | |-> settings.py # Django settings, configured for D1
2424
| | |-> urls.py # Django URLs, includes management endpoints
@@ -28,72 +28,49 @@ template-root/
2828
|-> staticfiles/ # Collected static files (after build)
2929
|-> .gitignore
3030
|-> package.json # For Node.js dependencies like wrangler
31-
|-> package-lock.json
32-
|-> requirements-dev.txt # Python dev dependencies
33-
|-> vendor.txt # Pip requirements for vendoring
31+
|-> uv.lock # Python dependencies lock file
32+
|-> pyproject.toml # Python project configuration
3433
|-> wrangler.jsonc # Wrangler configuration
3534
```
3635

3736
## Setup and Deployment
3837

3938
1. **Install Dependencies:**
40-
* **Node.js & Wrangler:** Ensure you have Node.js and npm installed. Then install dependencies with this command:
41-
```bash
42-
npm install
43-
```
44-
* **Python Dependencies (Vendoring):**
45-
List your Python dependencies (including `django` and `django-cf`) in `vendor.txt`.
46-
```txt
47-
# vendor.txt
48-
django~=5.0
49-
django-cf
50-
tzdata # For timezone support
51-
# Add other dependencies here
52-
```
53-
Install them into the `src/vendor` directory:
54-
```bash
55-
pip install -t src/vendor -r vendor.txt
56-
```
57-
58-
* **Python Dependencies (Local Development):**
59-
List your Python dev dependencies (including `django` and `django-cf`) in `requirements-dev.txt`.
60-
```txt
61-
# requirements-dev.txt
62-
django==5.1.2
63-
django-cf
64-
# For local D1 API access during development (e.g., running migrations)
65-
# Add other dev dependencies here
66-
```
67-
Install them:
68-
```bash
69-
pip install -r requirements-dev.txt
70-
```
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+
```
7153
7254
2. **Configure `wrangler.jsonc`:**
7355
Review and update `wrangler.jsonc` for your project. Key sections:
7456
* `name`: Your worker's name.
75-
* `main`: Should point to `src/worker.py`.
7657
* `compatibility_date`: Keep this up-to-date.
7758
* `d1_databases`:
7859
* `binding`: The name used to access the D1 database in your worker (e.g., "DB").
7960
* `database_name`: The name of your D1 database in the Cloudflare dashboard.
8061
* `database_id`: The ID of your D1 database.
81-
* `site`:
82-
* `bucket`: Points to `./staticfiles` for serving static assets.
83-
* `build`:
84-
* `command`: `"python src/manage.py collectstatic --noinput"` to automatically collect static files during deployment.
8562

8663
Example `d1_databases` configuration in `wrangler.jsonc`:
8764
```jsonc
88-
// ... other wrangler.jsonc configurations
89-
"d1_databases": [
90-
{
91-
"binding": "DB", // Must match CLOUDFLARE_BINDING in Django settings
92-
"database_name": "my-django-db",
93-
"database_id": "your-d1-database-id-here"
94-
}
95-
],
96-
// ...
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+
}
9774
```
9875

9976
3. **Django Settings (`src/app/settings.py`):**
@@ -102,103 +79,55 @@ template-root/
10279
# src/app/settings.py
10380
DATABASES = {
10481
'default': {
105-
'ENGINE': 'django_cf.d1_binding',
82+
'ENGINE': 'django_cf.db.backends.d1',
10683
# This name 'DB' must match the 'binding' in your wrangler.jsonc d1_databases section
10784
'CLOUDFLARE_BINDING': 'DB',
10885
}
10986
}
110-
111-
# Static files
112-
import os
113-
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
114-
STATIC_URL = '/static/'
115-
# STATIC_ROOT should point to the 'bucket' directory in wrangler.jsonc,
116-
# often one level above the 'src' directory.
117-
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles', 'static')
118-
119-
# Optional: Settings for local development using D1 API
120-
# You can create a separate settings_dev.py or use environment variables
121-
# DATABASES_DEV = {
122-
# 'default': {
123-
# 'ENGINE': 'django_cf.d1_api',
124-
# 'CLOUDFLARE_DATABASE_ID': '<your_database_id>',
125-
# 'CLOUDFLARE_ACCOUNT_ID': '<your_account_id>',
126-
# 'CLOUDFLARE_TOKEN': '<your_d1_api_token>',
127-
# }
128-
# }
12987
```
13088

131-
4. **Worker Entrypoint (`src/worker.py`):**
132-
This file contains the main `on_fetch` handler for your Django application.
89+
4. **Worker Entrypoint (`src/index.py`):**
90+
This file contains the main worker handler for your Django application.
13391
```python
134-
from django_cf import DjangoCFAdapter
92+
from workers import WorkerEntrypoint
93+
from django_cf import DjangoCF
13594
136-
async def on_fetch(request, env):
137-
# Ensure your Django project's WSGI application is importable
138-
# For example, if your project is 'app' inside 'src':
139-
from app.wsgi import application # Import application inside on_fetch
95+
class Default(DjangoCF, WorkerEntrypoint):
96+
async def get_app(self):
97+
from app.wsgi import application
98+
return application
99+
```
140100

141-
# The DjangoCFAdapter requires the Django application and the environment (for D1 binding)
142-
adapter = DjangoCFAdapter(application, env)
143-
return await adapter.handle_request(request)
101+
5. **Run Development Server:**
102+
```bash
103+
npm run dev
144104
```
105+
This starts the local development server using Wrangler.
145106

146-
5. **Deploy to Cloudflare:**
107+
6. **Deploy to Cloudflare:**
147108
```bash
148-
npx wrangler deploy
109+
npm run deploy
149110
```
150-
This command will also run the `collectstatic` command if configured in `wrangler.jsonc`.
111+
This command installs system dependencies and deploys your worker to Cloudflare.
151112

152113
## Running Management Commands
153114

154-
* **Migrations & `createsuperuser` (Local Development - Recommended for D1):**
155-
For D1, it's often easiest and safest to run migrations and `createsuperuser` from your local machine by configuring your development Django settings to use the D1 API.
156-
157-
1. Ensure you have `django-cf` and your other dependencies installed in your local Python environment (`pip install -r requirements-dev.txt`).
158-
2. Set up your Django settings for local D1 API access. You can do this by:
159-
* Creating a `settings_dev.py` and using `python src/manage.py migrate --settings=app.settings_dev`.
160-
* Or, by temporarily modifying your main `settings.py` (ensure you don't commit API keys).
161-
* Or, by using environment variables to supply D1 API credentials to your settings.
162-
163-
Example local D1 API settings in `settings_dev.py` (place it alongside your main `settings.py`):
164-
```python
165-
# app/settings_dev.py
166-
from .settings import * # Inherit base settings
167-
168-
DATABASES = {
169-
'default': {
170-
'ENGINE': 'django_cf.d1_api',
171-
'CLOUDFLARE_DATABASE_ID': 'your-actual-d1-database-id',
172-
'CLOUDFLARE_ACCOUNT_ID': 'your-cloudflare-account-id',
173-
'CLOUDFLARE_TOKEN': 'your-cloudflare-d1-api-token', # Ensure this token has D1 Read/Write permissions
174-
}
175-
}
176-
```
177-
3. Run commands:
178-
```bash
179-
# From the template root directory
180-
python src/manage.py migrate --settings=app.settings_dev
181-
python src/manage.py createsuperuser --settings=app.settings_dev
182-
```
183-
184-
* **Making Migrations (`makemigrations`):**
185-
When you need to generate new migration files based on your model changes, you should run `makemigrations`. However, because the D1 database engine (`django_cf.d1_binding` or `django_cf.d1_api`) requires a live connection to introspect the database schema (which might not be available or desirable during the `makemigrations` phase, especially in CI environments or when you only want to generate files without querying D1), you can use the `WORKERS_CI=1` environment variable. This variable signals `django-cf` to use a dummy database engine for schema-related operations that don't strictly need a live D1 connection, allowing `makemigrations` to run.
186-
187-
```bash
188-
# From the template root directory
189-
WORKERS_CI=1 python src/manage.py makemigrations --settings=app.settings_dev
190-
# Or, if you are not using settings_dev for this and your default settings.py is configured
191-
# WORKERS_CI=1 python src/manage.py makemigrations
192-
```
193-
After generating migration files, you can apply them using the `migrate` command as shown above (locally with D1 API access) or via a secured worker endpoint if you have one.
194-
195-
* **Via a Worker Endpoint (Use with Extreme Caution):**
196-
While possible, running migrations or creating users directly via a worker endpoint is generally **not recommended for D1** due to the direct database access available locally via the D1 API. If you absolutely must, you can adapt the management command endpoints from the Durable Objects template (`src/app/urls.py`), but ensure they are **extremely well-secured**.
197-
The main risk is exposing sensitive operations over HTTP and potential complexities with the worker environment.
198-
199-
If you choose this path, remember:
200-
* The worker needs the D1 binding (`env`) passed to the `DjangoCFAdapter` and accessible to your management command functions.
201-
* Secure the endpoints robustly (e.g., IP restrictions, strong authentication tokens, not just Django's `is_superuser` if the admin user might not exist yet).
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.
202131

203132
## Development Notes
204133

@@ -208,10 +137,9 @@ template-root/
208137
* Django Admin functionality might be limited.
209138
* **Local Testing with D1:**
210139
* Wrangler allows local development and can simulate D1 access. `npx wrangler dev --remote` can connect to your actual D1 database for more accurate testing.
211-
* Using the D1 API for local management tasks (as described above) is the most common workflow.
212140
* **Security:**
213-
* If you implement management command endpoints on your worker, secure them rigorously.
214-
* Protect your Cloudflare API tokens and credentials.
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.
215143
216144
---
217145
*For more details on `django-cf` features and configurations, refer to the main [django-cf GitHub repository](https://github.com/G4brym/django-cf).*

templates/durable-objects/README.md

Lines changed: 25 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ This template provides a starting point for running a Django application on Clou
88

99
This template is pre-configured to:
1010
- Use `django-cf` to bridge Django with Cloudflare's environment.
11-
- Employ Durable Objects as the primary data store through the `django_cf.do_binding` database engine.
11+
- Employ Durable Objects as the primary data store through the `django_cf.db.backends.do` database engine.
1212
- Include a basic Django project structure within the `src/` directory.
1313
- Provide example worker entrypoint (`src/worker.py`) and Durable Object class.
1414

@@ -37,66 +37,38 @@ template-root/
3737
## Setup and Deployment
3838

3939
1. **Install Dependencies:**
40-
* **Node.js & Wrangler:** Ensure you have Node.js and npm installed. Then install dependencies with this command:
41-
```bash
42-
npm install
43-
```
44-
* **Python Dependencies (Vendoring):**
45-
List your Python dependencies (including `django` and `django-cf`) in `vendor.txt`.
46-
```txt
47-
# vendor.txt
48-
django~=5.0
49-
django-cf
50-
tzdata # For timezone support
51-
# Add other dependencies here
52-
```
53-
Install them into the `src/vendor` directory:
54-
```bash
55-
pip install -t src/vendor -r vendor.txt
56-
```
57-
58-
* **Python Dependencies (Local Development):**
59-
List your Python dev dependencies (including `django` and `django-cf`) in `requirements-dev.txt`.
60-
```txt
61-
# requirements-dev.txt
62-
django==5.1.2
63-
django-cf
64-
```
65-
Install them:
66-
```bash
67-
pip install -r requirements-dev.txt
68-
```
40+
Ensure you have Node.js, npm, and Python installed. Then:
41+
42+
```bash
43+
# Install Node.js dependencies
44+
npm install
45+
46+
# Install Python dependencies
47+
uv sync
48+
```
49+
50+
If you don't have `uv` installed, install it first:
51+
```bash
52+
pip install uv
53+
```
6954
7055
2. **Configure `wrangler.jsonc`:**
7156
Review and update `wrangler.jsonc` for your project. Key sections:
7257
* `name`: Your worker's name.
73-
* `main`: Should point to `src/worker.py`.
7458
* `compatibility_date`: Keep this up-to-date.
7559
* `durable_objects`:
7660
* `bindings`: Ensure `name` (e.g., "DO_STORAGE") and `class_name` (e.g., "DjangoDO") are correctly set.
7761
* `migrations`: Define migrations for your Durable Object classes if you add or change them.
78-
* `site`:
79-
* `bucket`: Points to `./staticfiles` for serving static assets.
80-
* `build`: (To be added if not present)
81-
* `command`: `"python src/manage.py collectstatic --noinput"` to automatically collect static files during deployment.
8262

8363
3. **Django Settings (`src/app/settings.py`):**
8464
The template is pre-configured to use Durable Objects:
8565
```python
8666
# src/app/settings.py
8767
DATABASES = {
8868
'default': {
89-
'ENGINE': 'django_cf.do_binding',
69+
'ENGINE': 'django_cf.db.backends.do',
9070
}
9171
}
92-
93-
# Static files
94-
import os
95-
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
96-
STATIC_URL = '/static/'
97-
# STATIC_ROOT should point to the 'bucket' directory in wrangler.jsonc,
98-
# often one level above the 'src' directory.
99-
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles', 'static')
10072
```
10173

10274
4. **Worker Entrypoint (`src/worker.py`):**
@@ -122,11 +94,17 @@ template-root/
12294
return await stub.fetch(request) # Forward the request to the Durable Object
12395
```
12496

125-
5. **Deploy to Cloudflare:**
97+
5. **Run Development Server:**
98+
```bash
99+
npm run dev
100+
```
101+
This starts the local development server using Wrangler.
102+
103+
6. **Deploy to Cloudflare:**
126104
```bash
127-
npx wrangler deploy
105+
npm run deploy
128106
```
129-
This command will also run the `collectstatic` command if configured in `wrangler.jsonc`.
107+
This command installs system dependencies and deploys your worker to Cloudflare.
130108

131109
## Running Management Commands
132110

0 commit comments

Comments
 (0)