This is the full developer documentation for Ghuri
# Ghuri
> Django for TypeScript. Start on Cloudflare for almost nothing, move to Postgres on any server by changing settings, not code.
## Start on the edge, grow without a rewrite
Ghuri gives you the shape of Django (settings, installed apps, models with managers, migrations, `urls.ts`, class-based views, an admin, a REST framework, GraphQL) written in strict TypeScript and built on [Hono](https://hono.dev) and [Drizzle](https://orm.drizzle.team).
A new project runs on **Cloudflare Workers with D1, R2 and KV**. That costs close to nothing while you find out whether anyone wants what you are building. When you outgrow it, point `DATABASES` at Postgres, run `ghuri migrate`, copy your data with `ghuri dumpdata` and `ghuri loaddata`, and deploy the same code to Node on any VPS or container platform.
src/blog/models.ts
```ts
import { Model, CharField, TextField, DateTimeField, ForeignKey, CASCADE } from '@ghuri/orm'
import { User } from '@ghuri/auth'
export class Post extends Model({
title: new CharField({ maxLength: 200 }),
body: new TextField({ blank: true }),
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'posts' }),
createdAt: new DateTimeField({ autoNowAdd: true }),
}) {
static Meta = { ordering: ['-createdAt'] }
toString() { return this.title }
}
const recent = await Post.objects
.filter({ author__username: 'rifat', title__icontains: 'workers' })
.selectRelated('author')
.slice(0, 10)
```
## Batteries included
Models and migrations
A Django-style ORM with lazy, chainable QuerySets, `__` lookups across relations, `F`/`Q` expressions, aggregation and autodetected migrations. One codebase runs on D1, SQLite and Postgres.
The admin
`admin.site.register(Post)` gives you a server-rendered admin with search, filters, inlines, bulk actions and permissions. It runs on Workers with no build step.
REST framework
Serializers, viewsets, routers, permissions, pagination, filtering, throttling and an OpenAPI 3.1 schema. If you know DRF you already know the API.
GraphQL
graphene-django style types from your models, Relay connections with filters, mutations that reuse your REST serializers and permissions, DataLoaders and GraphiQL.
Auth
Users, groups and permissions, sessions, tokens and JWT. Password hashes use Django’s `pbkdf2_sha256` format, so you can bring your existing users with you.
Storage
`FileField` and `ImageField` backed by R2 on Cloudflare, or S3, MinIO or the local filesystem anywhere else.
Social login
Log in with GitHub, Google, Facebook, Microsoft and any OpenID Connect provider, like django-allauth, or build your own flows with Passport-style strategies.
WebSockets
Channels-style consumers routed in `urls.ts`, with rooms on Durable Objects that hibernate while idle. Send to any room from a view, a signal or a cron job.
Email
`sendMail()` and `EmailMessage` from `django.core.mail`, sent through Cloudflare Email Service, Resend or SMTP, with a test outbox.
Multi-tenancy
Tenant-scoped models and QuerySets that fail closed, with the tenant found from a subdomain, a custom domain or a header.
AI agents and MCP
Turn models and viewsets into agent tools that respect your permissions, and expose them to any MCP client with one URL pattern.
## Quick start
1. Create a project. The default template targets Cloudflare Workers with D1 and R2.
```sh
npm create ghuri@latest mysite
cd mysite
```
2. Create the database tables and an admin user. This runs against a local D1 database that Wrangler simulates on your machine.
```sh
npx ghuri migrate
npx ghuri createsuperuser
```
3. Start the development server.
```sh
npm run dev
```
Open `http://localhost:8787/admin/` and sign in. Add your first app with `npx ghuri startapp blog`; it is added to `INSTALLED_APPS` for you.
## One project, two homes
The only lines that change when you leave Cloudflare are in `settings.ts` and the entry file.
* Cloudflare Workers
src/settings.ts
```ts
DATABASES: { default: d1('DB') },
STORAGES: { default: r2('MEDIA') },
CACHES: { default: env.CACHE ? kvCache('CACHE') : memoryCache() },
```
* Node + Postgres
src/settings.ts
```ts
DATABASES: { default: postgres({ url: env.DATABASE_URL }) },
STORAGES: { default: s3({ endpoint, bucket, accessKeyId, secretAccessKey }) },
CACHES: { default: memoryCache() },
```
[Install Ghuri](https://ghurijs.github.io/docs/getting-started/installation/): Requirements and your first project.
[Tutorial: build a blog](https://ghurijs.github.io/docs/tutorial/part-1-models/): Models, migrations, admin, REST API, deploy.
[Ghuri for Django developers](https://ghurijs.github.io/docs/django-developers/): Python and TypeScript, side by side.
[GraphQL](https://ghurijs.github.io/docs/topics/graphql/): graphene-django style APIs from your models and serializers.
[Migrating from D1 to Postgres](https://ghurijs.github.io/docs/deployment/d1-to-postgres/): The escape hatch, step by step.
# What is Ghuri?
> Why Ghuri exists, what it is built on, and how its packages fit together.
Ghuri is a web framework for TypeScript that copies Django’s structure on purpose. A Ghuri project has a `settings.ts`, a list of `INSTALLED_APPS`, models with `objects` managers, migrations generated from those models, a `urls.ts` built from `path()` and `include()`, an admin you get by registering models, and a REST framework that reads like Django REST framework.
The name is Bengali for *kite* (ঘুড়ি): something light that flies high and stays on a string you control.
## Why another framework?
TypeScript has excellent building blocks (routers, query builders, validation libraries) and very few frameworks that decide how a whole application fits together. Django’s answers to that question have held up for twenty years. Ghuri takes those answers and fits them to a different runtime: serverless JavaScript at the edge.
Three ideas drive the design:
**Cloudflare first.** A new project runs on Cloudflare Workers with D1 (SQLite) for data, R2 for files and KV for cache. `npm run dev` starts `wrangler dev`; `ghuri deploy` ships it. For a small project that is free or close to it.
**Portability is a feature.** Your code never touches `env.DB` or `env.BUCKET`. Databases, storage, caches and the runtime sit behind adapters chosen in settings. Moving to Postgres on a VPS means changing `DATABASES`, running `ghuri migrate`, and copying your data with `ghuri dumpdata` and `ghuri loaddata`. Your models, views and serializers stay as they are.
**Django muscle memory.** Names, file layout and behaviour follow Django and DRF wherever TypeScript allows. Where TypeScript forces a change (options are `camelCase`, everything that touches the database is `async`), the change is mechanical and documented in [Ghuri for Django developers](https://ghurijs.github.io/docs/django-developers/).
## What it is built on
| Layer | Library |
| --------------------------------------- | --------------------------------------------------------------- |
| HTTP routing, middleware, JSX rendering | [Hono](https://hono.dev) |
| SQL generation and dialects | [Drizzle ORM](https://orm.drizzle.team) |
| Local development and deploys | [Wrangler](https://developers.cloudflare.com/workers/wrangler/) |
| Node runtime | `@hono/node-server` |
| AI agents | [Vercel AI SDK](https://ai-sdk.dev) |
You can always reach the layer below. A view receives a Hono `Context`, any Hono app can be mounted in `urlpatterns`, and `getDrizzle()` gives you the Drizzle database for a query the ORM cannot express.
## The packages
Ghuri is split into packages under the `@ghuri` npm scope. A new project installs the core set (`core`, `orm`, `auth`, `rest`, `storage`, `admin`, `cli`, plus `graphql` with `startproject --graphql`). You add the others when you want them, and can drop the ones you do not use.
| Package | Contains |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `@ghuri/core` | settings, app registry, URLs, views, middleware, request context, signals, cache, management command base, test client, Node adapter |
| `@ghuri/orm` | `Model`, fields, managers and QuerySets, relations, database adapters (D1, Postgres, SQLite, PGlite), migrations |
| `@ghuri/auth` | content types, users, groups, permissions, password hashing, sessions, tokens, JWT; REST authentication in `@ghuri/auth/rest` |
| `@ghuri/rest` | serializers, API views, viewsets, routers, permissions, pagination, filters, throttling, OpenAPI |
| `@ghuri/storage` | storage API with R2, S3, filesystem (`@ghuri/storage/fs`) and memory backends; `FileField`, `ImageField` |
| `@ghuri/admin` | the admin site, server-rendered with Hono JSX and htmx |
| `@ghuri/graphql` | GraphQL in graphene-django style: model types, Relay connections and filters, serializer mutations, GraphiQL |
| `@ghuri/realtime` | WebSockets in Django Channels style: consumers routed in `urls.ts`, rooms on Durable Objects, a channel layer |
| `@ghuri/oauth` | Passport.js-style login strategies: OAuth2, OpenID Connect, local, magic link, bearer |
| `@ghuri/socialauth` | social login like django-allauth: GitHub, Google, Microsoft and other providers, any OpenID Connect provider |
| `@ghuri/mail` | email like `django.core.mail`: `sendMail`, `EmailMessage`; Cloudflare Email, Resend, SMTP, console and test backends |
| `@ghuri/tenants` | shared-schema multi-tenancy: tenant-scoped models and QuerySets that fail closed, request resolvers, leak tests |
| `@ghuri/agents` | AI agents whose tools come from your models and viewsets; an MCP server |
| `@ghuri/cli` | the `ghuri` command |
| `create-ghuri` | `npm create ghuri@latest` |
Alpha software
Ghuri is at `0.1.0-alpha`. Packages publish under the `next` dist-tag, and APIs can still change between alpha releases. Pages that describe APIs most likely to move carry an **Alpha** note.
## Where to go next
* [Install Ghuri](https://ghurijs.github.io/docs/getting-started/installation/) and create a project.
* Work through the [tutorial](https://ghurijs.github.io/docs/tutorial/part-1-models/), which builds a blog with an admin and a REST API and deploys it to Cloudflare.
* If you already know Django, keep the [cheat sheet](https://ghurijs.github.io/docs/django-developers/) open in a tab.
# Installation
> Requirements, creating a project with npm create ghuri, and choosing a database.
## Requirements
* **Node.js 20 or later** (22 LTS recommended). The `ghuri` CLI and Wrangler run on Node even when your app runs on Workers.
* **npm**, pnpm, Bun or Yarn. The examples use npm.
* A **Cloudflare account** when you want to deploy to Workers. You do not need one to develop locally: `wrangler dev` simulates D1, R2 and KV on your machine.
* **Postgres 14+** only if you choose the Postgres template or deploy to a VPS.
## Create a project
```sh
npm create ghuri@latest mysite
```
`create-ghuri` asks for the project name, the database, the package manager, whether to install dependencies and whether to initialise a git repository (with an initial commit). Then it runs `ghuri startproject` for you and prints the next steps. You can answer the questions up front with flags:
```sh
npm create ghuri@latest mysite -- --db d1 # Cloudflare D1 + R2 (default)
npm create ghuri@latest mysite -- --db postgres # Postgres: Hyperdrive on Workers, DATABASE_URL elsewhere
npm create ghuri@latest mysite -- --db sqlite # Node.js project: better-sqlite3 + local files, no Cloudflare
```
| Option | Default | Meaning |
| ----------------------------- | ----------------------------------- | --------------------------------------------------------------------------------- |
| `[name]` | asked (`my-ghuri-app` with `--yes`) | Project name and directory. Letters, digits, `-` and `_`, starting with a letter. |
| `--db ` | `d1` | Database the generated `settings.ts`, `wrangler.jsonc` and `.dev.vars` use. |
| `--pm ` | the one you ran `create` with | Package manager for installing and for the printed commands. |
| `--install` / `--no-install` | yes | Install dependencies. |
| `--git` / `--no-git` | yes | `git init` plus an initial commit. |
| `-y`, `--yes` | | Never prompt; use defaults for anything not given. |
Prompts are skipped automatically when stdin is not a terminal (CI). You can also skip `create-ghuri` and run the CLI directly: `npx @ghuri/cli@next startproject mysite --db d1`.
The `--db` choice only decides what goes into the generated files, and every template already switches to Postgres when `DATABASE_URL` is set. You can change databases later by editing settings, so do not agonise over it. If you are unsure, take the default.
## Run it
```sh
cd mysite
npx ghuri migrate # create the tables for auth, sessions, tokens and the admin
npx ghuri createsuperuser # an admin user
npm run dev
```
`npm run dev` runs `ghuri runserver`, which starts `wrangler dev` on `http://localhost:8787` (for a `--db sqlite` project it runs `ghuri runserver --node` on `http://localhost:8000`). The root URL answers with a small JSON document from the home view in `src/urls.ts`; the admin is at `/admin/` and the REST API root at `/api/`.
Local development works with the placeholder `database_id` in `wrangler.jsonc`. You only need to run `npx wrangler d1 create mysite-db` and paste the real id when you [deploy](https://ghurijs.github.io/docs/tutorial/part-5-deploy/).
If you know Django
`npm create ghuri@latest mysite` is `django-admin startproject mysite`, and `npm run dev` is `python manage.py runserver`. Instead of `python manage.py ` you run `npx ghuri ` from the project root (or `npm run ghuri -- `).
## The secret key
Ghuri signs sessions, CSRF tokens and password reset links with `SECRET_KEY`. `startproject` generates a random one into `.dev.vars`, which Wrangler and the `ghuri` CLI both load:
.dev.vars
```ini
# Local development variables (read by wrangler and ghuri). Never commit this file.
SECRET_KEY=q3N…64 random characters…
DEBUG=true
```
`.dev.vars` is git-ignored; `.dev.vars.example` is the committed template for your teammates. For production you set the secret with `npx wrangler secret put SECRET_KEY` (Workers) or an environment variable (Node). Settings refuse to load without a `SECRET_KEY` unless `DEBUG` is on.
## Adding Ghuri to an existing Workers project
The `create-ghuri` template is the supported path, but nothing in it is magic. To add Ghuri by hand, install the packages under the `next` tag:
```sh
npm install @ghuri/core@next @ghuri/orm@next @ghuri/auth@next @ghuri/rest@next \
@ghuri/storage@next @ghuri/admin@next hono drizzle-orm
npm install -D @ghuri/cli@next wrangler typescript vitest
```
Then:
1. Make sure `wrangler.jsonc` has `"compatibility_flags": ["nodejs_compat"]`. Ghuri uses `AsyncLocalStorage` from `node:async_hooks` to carry the request context.
2. Add `"ghuri": { "settings": "src/settings.ts" }` to `package.json` so the CLI can find your settings (without it the CLI looks for `src/settings.ts`).
3. Write a `settings.ts` (see [Settings](https://ghurijs.github.io/docs/topics/settings/) and [Project layout](https://ghurijs.github.io/docs/getting-started/project-layout/)) and export `createApp(settings)` as the Worker’s default export.
The easiest way to get a correct starting point is to generate a throwaway project with `npx @ghuri/cli@next startproject scratch --no-install` and copy what you need from it.
## Editor setup
Ghuri is written for `strict` TypeScript with `moduleResolution: "bundler"`, and the generated `tsconfig.json` already has the right options:
tsconfig.json
```jsonc
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2023"],
"types": ["@cloudflare/workers-types", "node"],
"strict": true,
"skipLibCheck": true,
"isolatedModules": true,
"noEmit": true,
// Hono JSX for server-rendered views
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx"
// Ghuri uses standard (TC39) decorators: @admin.register, @action.
// You do not need "experimentalDecorators".
},
"include": ["src", "vitest.config.ts"]
}
```
`npm run typecheck` runs `tsc --noEmit` over the project.
## Next steps
Take a look at [what `startproject` generated](https://ghurijs.github.io/docs/getting-started/project-layout/), then start the [tutorial](https://ghurijs.github.io/docs/tutorial/part-1-models/).
# Project layout
> What ghuri startproject and ghuri startapp generate, file by file.
`npm create ghuri@latest mysite` (which runs `ghuri startproject`) produces this tree:
```plaintext
mysite/
├── package.json # scripts + "ghuri": { "settings": "src/settings.ts" }
├── wrangler.jsonc # Worker config: nodejs_compat, D1 "DB", R2 "MEDIA" (not for --db sqlite)
├── tsconfig.json
├── vitest.config.ts # `ghuri test` runs vitest (decorators enabled for tests)
├── .dev.vars # local secrets: a random SECRET_KEY, DEBUG=true (git-ignored)
├── .dev.vars.example # committed template of .dev.vars
├── .gitignore
├── README.md
└── src/
├── index.ts # Worker entry: export default createApp(settings)
├── server.ts # Node entry, for a VPS or Docker
├── settings.ts # the project's settings
└── urls.ts # root URL patterns (ROOT_URLCONF) and the REST router
```
The examples on this page are the default `--db d1` template. The `postgres` and `sqlite` variants differ only in `DATABASES`, `STORAGES` and the wrangler bindings.
## The project files
### `src/settings.ts`
Settings are a function of the environment. On Workers `env` holds your bindings and vars; on Node it is `process.env`. Read [Settings](https://ghurijs.github.io/docs/topics/settings/) for the full story.
src/settings.ts
```ts
import { AdminConfig } from '@ghuri/admin'
import {
AuthConfig, AuthenticationMiddleware, AuthTokenConfig, ContentTypesConfig,
SessionMiddleware, SessionsConfig,
} from '@ghuri/auth'
import { SessionAuthentication, TokenAuthentication } from '@ghuri/auth/rest'
import {
CommonMiddleware, CsrfMiddleware, defineSettings, kvCache, memoryCache,
SecurityMiddleware, XFrameOptionsMiddleware,
} from '@ghuri/core'
import { d1, postgres } from '@ghuri/orm'
import { IsAuthenticatedOrReadOnly, PageNumberPagination, RestFrameworkConfig } from '@ghuri/rest'
import { r2 } from '@ghuri/storage'
import { urlpatterns } from './urls'
export default defineSettings((env) => ({
SECRET_KEY: env.SECRET_KEY,
DEBUG: env.DEBUG === 'true',
ALLOWED_HOSTS: env.ALLOWED_HOSTS ? String(env.ALLOWED_HOSTS).split(',') : ['*'],
INSTALLED_APPS: [
ContentTypesConfig,
AuthConfig,
SessionsConfig,
AuthTokenConfig,
AdminConfig,
RestFrameworkConfig,
],
MIDDLEWARE: [
SecurityMiddleware,
CommonMiddleware,
SessionMiddleware,
CsrfMiddleware,
AuthenticationMiddleware,
XFrameOptionsMiddleware,
],
ROOT_URLCONF: urlpatterns,
DATABASES: {
// D1 on Cloudflare; set DATABASE_URL to use Postgres instead (Node / a VPS).
default: env.DATABASE_URL ? postgres({ url: env.DATABASE_URL }) : d1('DB'),
},
STORAGES: {
default: r2('MEDIA'),
},
MEDIA_URL: '/media/',
CACHES: {
// Workers KV when the CACHE binding exists, otherwise an in-memory cache.
default: env.CACHE ? kvCache('CACHE') : memoryCache(),
},
AUTH_USER_MODEL: 'auth.User',
REST_FRAMEWORK: {
DEFAULT_AUTHENTICATION_CLASSES: [SessionAuthentication, TokenAuthentication],
DEFAULT_PERMISSION_CLASSES: [IsAuthenticatedOrReadOnly],
DEFAULT_PAGINATION_CLASS: PageNumberPagination,
PAGE_SIZE: 20,
},
TIME_ZONE: 'UTC',
USE_TZ: true,
}))
```
The installed apps are Django’s `contenttypes`, `auth`, `sessions`, DRF’s `authtoken`, and `admin`. Their tables use Django’s names (`auth_user`, `django_session`, `authtoken_token`, `django_admin_log`, …). `AuthConfig` refuses to start without `ContentTypesConfig` before it.
With `--db postgres`, `DATABASES` reads `env.HYPERDRIVE ? postgres({ hyperdrive: 'HYPERDRIVE' }) : postgres({ url: env.DATABASE_URL })`. With `--db sqlite`, it is `sqlite({ filename: env.DATABASE_PATH ?? 'db.sqlite3' })` from `@ghuri/orm/sqlite` (or Postgres when `DATABASE_URL` is set), and `STORAGES` uses `fileSystemStorage({ location: 'media', baseUrl: '/media/' })` from `@ghuri/storage/fs`.
### `src/urls.ts`
The root URLconf. Unlike Django, `ROOT_URLCONF` is the pattern array itself, not a dotted module path, so the settings file imports it directly. The REST API router lives here too, next to the [OpenAPI](https://ghurijs.github.io/docs/topics/rest/openapi/) schema and its Swagger UI and Scalar pages.
src/urls.ts
```ts
import { admin } from '@ghuri/admin'
import { include, path } from '@ghuri/core'
import { DefaultRouter, ScalarView, SchemaView, SwaggerUIView } from '@ghuri/rest'
import type { Context } from 'hono'
/** REST API router: register viewsets here, e.g. `router.register('posts', PostViewSet)`. */
export const router = new DefaultRouter()
function home(c: Context) {
return c.json({ project: 'mysite', admin: '/admin/', api: '/api/', docs: '/api/docs/' })
}
export const urlpatterns = [
path('', home, { name: 'home' }),
path('admin/', admin.site.urls),
path('api/schema/', SchemaView.asView({ title: 'mysite API', version: '0.1.0' }), { name: 'schema' }),
path('api/docs/', SwaggerUIView.asView({ urlName: 'schema' }), { name: 'swagger-ui' }),
path('api/reference/', ScalarView.asView({ urlName: 'schema' }), { name: 'scalar' }),
path('api/', include(router.urls)),
]
```
### `src/index.ts` and `src/server.ts`
These are the equivalents of Django’s `wsgi.py`/`asgi.py`: the place a runtime enters your app.
src/index.ts
```ts
import { createApp } from '@ghuri/core'
import settings from './settings'
export default createApp(settings)
```
src/server.ts
```ts
import { createApp } from '@ghuri/core'
import { serve } from '@ghuri/core/node'
import settings from './settings'
serve(createApp(settings), {
port: Number(process.env.PORT ?? 8000),
env: process.env,
})
```
`createApp()` returns a Workers module handler with `fetch`, `scheduled` and `queue`, so `src/index.ts` also serves Cron Triggers and Queues. `npm start` runs `src/server.ts` on Node. You only ever use one of them in a given deployment. Keeping both in the project costs nothing and means the Node path is always one command away.
### `wrangler.jsonc`
Declares the Worker and the Cloudflare resources the default settings expect (comments trimmed):
wrangler.jsonc
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "mysite",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"compatibility_flags": ["nodejs_compat"],
"observability": { "enabled": true },
// Placeholder id: fine locally. Before deploying: npx wrangler d1 create mysite-db
"d1_databases": [
{ "binding": "DB", "database_name": "mysite-db", "database_id": "00000000-0000-0000-0000-000000000000" }
],
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "mysite-media" }],
// Optional KV cache: kvCache('CACHE') is used when the binding exists.
// "kv_namespaces": [{ "binding": "CACHE", "id": "" }],
"vars": { "DEBUG": "false" }
}
```
The binding names (`DB`, `MEDIA`, `CACHE`) are what settings refer to in `d1('DB')`, `r2('MEDIA')` and `kvCache('CACHE')`. The `postgres` template replaces `d1_databases` with a commented-out `hyperdrive` binding.
### `package.json`
package.json (excerpt)
```json
{
"type": "module",
"ghuri": { "settings": "src/settings.ts" },
"scripts": {
"dev": "ghuri runserver",
"deploy": "ghuri deploy",
"start": "node --import jiti/register src/server.ts",
"migrate": "ghuri migrate",
"makemigrations": "ghuri makemigrations",
"check": "ghuri check",
"test": "ghuri test",
"typecheck": "tsc --noEmit",
"ghuri": "ghuri"
}
}
```
The `ghuri.settings` key is how the CLI finds your project. It plays the role of `DJANGO_SETTINGS_MODULE`. In a `--db sqlite` project `dev` is `ghuri runserver --node` and there is no `deploy` script. `@ghuri/cli`, `wrangler` and `vitest` are dev dependencies, so `npx ghuri` uses the project’s own copy.
## Apps
Functionality lives in apps. `npx ghuri startapp blog` creates:
```plaintext
src/blog/
├── app.ts # BlogConfig (AppConfig subclass)
├── models.ts # commented-out example model
├── views.ts # an `index` view returning JSON
├── urls.ts # urlpatterns('blog', [...])
├── serializers.ts # REST serializers
├── admin.ts # ModelAdmin registrations
├── tests.ts # a vitest test for the index view
└── migrations/
└── index.ts # generated by makemigrations; do not edit by hand
```
and adds `BlogConfig` to `INSTALLED_APPS` in `src/settings.ts` (import plus list entry). Pass `--no-register` to skip that. It does not touch `src/urls.ts`; it prints the line to add. See [Applications](https://ghurijs.github.io/docs/topics/applications/).
If you know Django
The mapping is one to one: `apps.py` → `app.ts`, `settings.py` → `settings.ts`, `urls.py` → `urls.ts`, `wsgi.py` → `index.ts` / `server.ts`, `manage.py` → `npx ghuri`. The only new file is `wrangler.jsonc`, which describes the Cloudflare resources your Worker can use.
One structural difference: Ghuri apps are wired with ES imports rather than discovered from dotted strings. `AppConfig` imports its own `models`, `migrations` and `admin` modules, and `INSTALLED_APPS` holds classes, not strings. This is what lets a bundler build a Worker without any filesystem scanning at runtime.
## Why there is no `manage.py`
Workers have no filesystem and no long-running process, so commands cannot run “inside” the deployed app. The `ghuri` CLI runs on your machine, loads your settings with [jiti](https://github.com/unjs/jiti), builds the `env` from `wrangler.jsonc` bindings (local by default, remote with `--remote`) merged with `process.env`, `.dev.vars` and `.env` files, and then runs the command against that environment. See the [CLI reference](https://ghurijs.github.io/docs/reference/cli/).
# Ghuri for Django developers
> A side-by-side cheat sheet mapping Django and Django REST framework code to Ghuri.
If you know Django, you already know most of Ghuri. This page maps what you write in Python to what you write in TypeScript. Keep it open while you work through the [tutorial](https://ghurijs.github.io/docs/tutorial/part-1-models/).
## The rules of translation
Almost every difference comes from five mechanical rules:
1. **`snake_case` options and methods become `camelCase`.** `max_length` → `maxLength`, `order_by` → `orderBy`, `perform_create` → `performCreate`. Settings keys stay `UPPER_SNAKE`, and database columns stay `snake_case`.
2. **Keyword arguments become an object.** `filter(title__icontains='x')` → `filter({ title__icontains: 'x' })`. The `__` lookup syntax is unchanged.
3. **Anything that touches the database is `async`.** You `await` QuerySets, `get()`, `save()`, related objects (`await post.author`) and serializer output.
4. **Nothing is discovered by name.** Apps import their models, migrations and admin modules; `INSTALLED_APPS` holds classes; `ROOT_URLCONF` holds the pattern array.
5. **Settings are a function of `env`.** On Workers, configuration and resources arrive with each request, so `settings.ts` exports `defineSettings((env) => ({...}))`.
## Project and commands
| Django | Ghuri |
| --------------------------------------------------- | ------------------------------------------------------------------- |
| `django-admin startproject mysite` | `npm create ghuri@latest mysite` |
| `python manage.py startapp blog` | `npx ghuri startapp blog` |
| `python manage.py runserver` | `npm run dev` (`ghuri runserver`) |
| `python manage.py makemigrations` | `npx ghuri makemigrations` |
| `python manage.py migrate` | `npx ghuri migrate` (`--remote` for production D1) |
| `python manage.py createsuperuser` | `npx ghuri createsuperuser` |
| `python manage.py shell` | `npx ghuri shell` (top-level `await` works) |
| `python manage.py dumpdata > data.json` | `npx ghuri dumpdata > data.json` |
| `python manage.py loaddata data.json --database pg` | `npx ghuri loaddata data.json --database pg` |
| (dump + load between two aliases) | `npx ghuri copydata --from default --to pg` |
| `python manage.py test` | `npx ghuri test` (Vitest) |
| `python manage.py show_urls` (django-extensions) | `npx ghuri routes` |
| `python manage.py check --deploy` | `npx ghuri check --deploy` |
| `DJANGO_SETTINGS_MODULE` | `"ghuri": { "settings": "src/settings.ts" }` in `package.json` |
| `settings.py`, `urls.py`, `wsgi.py` | `settings.ts`, `urls.ts`, `index.ts` (Workers) / `server.ts` (Node) |
| `apps.py`, `models.py`, `admin.py` | `app.ts`, `models.ts`, `admin.ts` |
| `call_command('migrate')` | `await callCommand('migrate')` |
## Settings
settings.py
```python
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = os.environ.get('DEBUG') == '1'
INSTALLED_APPS = [
'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions',
'rest_framework.authtoken', 'django.contrib.admin', 'blog',
]
ROOT_URLCONF = 'mysite.urls'
DATABASES = {'default': dj_database_url.config()}
```
src/settings.ts
```ts
export default defineSettings((env) => ({
SECRET_KEY: env.SECRET_KEY,
DEBUG: env.DEBUG === 'true',
INSTALLED_APPS: [ContentTypesConfig, AuthConfig, SessionsConfig, AuthTokenConfig, AdminConfig, BlogConfig],
ROOT_URLCONF: urlpatterns,
DATABASES: { default: env.DATABASE_URL ? postgres({ url: env.DATABASE_URL }) : d1('DB') },
}))
```
| Django | Ghuri |
| -------------------------------------------------- | ----------------------------------------------------------------------- |
| `from django.conf import settings; settings.DEBUG` | `getSettings().DEBUG` |
| `getattr(settings, 'X', default)` | `setting('X', default)` |
| `os.environ['KEY']` | `env.KEY` in settings, `getEnv().KEY` elsewhere |
| `'django.contrib.auth'` and friends | `ContentTypesConfig`, `AuthConfig`, `SessionsConfig` from `@ghuri/auth` |
| `'rest_framework.authtoken'` | `AuthTokenConfig` from `@ghuri/auth` |
| `'django.contrib.admin'` | `AdminConfig` from `@ghuri/admin` |
## Models
models.py
```python
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
tags = models.ManyToManyField(Tag, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
```
models.ts
```ts
export class Post extends Model({
title: new CharField({ maxLength: 200 }),
slug: new SlugField({ unique: true }),
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'posts' }),
tags: new ManyToManyField(() => Tag, { blank: true }),
createdAt: new DateTimeField({ autoNowAdd: true }),
}) {
static Meta = { ordering: ['-createdAt'] }
toString() { return this.title }
}
```
| Django | Ghuri |
| ------------------------------------------ | ------------------------------------------------------------ |
| `models.CASCADE` | `CASCADE` (import from `@ghuri/orm`) |
| `post.author_id` | `post.authorId` |
| `post.author` | `await post.author` |
| `user.post_set.all()` | `await user.postSet.all()` (camelCase; or the `relatedName`) |
| `filter(post__title='x')` (reverse lookup) | `filter({ post__title: 'x' })` |
| `post.save(update_fields=['title'])` | `await post.save({ updateFields: ['title'] })` |
| `post.full_clean()` | `await post.fullClean()` |
| `Post._meta.get_field('title')` | `Post._meta.getField('title')` |
| `class Meta: abstract = True` | `static Meta = { abstract: true }` |
| `objects = PublishedManager()` | `static published = new PublishedManager()` |
| `def get_queryset(self)` (manager) | `getQueryset()` |
## Queries
| Django | Ghuri |
| ------------------------------------------------------ | ---------------------------------------------------------------------------- |
| `Post.objects.all()` | `await Post.objects.all()` |
| `Post.objects.filter(published=True)` | `await Post.objects.filter({ published: true })` |
| `.exclude(title__startswith='x')` | `.exclude({ title__startswith: 'x' })` |
| `.order_by('-created_at')` | `.orderBy('-createdAt')` |
| `qs[:10]` | `qs.slice(0, 10)` |
| `qs[10:20]` | `qs.slice(10, 20)` |
| `Post.objects.get(pk=1)` | `await Post.objects.get({ pk: 1 })` |
| `except Post.DoesNotExist:` | `catch (e) { if (e instanceof Post.DoesNotExist) ... }` |
| `get_object_or_404(Post, slug=s)` | `await getObjectOr404(Post.objects, { slug: s })` |
| `qs.first()`, `qs.count()`, `qs.exists()` | `await qs.first()`, `await qs.count()`, `await qs.exists()` |
| `qs.values('id', 'title')` | `await qs.values('id', 'title')` |
| `qs.values_list('id', flat=True)` | `await qs.valuesList('id', { flat: true })` |
| `Post.objects.create(title='x')` | `await Post.objects.create({ title: 'x' })` |
| `obj, created = get_or_create(slug=s, defaults={...})` | `const [obj, created] = await getOrCreate({ slug: s }, { defaults: {...} })` |
| `bulk_create([...])` | `await bulkCreate([...])` |
| `qs.update(published=True)` | `await qs.update({ published: true })` |
| `total, per_model = qs.delete()` | `const [total, perModel] = await qs.delete()` |
| `qs.in_bulk([1, 2])` (a `dict`) | `await qs.inBulk([1, 2])` (a `Map`) |
| `Q(a=1) \| Q(b=2)` | `Q({ a: 1 }).or(Q({ b: 2 }))` |
| `Q(a=1) & ~Q(c=3)` | `Q({ a: 1 }).and(Q.not({ c: 3 }))` |
| `F('views') + 1` | `F('views').add(1)` |
| `qs.annotate(n=Count('comments'))` | `qs.annotate({ n: Count('comments') })` |
| `qs.aggregate(Avg('views'))` | `await qs.aggregate({ avg: Avg('views') })` (always named) |
| `select_related('author')` | `selectRelated('author')` |
| `prefetch_related('tags')` | `prefetchRelated('tags')` |
| `for p in qs:` | `for await (const p of qs)` or `for (const p of await qs)` |
| `with transaction.atomic():` | `await atomic(async () => { ... })` (no rollback on D1, see below) |
| `transaction.on_commit(fn)` | `onCommit(fn)` |
| `connection.cursor().execute(sql, params)` | `(await connections.get()).execute(sql, params)` |
## URLs and views
| Django | Ghuri |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `path('posts//', view, name='detail')` | `path('posts//', view, { name: 'detail' })` |
| `re_path(r'^x/$', view)` | `rePath('^x/$', view)` |
| `include('blog.urls')` | `include(blogUrls)` (an imported module or array) |
| `app_name = 'blog'` | `export const urlpatterns = urlpatterns('blog', [...])` (or `export const appName = 'blog'`) |
| `reverse('blog:detail', kwargs={'id': 1})` | `reverse('blog:detail', { id: 1 })` |
| `def view(request, id):` | `function view(c: Context)` with `kwargs(c).id` |
| `request.GET.get('q')` | `c.req.query('q')` |
| `request.POST` | `await c.req.parseBody()` |
| `json.loads(request.body)` | `await c.req.json()` |
| `request.user` | `getUser(c)` |
| `request.session['k'] = v` | `c.get('session')` (see [Authentication](https://ghurijs.github.io/docs/topics/authentication/)) |
| `JsonResponse(data)` | `json(c, data)` or `c.json(data)` |
| `redirect('home')` | `redirect(c, 'home')` |
| `render(request, 'x.html', ctx)` | `c.html()` with Hono JSX |
| `raise Http404` | `throw new Http404()` |
| `class MyView(View): def get(self, request)` | `class MyView extends View { async get(c) }` |
| `MyView.as_view()` | `MyView.asView()` |
| `@login_required` | `loginRequired(view)` |
| `@permission_required('blog.add_post')` | `permissionRequired('blog.add_post')(view)` |
| `@csrf_exempt` | `csrfExempt(view)` |
| `@xframe_options_exempt` | `xframeOptionsExempt(view)` |
| `request.META['REMOTE_ADDR']` | `getRemoteAddr(c)` |
## Middleware
| Django | Ghuri |
| -------------------------------------------------------------------- | ----------------------------------------------- |
| `def __call__(self, request): response = self.get_response(request)` | `async handle(c, next) { await next(); c.res }` |
| `'django.middleware.security.SecurityMiddleware'` | `SecurityMiddleware` (from `@ghuri/core`) |
| `'django.contrib.sessions.middleware.SessionMiddleware'` | `SessionMiddleware` (from `@ghuri/auth`) |
| `'django.middleware.csrf.CsrfViewMiddleware'` | `CsrfMiddleware` |
| `django-cors-headers` | `CorsMiddleware` + `CORS` setting |
## Admin
| Django | Ghuri |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `admin.site.register(Post)` | `admin.site.register(Post)` |
| `@admin.register(Post)` | `@admin.register(Post)` |
| `class PostAdmin(admin.ModelAdmin)` | `class PostAdmin extends ModelAdmin` |
| `list_display = ('title', 'author')` | `listDisplay = ['title', 'author']` |
| `list_filter`, `search_fields` | `listFilter`, `searchFields` |
| `prepopulated_fields = {'slug': ('title',)}` | `prepopulatedFields = { slug: ['title'] }` |
| `inlines = [CommentInline]` | `inlines = [CommentInline]` |
| `class CommentInline(admin.TabularInline): model = Comment` | `class CommentInline extends TabularInline { model = Comment }` |
| `def has_change_permission(self, request, obj=None)` | `async hasChangePermission(c, obj?)` |
| `@admin.action(description='Publish')` | `action({ description: 'Publish' }, async (modelAdmin, c, queryset) => {...})` |
| `@admin.display(description='Title', boolean=True)` | `@display({ description: 'Title', boolean: true })` |
| `self.message_user(request, 'Done')` | `await this.messageUser(c, 'Done')` |
## Django REST framework
| DRF | Ghuri |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| `class PostSerializer(serializers.ModelSerializer)` | `class PostSerializer extends ModelSerializer` |
| `class Meta: model = Post; fields = [...]` | `static Meta = { model: Post, fields: [...] }` |
| `read_only_fields` | `readOnlyFields` |
| `serializers.CharField(source='author.username', read_only=True)` | `new CharField({ source: 'author.username', readOnly: true })` |
| `def validate_title(self, value)` | `validateTitle(value)` |
| `serializer.is_valid(raise_exception=True)` | `await serializer.isValid({ raiseException: true })` |
| `serializer.data` | `await serializer.getData()` |
| `serializer.validated_data` | `serializer.validatedData` |
| `serializer.save(author=request.user)` | `await serializer.save({ author: this.request.user })` |
| `class PostViewSet(viewsets.ModelViewSet)` | `class PostViewSet extends ModelViewSet` |
| `queryset`, `serializer_class` | `queryset`, `serializerClass` |
| `permission_classes = [IsAuthenticated]` | `permissionClasses = [IsAuthenticated]` |
| `IsAuthenticated \| IsAdminUser`, `&`, `~` | `IsAuthenticated.or(IsAdminUser)`, `.and(...)`, `.not()` |
| `def get_queryset(self)` | `getQueryset()` |
| `def perform_create(self, serializer)` | `async performCreate(serializer)` |
| `@action(detail=True, methods=['post'])` | `@action({ detail: true, methods: ['post'] })` |
| `def publish(self, request, pk=None)` | `async publish(request, kwargs)` |
| `self.request.data`, `self.request.query_params` | `this.request.data`, `this.request.query` |
| `router = DefaultRouter(); router.register(r'posts', PostViewSet)` | `const router = new DefaultRouter(); router.register('posts', PostViewSet)` |
| `path('api/', include(router.urls))` | `path('api/', include(router.urls))` |
| `@api_view(['GET'])` | `apiView(['GET'])(fn)` |
| `Response(data, status=201)` | `new APIResponse(data, 201)` (or return plain data) |
| `serializer = PostSerializer(posts, many=True)` | `new PostSerializer({ instance: posts, many: true })` |
| `REST_FRAMEWORK = {'PAGE_SIZE': 20}` | `REST_FRAMEWORK: { PAGE_SIZE: 20 }` |
| `drf-spectacular` | `SchemaView`, `SwaggerUIView`, `ScalarView` (built in) |
| `./manage.py generateschema --file openapi.yaml` | `npx ghuri generateschema --file openapi.yaml` (`RestFrameworkConfig` in `INSTALLED_APPS`) |
| `rest_framework.authtoken` | `TokenAuthentication`, `obtainAuthToken` from `@ghuri/auth/rest` |
| `djangorestframework-simplejwt` | `JWTAuthentication`, `TokenObtainPairView` from `@ghuri/auth/rest` |
## GraphQL (graphene-django)
| graphene-django | Ghuri (`@ghuri/graphql`) |
| ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `class PostType(DjangoObjectType): class Meta: model = Post; fields = (...)` | `class PostType extends ModelType { static Meta = { model: Post, fields: [...] } }` |
| `def resolve_title(self, info)` | `static resolveTitle(post, args, info)` |
| `get_queryset(cls, queryset, info)` | `static getQueryset(qs, info)` |
| `class Query(graphene.ObjectType)` per app, combined by inheritance | `class BlogQuery extends Query` + `new Schema({ query: [BlogQuery, …] })` |
| `relay.Node`, `DjangoFilterConnectionField(PostType)` + `filter_fields` | `interfaces: [Node]`, `ConnectionField(PostType)` + `Meta.filterFields` |
| `allPosts(title_Icontains: "x")` | `allPosts(filter: { title: { icontains: "x" } }, orderBy: ["-createdAt"])` |
| `SerializerMutation` with `serializer_class` | `SerializerMutation` with `serializerClass` (your REST serializer and permission classes) |
| `GraphQLView.as_view(graphiql=True)` | `GraphQLView.asView({ graphiql: true })` |
| `GRAPHENE = {'SCHEMA': 'mysite.schema.schema'}` | `GRAPHQL: { SCHEMA: schema }` |
| `./manage.py graphql_schema` | `npx ghuri graphql_schema` |
| `@login_required` (django-graphql-jwt) | `loginRequired(resolver)` |
| `graphene_file_upload`: `Upload` + `FileUploadGraphQLView` | `Upload` from `@ghuri/graphql`; `GraphQLView` handles the multipart request |
See [GraphQL](https://ghurijs.github.io/docs/topics/graphql/).
## Channels (WebSockets)
| Django Channels | Ghuri (`@ghuri/realtime`) |
| -------------------------------------------------------------- | ------------------------------------------------------------------ |
| `class ChatConsumer(AsyncJsonWebsocketConsumer)` | `class ChatConsumer extends JsonWebSocketConsumer` |
| `websocket_urlpatterns` + `URLRouter` in `asgi.py` | `path('ws/chat//', ChatConsumer.asView())` in `urls.ts` |
| `AuthMiddlewareStack`, `AllowedHostsOriginValidator` | `MIDDLEWARE` runs on the handshake; the Origin check is built in |
| `self.scope['user']`, `self.scope['url_route']['kwargs']` | `this.user`, `this.scope.params` |
| `group_add(group, self.channel_name)` in `connect` | `static room = (scope) => …` (one room per socket) |
| `channel_layer.group_send(group, {'type': 'chat.message', …})` | `channelLayer.groupSend(room, { type: 'chat.message', … })` |
| `async def chat_message(self, event)` | `async chatMessage(event)` |
| `CHANNEL_LAYERS` (Redis) | `REALTIME: { LAYER: durableObjectLayer('REALTIME') }` |
| `WebsocketCommunicator` | `WebSocketCommunicator` from `@ghuri/realtime/testing` |
Consumers are rebuilt for every event (Durable Objects hibernate), so keep per-connection data in `this.state`, not on `this`. See [WebSockets](https://ghurijs.github.io/docs/topics/websockets/).
## Auth
| Django | Ghuri |
| -------------------------------------------------- | ------------------------------------------------------------- |
| `from django.contrib.auth.models import User` | `import { User } from '@ghuri/auth'` |
| `get_user_model()` | `getUserModel()` |
| `User.objects.create_user(username, password=...)` | `await User.objects.createUser({ username, password })` |
| `user.set_password(pw)` / `check_password(pw)` | `await user.setPassword(pw)` / `await user.checkPassword(pw)` |
| `authenticate(request, username=u, password=p)` | `await authenticate(c, { username: u, password: p })` |
| `login(request, user)` / `logout(request)` | `await login(c, user)` / `await logout(c)` |
| `user.has_perm('blog.change_post')` | `await user.hasPerm('blog.change_post')` |
| `class User(AbstractUser)` | `Model({...}, { extends: AbstractUser })` + `AUTH_USER_MODEL` |
Password hashes use Django’s `pbkdf2_sha256$$$` format, so a user table copied from Django keeps working.
## Social login (django-allauth)
| django-allauth | Ghuri (`@ghuri/socialauth`) |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `allauth.socialaccount` + a provider app per provider | `SocialAuthConfig` (providers built in) |
| `SOCIALACCOUNT_PROVIDERS = {'github': {'APP': {...}}}` | `SOCIALACCOUNT: { PROVIDERS: { github: { APP: { clientId, secret } } } }` |
| `path('accounts/', include('allauth.urls'))` | `path('accounts/', include(socialUrls))` |
| `{% provider_login_url 'github' %}` | `reverse('socialaccount_login', { provider: 'github' })` (POST) |
| `SOCIALACCOUNT_AUTO_SIGNUP`, `…_EMAIL_AUTHENTICATION`, `…_STORE_TOKENS` | `AUTO_SIGNUP`, `EMAIL_AUTHENTICATION`, `STORE_TOKENS` |
| `DefaultSocialAccountAdapter` | `SocialAccountAdapter` |
See [Social login](https://ghurijs.github.io/docs/topics/social-login/). For custom flows (your own IdP, magic links, API keys) see [Login strategies](https://ghurijs.github.io/docs/topics/login-strategies/).
## OAuth provider (django-oauth-toolkit)
| django-oauth-toolkit | Ghuri (`@ghuri/oauth-provider`) |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `'oauth2_provider'` in `INSTALLED_APPS` | `OAuth2ProviderConfig` (app label `oauth2_provider`, tables `oauth2_provider_*`) |
| `path('o/', include('oauth2_provider.urls'))` | `path('oauth/', include(oauth2ProviderUrls))` plus `oauth2WellKnownUrls` at the root |
| `OAUTH2_PROVIDER = {'SCOPES': {...}, 'ACCESS_TOKEN_EXPIRE_SECONDS': ...}` | `OAUTH2_PROVIDER: { SCOPES: {...}, ACCESS_TOKEN_EXPIRE_SECONDS: ... }` |
| `Application`, `RefreshToken`, `skip_authorization` | `Application`, `RefreshToken`, `skipAuthorization` |
| `OAuth2Authentication`, `TokenHasScope`, `required_scopes` | `OAuth2Authentication`, `TokenHasScope`, `requiredScopes` (`@ghuri/oauth-provider/rest`) |
| `manage.py cleartokens` | `ghuri cleartokens` |
See [MCP server with OAuth](https://ghurijs.github.io/docs/topics/mcp-oauth/).
## Email
| Django | Ghuri (`@ghuri/mail`) |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `send_mail(subject, message, from_email, recipient_list, html_message=…)` | `await sendMail(subject, message, fromEmail, recipientList, { htmlMessage })` |
| `send_mass_mail(datatuple)`, `mail_admins()`, `mail_managers()` | `await sendMassMail(tuples)`, `await mailAdmins()`, `await mailManagers()` |
| `EmailMessage(subject, body, from_email, to, bcc, …)` | `new EmailMessage(subject, body, { fromEmail, to, bcc, … })` |
| `EmailMultiAlternatives` + `attach_alternative(html, 'text/html')` | `EmailMultiAlternatives` + `attachAlternative(html, 'text/html')` |
| `get_connection()` | `getConnection()` |
| `EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'` | `EMAIL_BACKEND: smtpBackend()` from `@ghuri/mail/smtp` (Node only) |
| console / locmem / dummy backends | `consoleBackend()`, `locmemBackend()`, `dummyBackend()` |
| `mail.outbox` in tests | `outbox` from `@ghuri/mail/testing` (with `useOutbox()`) |
On Workers, use `cloudflareEmailBackend()` or `resendBackend({ apiKey })`. There is no default SMTP backend. See [Sending email](https://ghurijs.github.io/docs/topics/email/).
## Multi-tenancy
Django has no built-in multi-tenancy. `@ghuri/tenants` uses one shared schema with a tenant foreign key on every row, like `django-multitenant` or `django-scopes`, rather than `django-tenants`’ schema per tenant, which D1 and SQLite cannot do.
| Django add-ons | Ghuri (`@ghuri/tenants`) |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `TenantModel` / a `tenant` FK on each model | `tenantModel({ field: 'store', to: () => Store })` as the model factory |
| `TenantMainMiddleware` (by domain) | `TenantMiddleware` + `TENANTS.RESOLVERS` (`HostResolver`, `SubdomainResolver`, `HeaderResolver`) |
| `with scope(store=s):` (django-scopes) | `await runAsTenant(s, async () => { … })` |
| `with scopes_disabled():` | `withoutTenant(() => …)` or `Model.unscoped` |
| `connection.set_tenant(t)` (django-tenants) | `activateTenant(t)` |
| `ScopeError` when no scope is active | `TenantNotSet`: queries fail closed |
See [Multi-tenancy](https://ghurijs.github.io/docs/topics/multi-tenancy/).
## Signals, cache, commands
| Django | Ghuri |
| ------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `@receiver(post_save, sender=Post)` | `receiver(postSave, { sender: Post })(fn)` |
| `post_save.connect(fn, sender=Post)` | `postSave.connect(fn, { sender: Post })` |
| `def fn(sender, instance, created, **kwargs)` | `async ({ sender, instance, created }) => {}` |
| `from django.core.cache import cache` | `import { cache } from '@ghuri/core'` |
| `cache.set('k', v, 300)` | `await cache.set('k', v, 300)` |
| `cache.get_or_set('k', fn, 300)` | `await cache.getOrSet('k', fn, 300)` |
| `class Command(BaseCommand): def handle(self, *args, **options)` | `class Command extends BaseCommand { async handle(args, io) }` |
| `def add_arguments(self, parser): parser.add_argument('--dry-run')` | `addArguments(parser) { parser.option('--dry-run') }` |
| `self.stdout.write(self.style.SUCCESS('ok'))` | `io.stdout(io.style.success('ok'))` |
| `raise CommandError('...')` | `throw new CommandError('...')` |
| cron job running a command | `onSchedule('0 3 * * *', fn)` + `triggers.crons` in `wrangler.jsonc` |
| Celery task consumer | `onQueue('emails', fn)` + a Cloudflare Queues consumer binding |
## Differences and limitations
These are the places where Ghuri behaves differently from Django on purpose, or has not caught up yet.
D1 transactions do not roll back
D1 has no interactive transactions. On D1, `atomic()` runs the callback directly: there is no isolation and **no rollback** if it throws (`onCommit` callbacks still run after it succeeds). For all-or-nothing writes on D1 use `(await connections.get()).batch([...])`. On SQLite and Postgres, `atomic()` is a real transaction with savepoints for nested blocks. See [Transactions](https://ghurijs.github.io/docs/topics/transactions/).
Migrations
`makemigrations` (including `--empty`, `--merge`, `--check`), `migrate` (including `--fake`, `--fake-initial`, `--plan`), `showmigrations`, `sqlmigrate` and `--database ` all work. **`squashmigrations` and `inspectdb` do not exist yet**, and neither do changes to a model’s primary key / auto field. Data migrations use `ops.RunCode(async (apps, conn, { using }) => {...})` instead of `RunPython`. Swappable models: `to=settings.AUTH_USER_MODEL` is `to: swappableModel('AUTH_USER_MODEL', 'auth.User')` and `swappable_dependency()` is `swappableDependency()`; it depends on the migration that creates the model rather than always `__first__`. A swapped model is not returned by `apps.getModel()`, and `Meta.swappable` may name a nested setting (`'AGENTS.CONVERSATION_MODEL'`).
Admin
No green “+” related-object popups, no `jsi18n`, no “show facets”, no `@` full-text search (treated as `icontains`). Templates are JSX components rather than overridable template files; customise through `ModelAdmin` options, hooks, CSS and custom views. See the [admin reference](https://ghurijs.github.io/docs/topics/admin-reference/).
MCP
The MCP server in `@ghuri/agents` authenticates with your REST authentication classes (for example `Authorization: Token `), or, in OAuth mode, with access tokens from `@ghuri/oauth-provider`. See [AI agents and MCP](https://ghurijs.github.io/docs/topics/agents-mcp/) and [MCP server with OAuth](https://ghurijs.github.io/docs/topics/mcp-oauth/).
OAuth provider
`@ghuri/oauth-provider` follows django-oauth-toolkit’s names and tables, with these differences:
* **`Grant` means something else.** In django-oauth-toolkit, `Grant` is the authorization code. Here `AuthorizationCode` is the code, and `Grant` is the user’s consent for a client (scopes, resource and app-defined `props`). Every refresh token belongs to a grant, and revoking the grant ends all of them.
* **Access tokens are not stored.** They are signed JWTs (RFC 9068) bound to a resource (`aud`), so there is no `AccessToken` model. Codes, refresh tokens and client secrets are stored as SHA-256 hashes.
* **OAuth 2.1 only.** The authorization code grant always requires PKCE `S256`, and refresh tokens always rotate, with reuse detection. There are no implicit, password, client-credentials or OpenID Connect flows.
* **Clients can register themselves**, through Client ID Metadata Documents and RFC 7591 dynamic registration, as MCP clients need.
Other differences:
* **Reverse accessors are camelCase**: `user.postSet`, not `user.post_set`. The lookup name is `post`.
* **`inBulk()` returns a `Map`** and **`delete()` returns `[total, perModel]`**.
* **Serializers are async**: `await serializer.isValid()`, `await serializer.getData()`.
* **Throttles do not trust `X-Forwarded-For` by default.** DRF uses the whole header when `NUM_PROXIES` is `None`; Ghuri ignores it unless `NUM_PROXIES` is set and identifies clients by `CF-Connecting-IP` on Cloudflare or the socket address on Node. See [throttling](https://ghurijs.github.io/docs/topics/rest/throttling/#client-ip-addresses).
* **Table names follow Django** (`auth_user`, `django_session`, `django_admin_log`), and password hashes and signed cookies are byte-compatible, so an existing Django database can be shared or migrated.
## Things that do not exist (yet)
* **Template language.** Use Hono JSX (`.tsx` views) or a frontend framework talking to the API.
* **Forms.** The admin and serializers cover validation; a standalone `@ghuri/forms` is on the roadmap.
* **Multi-table inheritance and proxy models.** Use abstract models and composition.
* **Database routers.** Multiple aliases in `DATABASES` work with `using()` and `--database `, but automatic routing is on the roadmap.
* **`squashmigrations`, `inspectdb`.**
* **Sync ORM calls.** Every database operation is `async`, everywhere.
* **i18n**, GIS, `contenttypes` generic relations beyond what auth needs.
# Part 1: Your first app and models
> Create a project, add a blog app, write a view, and define your first models.
This tutorial builds a small blog: posts with tags and comments, an admin to write them, a JSON API to read them, and a deployment to Cloudflare. It follows the same arc as Django’s “polls” tutorial, so if you have done that one, the steps will feel familiar.
By the end of this part you will have a project, a `blog` app with two views, and three models.
## Create the project
Make sure you have Node.js 20 or later (see [Installation](https://ghurijs.github.io/docs/getting-started/installation/)), then run:
```sh
npm create ghuri@latest mysite -- --db d1 --yes
cd mysite
npx ghuri migrate
npm run dev
```
`--yes` accepts the defaults (npm, install dependencies, initialise git); leave it out to answer the questions yourself. `startproject` already wrote a `.dev.vars` with a random `SECRET_KEY`, and `migrate` created the tables for the built-in apps (content types, users, sessions, tokens and the admin log) in a local D1 database.
Visit `http://localhost:8787/`. You should see `{"project":"mysite","admin":"/admin/","api":"/api/","docs":"/api/docs/"}`, which comes from the home view in `src/urls.ts`. Leave the server running; it reloads when you save files.
If you know Django
This is `django-admin startproject mysite` followed by `python manage.py migrate` and `python manage.py runserver`. The development server is `wrangler dev`, which runs your code in the same `workerd` runtime Cloudflare uses in production, with a local SQLite file standing in for D1.
## Create the blog app
A project is a collection of apps. Each app is a directory under `src/` that owns some models, views and URLs. Create one (in a second terminal, from the project root):
```sh
npx ghuri startapp blog
```
This writes `src/blog/` with `app.ts`, `models.ts`, `views.ts`, `urls.ts`, `serializers.ts`, `admin.ts`, `tests.ts` and a `migrations/index.ts`. Open `src/blog/app.ts`:
src/blog/app.ts
```ts
import { AppConfig } from '@ghuri/core'
import * as admin from './admin'
import * as migrations from './migrations'
import * as models from './models'
export class BlogConfig extends AppConfig {
name = 'blog'
verboseName = 'Blog'
path = import.meta.dirname
models = models
migrations = migrations
admin = admin
}
```
An `AppConfig` tells Ghuri what the app contains. Because a Worker is a bundle with no filesystem, apps import their own modules instead of having Ghuri discover them by name: whatever `models.ts` exports becomes the app’s models, and importing `admin.ts` registers its admin classes. `path` is only used by the CLI, to know where to write migration files.
`startapp` also installed the app for you: it added the import and the list entry to `src/settings.ts`.
src/settings.ts
```diff
// ...
import { r2 } from '@ghuri/storage'
import { urlpatterns } from './urls'
+import { BlogConfig } from './blog/app'
export default defineSettings((env) => ({
// ...
INSTALLED_APPS: [
ContentTypesConfig,
AuthConfig,
SessionsConfig,
AuthTokenConfig,
AdminConfig,
RestFrameworkConfig,
+ BlogConfig,
],
// ...the rest is unchanged
}))
```
If your settings file does not have the usual shape, `startapp` prints the two lines to add instead.
## Write your first view
Views are functions that receive a [Hono `Context`](https://hono.dev/docs/api/context) and return a `Response`. `startapp` created one in `src/blog/views.ts`; change its body:
src/blog/views.ts
```ts
import type { Context } from 'hono'
export function index(c: Context) {
return c.text("Hello, world. You're at the blog index.")
}
```
The app’s own URLconf, `src/blog/urls.ts`, already maps it:
src/blog/urls.ts
```ts
import { path, urlpatterns as patterns } from '@ghuri/core'
import { index } from './views'
export const urlpatterns = patterns('blog', [
path('', index, { name: 'index' }),
])
```
`urlpatterns('blog', [...])` (imported here as `patterns`) builds a pattern list with an `appName`, Django’s `app_name = 'blog'`. Include the app’s patterns from the root URLconf:
src/urls.ts
```diff
import { admin } from '@ghuri/admin'
import { include, path } from '@ghuri/core'
import { DefaultRouter } from '@ghuri/rest'
import type { Context } from 'hono'
+import { urlpatterns as blogUrls } from './blog/urls'
/** REST API router: register viewsets here, e.g. `router.register('posts', PostViewSet)`. */
export const router = new DefaultRouter()
function home(c: Context) {
return c.json({ project: 'mysite', admin: '/admin/', api: '/api/' })
}
export const urlpatterns = [
path('', home, { name: 'home' }),
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
+path('blog/', include(blogUrls)),
]
```
Visit `http://localhost:8787/blog/` and you will see the greeting.
`include()` accepts a pattern array or a module that exports `urlpatterns`. Because the blog patterns carry `appName = 'blog'`, their URL names live in the `blog` namespace, so elsewhere you can write `reverse('blog:index')`. Routes use Django’s syntax: `'posts//'` matches `/posts/42/` and gives you `id` as a number. Read more in [URLs and views](https://ghurijs.github.io/docs/topics/urls-and-views/).
If you know Django
`path()`, `include()`, `reverse()`, namespaces, `app_name` (here the first argument of `urlpatterns()`) and the `` converters all behave as in Django. The only change is that a view takes Hono’s `Context` (`c`) instead of an `HttpRequest`, and you reach the request through `c.req`.
## Define models
Now the interesting part. A blog needs posts, tags and comments. `src/blog/models.ts` contains a commented-out example; replace it with:
src/blog/models.ts
```ts
import {
BooleanField, CASCADE, CharField, DateTimeField, ForeignKey, Manager, ManyToManyField, Model,
type RelatedManager, SlugField, TextField,
} from '@ghuri/orm'
import { User } from '@ghuri/auth'
export class Tag extends Model({
name: new CharField({ maxLength: 50, unique: true }),
}) {
declare static objects: Manager
toString() {
return this.name
}
}
export class Post extends Model({
title: new CharField({ maxLength: 200 }),
slug: new SlugField({ unique: true }),
body: new TextField({ blank: true }),
published: new BooleanField({ default: false }),
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'posts' }),
tags: new ManyToManyField(() => Tag, { blank: true, relatedName: 'posts' }),
createdAt: new DateTimeField({ autoNowAdd: true }),
updatedAt: new DateTimeField({ autoNow: true }),
}) {
static Meta = { ordering: ['-createdAt'] }
declare static objects: Manager
declare comments: RelatedManager
toString() {
return this.title
}
}
export class Comment extends Model({
post: new ForeignKey(() => Post, { onDelete: CASCADE, relatedName: 'comments' }),
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'comments' }),
body: new TextField(),
approved: new BooleanField({ default: true }),
createdAt: new DateTimeField({ autoNowAdd: true }),
}) {
static Meta = { ordering: ['createdAt'] }
declare static objects: Manager
toString() {
return `Comment by ${this.authorId} on ${this.postId}`
}
}
```
A few things to notice:
* **`Model({...})` takes the fields and returns a base class.** You extend it to add methods and `Meta`. TypeScript infers instance properties from the fields, so `post.title` is a `string`, `post.published` a `boolean` and `post.createdAt` a `Date`.
* **Every model gets an `id` primary key** (`BigAutoField`) unless you mark a field `primaryKey: true`.
* **Options are camelCase.** Django’s `max_length`, `auto_now_add` and `related_name` become `maxLength`, `autoNowAdd` and `relatedName`. Columns in the database are still snake_case: `createdAt` is stored as `created_at`.
* **Relations take a function** (`() => User`) so models can refer to each other regardless of declaration order. A string such as `'auth.User'` also works.
* **A foreign key has two properties on instances**: `post.authorId` is the raw id, and `await post.author` loads the related `User`.
* **Reverse relations** get the name in `relatedName` (`user.posts`, `post.comments`). Without one, the default is camelCase `Set`, so it would be `user.postSet`.
* **`declare` lines are for TypeScript only.** Every model has an `objects` manager; `declare static objects: Manager` tells TypeScript that queries return `Post` instances with your methods, and `declare comments: RelatedManager` types the reverse side of `Comment.post`. Use `declare`, never a class field with an initializer.
If you know Django
This is almost a transliteration of a Django `models.py`. `class Meta:` becomes `static Meta = {...}`, `__str__` becomes `toString()`, and fields are passed to `Model()` rather than declared as class attributes. That last change is what lets TypeScript infer types for every field without a code generator.
Because `models` in `BlogConfig` is `import * as models from './models'`, all three classes are registered to the `blog` app automatically. Their database tables will be called `blog_tag`, `blog_post` and `blog_comment`, and the many-to-many table `blog_post_tags`.
## Try the models in a view
Models do nothing until their tables exist, which is the subject of [Part 2](https://ghurijs.github.io/docs/tutorial/part-2-migrations/). But you can already write the views that will list published posts and show one. Replace `src/blog/views.ts`:
src/blog/views.ts
```ts
import type { Context } from 'hono'
import { json } from '@ghuri/core'
import { getObjectOr404 } from '@ghuri/orm'
import { Post } from './models'
export async function index(c: Context) {
const posts = await Post.objects
.filter({ published: true })
.selectRelated('author')
.slice(0, 20)
return json(c, {
posts: await Promise.all(
posts.map(async (p) => ({ title: p.title, slug: p.slug, author: (await p.author).username })),
),
})
}
export async function detail(c: Context) {
const post = await getObjectOr404(Post.objects.filter({ published: true }), { slug: c.req.param('slug') })
return json(c, { title: post.title, body: post.body, createdAt: post.createdAt })
}
```
src/blog/urls.ts
```diff
import { path, urlpatterns as patterns } from '@ghuri/core'
import { detail, index } from './views'
export const urlpatterns = patterns('blog', [
path('', index, { name: 'index' }),
+path('/', detail, { name: 'detail' }),
])
```
Every database call is `async`: a QuerySet is lazy, and nothing touches the database until you `await` it. `selectRelated('author')` fetches each post’s author in the same query, so `await p.author` does not hit the database again. `getObjectOr404` raises `Http404` when nothing matches, which Ghuri turns into a 404 response.
Note
`src/blog/tests.ts`, which `startapp` generated, checks that `index` returns `{ app: 'blog' }`. It no longer does; you will replace that test in [Part 4](https://ghurijs.github.io/docs/tutorial/part-4-rest-api/#testing-the-api).
If you reload `/blog/` now you will get an error about a missing `blog_post` table. That is expected. Continue to [Part 2: Migrations](https://ghurijs.github.io/docs/tutorial/part-2-migrations/).
# Part 2: Migrations and the QuerySet API
> Create migrations from your models, apply them to D1, and explore the ORM in the shell.
In [Part 1](https://ghurijs.github.io/docs/tutorial/part-1-models/) you defined `Tag`, `Post` and `Comment`. Now you will turn them into tables and start querying them.
## Make migrations
```sh
npx ghuri makemigrations
```
```plaintext
Migrations for 'blog':
src/blog/migrations/0001_initial.ts
- Create model Tag
- Create model Post
- Create model Comment
```
`makemigrations` loads your project, replays every existing migration to build the *project state*, compares that state with your current models, and writes the difference as a new migration file. It also regenerates `src/blog/migrations/index.ts`, which re-exports every migration (plus an ordered `migrations` map) so the Worker bundle contains them without a filesystem.
Open the generated file:
src/blog/migrations/0001_initial.ts
```ts
import { Migration, operations as ops } from '@ghuri/orm/migrations'
export default new Migration({
initial: true,
dependencies: [['auth', '0001_initial']],
operations: [
ops.CreateModel({
name: 'Tag',
fields: {
id: { type: 'BigAutoField', primaryKey: true },
name: { type: 'CharField', maxLength: 50, unique: true },
},
}),
ops.CreateModel({
name: 'Post',
fields: {
id: { type: 'BigAutoField', primaryKey: true },
title: { type: 'CharField', maxLength: 200 },
slug: { type: 'SlugField', maxLength: 50, unique: true },
body: { type: 'TextField', blank: true },
published: { type: 'BooleanField', default: false },
author: { type: 'ForeignKey', to: 'auth.User', onDelete: 'CASCADE', relatedName: 'posts' },
tags: { type: 'ManyToManyField', to: 'blog.Tag', blank: true, relatedName: 'posts' },
createdAt: { type: 'DateTimeField', autoNowAdd: true },
updatedAt: { type: 'DateTimeField', autoNow: true },
},
options: { ordering: ['-createdAt'] },
}),
// ...Comment
],
})
```
Migrations describe changes in terms of models and fields, not SQL. That is what makes them portable: the same file produces SQLite DDL for D1 today and Postgres DDL after you move. Commit migration files to git along with the models they describe.
To see the SQL a migration will run, use `sqlmigrate`:
```sh
npx ghuri sqlmigrate blog 0001
npx ghuri sqlmigrate blog 0001 --dialect postgresql
```
## Apply migrations
```sh
npx ghuri migrate
```
```plaintext
Operations to perform:
Apply all migrations: admin, auth, authtoken, blog, contenttypes, sessions
Running migrations:
Applying blog.0001_initial...
blog.0001_initial OK
```
`migrate` applies every migration that has not been applied yet and records it in the `ghuri_migrations` table. The built-in apps were migrated in Part 1, so only `blog` is pending. Each migration runs atomically together with its record: in a transaction on SQLite and Postgres, as a single `batch()` on D1. By default the CLI talks to the **local** D1 database that `wrangler dev` uses (a SQLite file under `.wrangler/state/`). When you deploy in [Part 5](https://ghurijs.github.io/docs/tutorial/part-5-deploy/) you will run the same command with `--remote`.
`showmigrations` lists what is applied:
```sh
npx ghuri showmigrations blog
```
```plaintext
blog
[X] 0001_initial
```
If you know Django
The three-step workflow is identical: change `models.ts`, run `makemigrations`, run `migrate`. Migration files have the same operations (`CreateModel`, `AddField`, `AlterField`, `RunSQL`, …), the same dependency graph and the same `showmigrations` / `sqlmigrate` commands. Data migrations use `ops.RunCode(async (apps, conn, { using }) => {...})` instead of `RunPython`, and `apps.getModel('blog', 'Post')` gives you the historical model. `makemigrations --empty blog` creates a file to put it in.
## Play with the API
`ghuri shell` opens a Node REPL with your settings loaded, apps populated and every model in scope by class name, plus `apps`, `settings`, `env`, `core`, `orm` and `getModel()`. Top-level `await` works.
```sh
npx ghuri shell
```
First create a user to be the author. `User` (from `@ghuri/auth`) is in scope like every other installed model:
```ts
ghuri> const rifat = await User.objects.createUser({ username: 'rifat', password: 'correct horse' })
ghuri> rifat.pk
1
```
Create some posts. `create()` builds an instance, saves it, and returns it:
```ts
ghuri> const hello = await Post.objects.create({ title: 'Hello, Ghuri', slug: 'hello-ghuri', author: rifat })
ghuri> hello.id
1
ghuri> hello.createdAt
2026-11-12T08:14:03.201Z
ghuri> hello.published
false
```
You can also build an instance and save it yourself:
```ts
ghuri> const draft = new Post({ title: 'Edge databases', slug: 'edge-databases', authorId: rifat.pk })
ghuri> await draft.save()
ghuri> draft.body = 'D1 is SQLite, replicated.'
ghuri> await draft.save({ updateFields: ['body'] })
```
Query them back. A QuerySet is lazy and chainable; `await` runs it and gives you an array:
```ts
ghuri> await Post.objects.all()
[ Post { title: 'Edge databases' }, Post { title: 'Hello, Ghuri' } ]
ghuri> await Post.objects.filter({ title__startswith: 'Hello' })
[ Post { title: 'Hello, Ghuri' } ]
ghuri> await Post.objects.filter({ author__username: 'rifat' }).count()
2
ghuri> await Post.objects.get({ slug: 'nope' })
Uncaught Post.DoesNotExist: Post matching query does not exist.
ghuri> await Post.objects.inBulk([1, 2]) // a Map keyed by primary key
Map(2) { 1 => Post { title: 'Hello, Ghuri' }, 2 => Post { title: 'Edge databases' } }
```
Notice `author__username`: the double underscore follows the `author` foreign key to `User` and filters on its `username`, exactly like Django. Lookups such as `__startswith`, `__icontains`, `__gte` and `__in` are listed in the [lookup reference](https://ghurijs.github.io/docs/reference/lookups/).
Work with relations:
```ts
ghuri> const ts = await Tag.objects.create({ name: 'typescript' })
ghuri> const cf = await Tag.objects.create({ name: 'cloudflare' })
ghuri> await hello.tags.add(ts, cf)
ghuri> await hello.tags.all()
[ Tag { name: 'typescript' }, Tag { name: 'cloudflare' } ]
ghuri> await cf.posts.all() // reverse side, from relatedName: 'posts'
[ Post { title: 'Hello, Ghuri' } ]
ghuri> await rifat.posts.filter({ published: false }).count()
2
ghuri> await Comment.objects.create({ post: hello, author: rifat, body: 'First!' })
ghuri> await hello.comments.count()
1
```
Update and delete in bulk, straight from a QuerySet. `update()` returns the number of rows; `delete()` returns `[total, perModel]`, counting the rows removed by cascades too:
```ts
ghuri> await Post.objects.filter({ slug: 'hello-ghuri' }).update({ published: true })
1
ghuri> await Tag.objects.filter({ name: 'cloudflare' }).delete()
[ 2, { 'blog.Post_tags': 1, 'blog.Tag': 1 } ]
```
Aggregation and annotation look like Django’s too. The REPL cannot run `import` statements, so take `Count` from the `orm` module that the shell exposes:
```ts
ghuri> const { Count } = orm
ghuri> await Post.objects.annotate({ numComments: Count('comments') }).values('title', 'numComments')
[ { title: 'Edge databases', numComments: 0 }, { title: 'Hello, Ghuri', numComments: 1 } ]
```
If you know Django
The two systematic differences from Django’s ORM:
1. **Everything that touches the database is awaited.** `await qs`, `await qs.count()`, `await post.author`, `for await (const p of qs)`. Building a QuerySet (`filter`, `exclude`, `orderBy`) is synchronous and does no I/O.
2. **Keyword arguments become objects.** `filter(title__icontains='x')` is `filter({ title__icontains: 'x' })`. `order_by` is `orderBy`, `select_related` is `selectRelated`, and `qs[:10]` is `qs.slice(0, 10)`.
## Check the views
Publish a post in the shell, then exit with `.exit` and reload `http://localhost:8787/blog/`. The index view from Part 1 now returns the published post, and `/blog/hello-ghuri/` returns its detail. An unknown slug returns a 404.
## Changing a model
Suppose you want a short summary on each post. Add a field:
src/blog/models.ts
```diff
export class Post extends Model({
title: new CharField({ maxLength: 200 }),
slug: new SlugField({ unique: true }),
+ summary: new CharField({ maxLength: 300, blank: true, default: '' }),
// ...
```
and run the workflow again:
```sh
npx ghuri makemigrations
npx ghuri migrate
```
`makemigrations` writes `0002_post_summary.ts` containing a single `ops.AddField`. On SQLite and D1, operations that SQLite cannot do with `ALTER TABLE` (changing a column type, for example) are applied by rebuilding the table, the same strategy Django uses. You do not have to think about it, but it is why large tables on D1 deserve a look at `sqlmigrate` output before you run a migration in production. More in [Migrations](https://ghurijs.github.io/docs/topics/migrations/).
Next, give yourself a way to edit posts without the shell: [Part 3: The admin](https://ghurijs.github.io/docs/tutorial/part-3-admin/).
# Part 3: The admin
> Create a superuser, register models with the admin and customise the change list and forms.
Ghuri ships an admin modelled on Django’s: a staff-only site that lets trusted users create, edit and delete your models. It is rendered on the server with Hono JSX and enhanced with htmx, so it runs on Workers and needs no frontend build.
## Create an admin user
```sh
npx ghuri createsuperuser
```
```plaintext
Username: admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.
```
Visit `http://localhost:8787/admin/` and log in. You will see the **Authentication and Authorization** section with Users and Groups. The admin registers those itself because `AuthConfig` is installed. Your blog models are not there yet.
`createsuperuser` also works without prompts, which is handy in scripts and CI: `GHURI_SUPERUSER_PASSWORD=… npx ghuri createsuperuser --no-input --username admin --email admin@example.com`.
## Register the blog models
Open `src/blog/admin.ts`, which `startapp` created with a commented-out example, and register the models:
src/blog/admin.ts
```ts
import { admin } from '@ghuri/admin'
import { Post, Tag, Comment } from './models'
admin.site.register(Post)
admin.site.register(Tag)
admin.site.register(Comment)
```
`BlogConfig` already imports this module (`admin = admin` in `app.ts`), and importing it is what runs the `register` calls. Reload the admin index and a **Blog** section appears with all three models.
Click **Posts**. The change list shows each post using its `toString()`. Click one to get a form generated from the model fields: a text input for `title`, a textarea for `body`, a checkbox for `published`, a select for `author` and a multi-select for `tags`. Required fields, `maxLength` and `unique` are validated on save, and errors show next to the field.
Note
Unlike Django, related-object selects have no green “+” button to create a related object in a popup. Create the tag first (or use an inline), then pick it.
The **History** link on each object lists every change made through the admin, recorded in the `LogEntry` model.
## Customise the admin
The defaults are useful, but the admin becomes much better once you tell it about your data. Replace the `Post` registration with a `ModelAdmin` class:
src/blog/admin.ts
```ts
import { action, admin, ModelAdmin, TabularInline } from '@ghuri/admin'
import { Post, Tag, Comment } from './models'
class CommentInline extends TabularInline {
model = Comment
extra = 0
fields = ['author', 'body', 'approved']
}
const makePublished = action(
{ description: 'Mark selected posts as published', permissions: ['change'] },
async (modelAdmin, c, queryset) => {
const n = await queryset.update({ published: true })
await modelAdmin.messageUser(c, `${n} posts were published.`, 'success')
},
)
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
listDisplay = ['title', 'author', 'published', 'createdAt']
listFilter = ['published', 'createdAt', 'tags']
searchFields = ['title', 'body', 'author__username']
prepopulatedFields = { slug: ['title'] }
readonlyFields = ['createdAt', 'updatedAt']
fieldsets = [
[null, { fields: ['title', 'slug', 'body'] }],
['Publishing', { fields: ['author', 'tags', 'published', 'createdAt', 'updatedAt'], classes: ['collapse'] }],
]
inlines = [CommentInline]
actions = [makePublished]
dateHierarchy = 'createdAt'
ordering = ['-createdAt']
listPerPage = 50
}
@admin.register(Tag)
export class TagAdmin extends ModelAdmin {
searchFields = ['name']
}
admin.site.register(Comment)
```
Reload the post list. You now have:
* **Columns** for title, author, published and created date, sortable by clicking the header.
* A **filter sidebar** for published, created date and tags.
* A **search box** that searches title, body and the author’s username.
* A **date hierarchy** above the list to drill down by year, month and day.
* An **action** in the bulk actions menu, next to the built-in “Delete selected”.
On the change form, the slug fills itself in as you type a title, the publishing fields sit in a collapsible fieldset, and comments are edited inline at the bottom.
If you know Django
`ModelAdmin` options use the same names in camelCase: `list_display` → `listDisplay`, `search_fields` → `searchFields`, `prepopulated_fields` → `prepopulatedFields`, and so on. `@admin.register(Post)` is the decorator you know. It works as a standard TC39 decorator (what wrangler and esbuild emit, so the build needs no `experimentalDecorators` flag) and as a legacy one: Vitest transpiles with oxc, which only lowers legacy decorators so far, so the generated `vitest.config.ts` sets `oxc: { decorator: { legacy: true } }` for `ghuri test`. `action({ description, permissions }, fn)` is `@admin.action(description=..., permissions=[...])`, and actions receive `(modelAdmin, c, queryset)` where Django passes `(modeladmin, request, queryset)`.
## Permissions
The admin is for staff only: a user needs `isStaff` to log in, and then sees only the models they have permissions for. Ghuri creates four permissions for every model after `migrate`: `blog.add_post`, `blog.change_post`, `blog.delete_post` and `blog.view_post`. Superusers have all of them.
To give an editor access to posts but not comments, create a group in the admin, give it the post permissions, and add the user to it. For finer control, override the permission hooks:
src/blog/admin.ts
```ts
import type { Context } from 'hono'
import { getUser } from '@ghuri/core'
export class PostAdmin extends ModelAdmin {
// ...
async hasChangePermission(c: Context, obj?: Post) {
if (obj && obj.authorId !== getUser(c).pk) return getUser(c).isSuperuser ?? false
return super.hasChangePermission(c, obj)
}
}
```
Read [The admin](https://ghurijs.github.io/docs/topics/admin/) for inlines, custom sites, autocomplete and file uploads, and the [admin reference](https://ghurijs.github.io/docs/topics/admin-reference/) for every `ModelAdmin` option.
Next: [Part 4: A REST API](https://ghurijs.github.io/docs/tutorial/part-4-rest-api/).
# Part 4: A REST API
> Expose posts, tags and comments as a JSON API with serializers, viewsets, routers, permissions and token authentication.
The blog has an admin for writers. Readers, mobile apps and frontends need an API. In this part you will build one with `@ghuri/rest`, which follows Django REST framework closely.
## Serializers
A serializer turns model instances into JSON-ready objects and validates incoming data before it reaches your models. Open `src/blog/serializers.ts`:
src/blog/serializers.ts
```ts
import {
CharField, ModelSerializer, SerializerMethodField, SlugRelatedField, ValidationError,
} from '@ghuri/rest'
import { Comment, Post, Tag } from './models'
export class TagSerializer extends ModelSerializer {
static Meta = { model: Tag, fields: ['id', 'name'] }
}
export class CommentSerializer extends ModelSerializer {
static Meta = { model: Comment, fields: ['id', 'post', 'authorName', 'body', 'createdAt'], readOnlyFields: ['post'] }
authorName = new CharField({ source: 'author.username', readOnly: true })
}
export class PostSerializer extends ModelSerializer {
static Meta = {
model: Post,
fields: ['id', 'title', 'slug', 'summary', 'body', 'published', 'authorName', 'tags', 'commentCount', 'createdAt'],
}
authorName = new CharField({ source: 'author.username', readOnly: true })
tags = new SlugRelatedField({ slugField: 'name', many: true, queryset: Tag.objects.all(), required: false })
commentCount = new SerializerMethodField()
async getCommentCount(post: Post) {
return post.comments.filter({ approved: true }).count()
}
validateTitle(value: string) {
if (value.toLowerCase().includes('lorem ipsum')) {
throw new ValidationError('Write a real title.')
}
return value
}
}
```
`ModelSerializer` reads the model’s fields and builds matching serializer fields, with the same validation rules (`maxLength`, `unique`, choices). You override or add fields as class properties: here `authorName` follows the `author` relation, `tags` uses tag names instead of ids, and `commentCount` is computed by a method named `get`.
`validate` methods validate a single field, and `validate(attrs)` validates the object as a whole.
Here is what using it looks like (the shell only preloads models, so try this in a test or a view):
```ts
const s = new PostSerializer(await Post.objects.get({ slug: 'hello-ghuri' }))
await s.getData()
// { id: 1, title: 'Hello, Ghuri', slug: 'hello-ghuri', summary: '', body: '', published: true,
// authorName: 'rifat', tags: ['typescript'], commentCount: 1, createdAt: '2026-11-12T08:14:03.201Z' }
const input = new PostSerializer({ data: { title: 'lorem ipsum', slug: 'hello-ghuri' } })
await input.isValid() // false
input.errors
// { title: ['Write a real title.'], slug: ['post with this slug already exists.'] }
await input.isValid({ raiseException: true }) // throws ValidationError: a 400 response in a view
```
A model instance can be passed directly; the full form is `new PostSerializer({ instance, data, partial, context, many })`.
Serializing is asynchronous (`await s.getData()`), because fields such as `authorName` and `commentCount` may need the database. That is the main difference from DRF, where `serializer.data` is a plain property.
## Viewsets
A viewset groups the views for one resource. `ModelViewSet` provides `list`, `create`, `retrieve`, `update`, `partialUpdate` and `destroy`. Add these to `src/blog/views.ts` (the function views from Part 1 can stay):
src/blog/views.ts
```ts
import {
action, APIResponse, type APIRequest, FieldFilter, IsAdminUser, IsAuthenticatedOrReadOnly,
ModelViewSet, OrderingFilter, ReadOnlyModelViewSet, SearchFilter,
} from '@ghuri/rest'
import { Post, Tag } from './models'
import { IsAuthorOrReadOnly } from './permissions'
import { CommentSerializer, PostSerializer, TagSerializer } from './serializers'
export class PostViewSet extends ModelViewSet {
serializerClass = PostSerializer
permissionClasses = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly.or(IsAdminUser)]
filterBackends = [SearchFilter, OrderingFilter, FieldFilter]
searchFields = ['title', 'body']
orderingFields = ['createdAt', 'title']
filtersetFields = ['published', 'tags__name']
lookupField = 'slug'
getQueryset() {
const qs = Post.objects.selectRelated('author').prefetchRelated('tags')
// Anonymous readers only see published posts; signed-in users also see drafts.
const user = this.request.user
return user.isAuthenticated ? qs : qs.filter({ published: true })
}
async performCreate(serializer: PostSerializer) {
await serializer.save({ author: this.request.user })
}
@action({ detail: true, methods: ['post'] })
async publish(request: APIRequest) {
const post = await this.getObject()
post.published = true
await post.save({ updateFields: ['published'] })
return new APIResponse({ status: 'published' })
}
@action({ detail: true, methods: ['get', 'post'] })
async comments(request: APIRequest) {
const post = await this.getObject()
if (request.method === 'POST') {
const serializer = new CommentSerializer({ data: request.data })
await serializer.isValid({ raiseException: true })
await serializer.save({ post, author: request.user })
return new APIResponse(await serializer.getData(), 201)
}
const comments = await post.comments.filter({ approved: true }).selectRelated('author')
return new APIResponse(await new CommentSerializer({ instance: comments, many: true }).getData())
}
}
export class TagViewSet extends ReadOnlyModelViewSet {
queryset = Tag.objects.all()
serializerClass = TagSerializer
}
```
Handlers, including `@action` methods, receive the REST `request` (`request.data`, `request.user`, `request.query`, and the Hono context as `request.c`); `this.request` is the same object. `@action` is a standard TC39 decorator; without decorators, write `static actions = { publish: action({ detail: true, methods: ['post'] }) }`.
A custom permission keeps people from editing each other’s posts. Create `src/blog/permissions.ts`:
src/blog/permissions.ts
```ts
import { type APIRequest, BasePermission, SAFE_METHODS } from '@ghuri/rest'
import type { Post } from './models'
export class IsAuthorOrReadOnly extends BasePermission {
message = 'Only the author can change this post.'
hasObjectPermission(request: APIRequest, _view: unknown, post: Post) {
if (SAFE_METHODS.includes(request.method)) return true
return post.authorId === request.user.pk
}
}
```
Permission classes compose like DRF’s `&`, `|` and `~` operators through static helpers: `IsAuthorOrReadOnly.or(IsAdminUser)` lets staff edit any post, and `.and()` and `.not()` work the same way. Each returns a new permission class.
## Routers
A router generates URL patterns for a viewset. The project already has one: `src/urls.ts` exports a `DefaultRouter` mounted at `api/`. Register the viewsets there:
src/urls.ts
```diff
import { admin } from '@ghuri/admin'
import { include, path } from '@ghuri/core'
import { DefaultRouter, ScalarView, SchemaView, SwaggerUIView } from '@ghuri/rest'
import type { Context } from 'hono'
+import { PostViewSet, TagViewSet } from './blog/views'
import { urlpatterns as blogUrls } from './blog/urls'
/** REST API router: register viewsets here, e.g. `router.register('posts', PostViewSet)`. */
export const router = new DefaultRouter()
+router.register('posts', PostViewSet)
+router.register('tags', TagViewSet)
function home(c: Context) {
return c.json({ project: 'mysite', admin: '/admin/', api: '/api/', docs: '/api/docs/' })
}
export const urlpatterns = [
path('', home, { name: 'home' }),
path('admin/', admin.site.urls),
path('api/schema/', SchemaView.asView({ title: 'mysite API', version: '0.1.0' }), { name: 'schema' }),
path('api/docs/', SwaggerUIView.asView({ urlName: 'schema' }), { name: 'swagger-ui' }),
path('api/reference/', ScalarView.asView({ urlName: 'schema' }), { name: 'scalar' }),
path('api/', include(router.urls)),
path('blog/', include(blogUrls)),
]
```
You now have:
| URL | Name | Methods |
| ------------------------------- | ------------------------ | ------------------------------- |
| `/api/` | `api-root` | `GET` (API root) |
| `/api/posts/` | `post-list` | `GET`, `POST` |
| `/api/posts//` | `post-detail` | `GET`, `PUT`, `PATCH`, `DELETE` |
| `/api/posts//publish/` | `post-publish` | `POST` |
| `/api/posts//comments/` | `post-comments` | `GET`, `POST` |
| `/api/tags/`, `/api/tags//` | `tag-list`, `tag-detail` | `GET` |
```sh
curl 'http://localhost:8787/api/posts/?search=ghuri&ordering=-createdAt'
curl 'http://localhost:8787/api/posts/?tags__name=typescript'
```
List responses are paginated by the project’s `PageNumberPagination` setting: `{ "count": …, "next": …, "previous": …, "results": [ … ] }`. Open `/api/posts/` in a browser to get the browsable API.
If you know Django
This is DRF: `ModelSerializer` with `class Meta` as `static Meta`, `ModelViewSet`, `@action`, `DefaultRouter().register()`, `perform_create` as `performCreate`, `get_queryset` as `getQueryset`. Two things are async that are not in DRF: `isValid()` (unique validators query the database) and reading output with `getData()`. `Response` is called `APIResponse` so it does not shadow fetch’s `Response`.
## Authentication
The generated settings already configure the REST framework for you:
src/settings.ts (excerpt)
```ts
REST_FRAMEWORK: {
DEFAULT_AUTHENTICATION_CLASSES: [SessionAuthentication, TokenAuthentication],
DEFAULT_PERMISSION_CLASSES: [IsAuthenticatedOrReadOnly],
DEFAULT_PAGINATION_CLASS: PageNumberPagination,
PAGE_SIZE: 20,
},
```
Browsers that are logged into the admin already have a session, so `SessionAuthentication` works for them (and enforces CSRF on unsafe methods). Other clients send a token, stored by the `authtoken` app (`AuthTokenConfig`, already in `INSTALLED_APPS`). Add an endpoint that exchanges a username and password for a token:
src/urls.ts
```diff
+import { obtainAuthToken } from '@ghuri/auth/rest'
// ...
export const urlpatterns = [
path('', home, { name: 'home' }),
path('admin/', admin.site.urls),
// ...the three schema / docs routes
path('api/', include(router.urls)),
+path('api-token-auth/', obtainAuthToken),
path('blog/', include(blogUrls)),
]
```
`obtainAuthToken` is CSRF-exempt and expects JSON (or form data). Get a token and use it:
```sh
curl -X POST http://localhost:8787/api-token-auth/ \
-H 'Content-Type: application/json' \
-d '{"username": "rifat", "password": "correct horse"}'
# {"token":"9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"}
curl -X POST http://localhost:8787/api/posts/ \
-H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' \
-H 'Content-Type: application/json' \
-d '{"title": "Written over the API", "slug": "over-the-api", "tags": ["typescript"]}'
```
The response is `201 Created` with the serialized post, and `authorName` is `rifat` because `performCreate` set the author from the request. You can also create a token from the command line with `npx ghuri drf_create_token rifat`. If you prefer JWTs, use `JWTAuthentication` with `TokenObtainPairView` and `TokenRefreshView`; see [REST authentication](https://ghurijs.github.io/docs/topics/rest/authentication/) and [Auth tokens](https://ghurijs.github.io/docs/topics/auth-tokens/).
## OpenAPI docs
The project came with an OpenAPI 3.1 schema and interactive docs; they are the three `api/schema/`, `api/docs/` and `api/reference/` routes in `src/urls.ts`. Open `http://localhost:8787/api/docs/` for Swagger UI or `http://localhost:8787/api/reference/` for Scalar, and try every endpoint from the browser. The raw document is at `/api/schema/`. It is built from your views and serializers, so it stays in sync with the code.
To write it to a file, for a client generator or to commit it:
```sh
npx ghuri generateschema --file openapi.yaml
```
See [OpenAPI](https://ghurijs.github.io/docs/topics/rest/openapi/) to rename operations, add tags or hide views.
## Testing the API
`startapp` created `src/blog/tests.ts`, whose test still expects the Part 1 `index` view. Replace it with a test that exercises the API through the real middleware and URL stack:
src/blog/tests.ts
```ts
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { createApp } from '@ghuri/core'
import { createTestClient } from '@ghuri/core/testing'
import { setupTestDatabase } from '@ghuri/orm/testing'
import { User } from '@ghuri/auth'
import settings from '../settings'
import { Post } from './models'
// Use one env object everywhere: settings are resolved (and cached) per env object.
const env = { SECRET_KEY: 'test', DEBUG: 'true' }
const app = createApp(settings)
let db: Awaited>
beforeAll(async () => {
await app.setup(env)
db = await setupTestDatabase({ using: 'sqlite' }) // in-memory, runs every migration
})
afterAll(() => db.teardown())
describe('posts API', () => {
it('hides drafts from anonymous users', async () => {
const author = await User.objects.createUser({ username: 'a', password: 'pw-123456' })
await Post.objects.create({ title: 'Draft', slug: 'draft', author })
await Post.objects.create({ title: 'Live', slug: 'live', author, published: true })
const client = createTestClient(app, { env })
const res = await client.get('/api/posts/')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.results.map((p: { slug: string }) => p.slug)).toEqual(['live'])
})
})
```
```sh
npx ghuri test
```
The generated `vitest.config.ts` picks up `src/**/tests.ts` and `*.test.ts` files, and turns on oxc’s legacy decorator mode so `@admin.register` and `@action` load under Vitest (Ghuri’s decorators work in both modes).
`setupTestDatabase()` swaps the `default` database for a fresh in-memory one (`'sqlite'`, `'pglite'` for Postgres, or `'d1'` through Miniflare) and applies your migrations, so the test never touches your development data. For DRF-style tests, `APIClient` from `@ghuri/rest/testing` adds `forceAuthenticate(user)` and parsed `res.data`. More in [Testing](https://ghurijs.github.io/docs/topics/testing/).
You have a complete backend. The last step is to put it on the internet: [Part 5: Deploy to Cloudflare](https://ghurijs.github.io/docs/tutorial/part-5-deploy/).
# Part 5: Deploy to Cloudflare
> Create the D1 database and R2 bucket, set secrets, migrate the remote database and deploy the blog to Cloudflare Workers.
The blog works locally. In this last part you will put it on Cloudflare’s network, with a real D1 database and an R2 bucket for uploads (and, optionally, a KV namespace for the cache).
You need a Cloudflare account (the free plan is enough) and Wrangler logged in:
```sh
npx wrangler login
```
## Create the resources
The generated `wrangler.jsonc` declares two bindings, `DB` (D1) and `MEDIA` (R2), plus a commented-out `CACHE` (KV). Locally, Wrangler simulated them; now create the real resources:
```sh
npx wrangler d1 create mysite-db
npx wrangler r2 bucket create mysite-media
npx wrangler kv namespace create CACHE # optional
```
`wrangler d1 create` prints the new database’s id. Replace the placeholder `00000000-0000-0000-0000-000000000000` in `wrangler.jsonc` with it, and, if you created the KV namespace, uncomment `kv_namespaces` and paste its `id`:
wrangler.jsonc
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "mysite",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"compatibility_flags": ["nodejs_compat"],
"observability": { "enabled": true },
"d1_databases": [
{ "binding": "DB", "database_name": "mysite-db",
"database_id": "4f0c3e1a-…" }
],
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "mysite-media" }],
"kv_namespaces": [
// only if you created it; settings use kvCache('CACHE') when the binding exists
{ "binding": "CACHE", "id": "b7d2…" }
],
"vars": { "DEBUG": "false" }
}
```
Your settings do not change. `d1('DB')` means “the D1 database bound as `DB`”, whichever database that is in the current environment, and `CACHES` already switches to KV when a `CACHE` binding exists.
## Set the secret key
Production needs its own `SECRET_KEY`, stored as an encrypted Worker secret rather than in `wrangler.jsonc` (the one in `.dev.vars` is for local development only):
```sh
openssl rand -base64 48 | npx wrangler secret put SECRET_KEY
```
## Migrate the remote database
Run the same migrations you ran locally, against the remote D1 database:
```sh
npx ghuri migrate --remote
npx ghuri createsuperuser --remote
```
`--remote` is a global option: the CLI asks Wrangler for remote bindings (it writes a temporary copy of `wrangler.jsonc` with every D1, R2 and KV binding marked `"remote": true`), so the command reads and writes your real Cloudflare resources instead of the local simulation. Every command accepts it, so you can also `npx ghuri shell --remote` to inspect production data. Use that one carefully. Remote bindings need `wrangler login` and the real `database_id`.
Alpha
Remote commands go through Wrangler’s platform proxy. Large migrations on D1 can be slow over that path; if one times out, generate plain SQL with `npx ghuri sqlmigrate --all --out migrations-sql` and apply it with `npx wrangler d1 migrations apply DB --remote` (set `"migrations_dir": "migrations-sql"` on the D1 binding). See [Deploy to Cloudflare](https://ghurijs.github.io/docs/deployment/cloudflare/).
## Deploy
```sh
npx ghuri deploy
```
`ghuri deploy` first asks whether to apply migrations to the remote database (`ghuri migrate --remote`); answer yes, or pass `--migrate` to skip the question (`--skip-migrations` to skip them). Then it runs `wrangler deploy`, which bundles `src/index.ts` and everything it imports (your apps, models, migrations index and admin) into a single Worker and uploads it. When it finishes it prints your URL:
```plaintext
Deployed mysite triggers
https://mysite..workers.dev
```
Open `https://mysite..workers.dev/admin/`, log in with the superuser you just created, and write a post. Then fetch it from the API:
```sh
curl https://mysite..workers.dev/api/posts/
```
## Tighten production settings
Before you share the URL, restrict hosts and trust your own origin for CSRF. The generated settings already read `ALLOWED_HOSTS` from the environment as a comma-separated list, so set it as a variable:
wrangler.jsonc
```jsonc
"vars": {
"DEBUG": "false",
"ALLOWED_HOSTS": "blog.example.com,mysite.example.workers.dev"
}
```
src/settings.ts
```ts
export default defineSettings((env) => ({
// ...
CSRF_TRUSTED_ORIGINS: ['https://blog.example.com'],
}))
```
To serve the site on your own domain, add a route or custom domain in `wrangler.jsonc`:
wrangler.jsonc
```jsonc
"routes": [{ "pattern": "blog.example.com", "custom_domain": true }]
```
Run `npx ghuri check --deploy` to catch the usual production mistakes.
## The deploy loop
From now on, shipping a change that touches models is:
```sh
npx ghuri makemigrations
npx ghuri migrate # local
npx ghuri test
npx ghuri deploy --migrate # remote migrations, then the new code
```
`--migrate` applies migrations before `wrangler deploy`, which is the right order when you add tables or columns: the new code never sees an old schema. When you remove a column, deploy the code that stops using it first (`npx ghuri deploy --skip-migrations`) and migrate afterwards (`npx ghuri migrate --remote`).
If you know Django
The order of operations is the same as for any Django deployment: migrate, then switch traffic to new code. What disappears is the server: there is no gunicorn to restart, no `collectstatic` (the admin’s CSS ships inside `@ghuri/admin`) and no process manager.
## Where to go from here
You have built and deployed a Django-style application on Cloudflare. Some next steps:
* When the blog outgrows D1, follow [Migrating from D1 to Postgres](https://ghurijs.github.io/docs/deployment/d1-to-postgres/). Your models, views and serializers will not change.
* To run on your own server, read [Node and Postgres on a VPS](https://ghurijs.github.io/docs/deployment/node-postgres/) or [Docker](https://ghurijs.github.io/docs/deployment/docker/).
* Run work on a schedule or from a queue with [background tasks](https://ghurijs.github.io/docs/topics/background-tasks/).
* Let an AI assistant manage posts through your API with [AI agents and MCP](https://ghurijs.github.io/docs/topics/agents-mcp/).
* Browse the topic guides, starting with [Making queries](https://ghurijs.github.io/docs/topics/queries/).
# Settings
> How Ghuri settings work, why they are a function of the environment, and how packages add their own keys.
A Ghuri project is configured by one file, `src/settings.ts`, whose default export is created with `defineSettings()`. Keys keep Django’s `UPPER_SNAKE` names, so `INSTALLED_APPS`, `MIDDLEWARE`, `DATABASES` and friends mean what you expect.
src/settings.ts
```ts
import { defineSettings, SecurityMiddleware, CommonMiddleware, CsrfMiddleware, kvCache, memoryCache } from '@ghuri/core'
import { d1, postgres } from '@ghuri/orm'
import { r2 } from '@ghuri/storage'
import {
ContentTypesConfig, AuthConfig, SessionsConfig, SessionMiddleware, AuthenticationMiddleware,
} from '@ghuri/auth'
import { AdminConfig } from '@ghuri/admin'
import { BlogConfig } from './blog/app'
import { urlpatterns } from './urls'
export default defineSettings((env) => ({
SECRET_KEY: env.SECRET_KEY,
DEBUG: env.DEBUG === 'true',
ALLOWED_HOSTS: ['blog.example.com', 'localhost'],
INSTALLED_APPS: [ContentTypesConfig, AuthConfig, SessionsConfig, AdminConfig, BlogConfig],
MIDDLEWARE: [SecurityMiddleware, SessionMiddleware, CommonMiddleware, CsrfMiddleware, AuthenticationMiddleware],
ROOT_URLCONF: urlpatterns,
DATABASES: {
default: env.DATABASE_URL ? postgres({ url: env.DATABASE_URL }) : d1('DB'),
},
STORAGES: { default: r2('MEDIA', { publicUrl: 'https://media.example.com' }) },
CACHES: { default: env.CACHE ? kvCache('CACHE') : memoryCache() },
TIME_ZONE: 'UTC',
}))
```
## Settings are a function of `env`
In Django, `settings.py` runs once at import time and reads `os.environ`. A Cloudflare Worker has no process environment: secrets, variables and resource bindings (D1, R2, KV) arrive as an `env` object passed to every request. So `defineSettings()` takes a function of `env` rather than an object.
* **On Workers**, `env` is the Worker’s environment: `vars` from `wrangler.jsonc`, secrets set with `wrangler secret put`, and bindings. Locally, `.dev.vars` fills in secrets.
* **On Node**, `env` is whatever you pass to `serve()` from `@ghuri/core/node`, normally `process.env` (the default).
* **In the CLI**, `env` is built from `wrangler.jsonc` bindings (local, or remote with `--remote`) merged with `.env` / `.dev.vars` and `process.env`.
The function runs once per distinct `env` object. The result is cached in a `WeakMap`, merged over the defaults, and validated, so calling it is cheap and you can treat settings as constants after startup. Because `env` values are always strings on Workers, convert explicitly: `DEBUG: env.DEBUG === 'true'`, `PAGE_SIZE: Number(env.PAGE_SIZE ?? 20)`.
`createApp()` also accepts a plain function or a settings object and wraps it with `defineSettings()` for you, but exporting a `defineSettings()` factory is what the CLI expects.
Adapters such as `d1('DB')`, `r2('MEDIA')` and `kvCache('CACHE')` take a **binding name**, not a binding. They look the binding up on `env` when the first connection is made. That keeps `settings.ts` free of runtime objects and is what lets the same file describe both a Worker and a Node process.
If you know Django
`defineSettings((env) => ({...}))` is your `settings.py`, and `env` is `os.environ` plus the Cloudflare resources. There is no `DJANGO_SETTINGS_MODULE`: the CLI finds the file through `"ghuri": { "settings": "src/settings.ts" }` in `package.json` (falling back to `src/settings.ts`, or `--settings `), and the Worker imports it directly in `src/index.ts`. For different environments, branch on `env` inside the function rather than keeping several settings modules.
## Reading settings at runtime
Anywhere code runs inside a request (or a CLI command, or a test after `app.setup()`), read the active settings with `getSettings()`:
```ts
import { getSettings, setting } from '@ghuri/core'
const debug = getSettings().DEBUG
const pageSize = setting('PAGE_SIZE', 20) // with a fallback for unset keys
```
Both read from the current [request context](#the-request-context). Calling them at module top level, before any request, throws `ImproperlyConfigured`. That is deliberate: on Workers there is no `env` until the first request arrives.
Inside middleware or an error handler that has the Hono context, `settingsFor(c)` returns the request’s settings (or `undefined`) without throwing, even when the code runs outside the `AsyncLocalStorage` scope.
To reach a raw binding (for example a Workers AI binding that no Ghuri adapter wraps), use `getEnv()`:
```ts
import { getEnv } from '@ghuri/core'
const answer = await getEnv().AI.run('@cf/meta/llama-3.3-70b-instruct-fp8-fast', { prompt })
```
Prefer adapters where they exist. Code that touches `env.DB` directly will not survive a move to Postgres.
## The request context
Settings, database connections, the current user and other per-request state live in a `GhuriContext` carried by `AsyncLocalStorage` (which is why `nodejs_compat` is required). `createApp()` wraps every request, cron trigger and queue batch in `runWithContext()`. Outside those, the CLI and test helpers call `app.setup(env)`, which populates apps and installs a global fallback context.
```ts
interface GhuriContext {
env: Env
settings: GhuriSettings
executionCtx?: { waitUntil(p: Promise): void; passThroughOnException?(): void }
request?: Request
hono?: import('hono').Context
state: Map // per-request cache
}
```
`getContext()` returns it (and throws outside one); `tryGetContext()` returns `undefined` instead. The Hono context carries it too, as `c.get('ghuri')`. To run code with a context of your own, for example in a script, build one with `createContext({ env, settings })` and call `runWithContext(ctx, fn)`.
You rarely need it directly, but `getContext().executionCtx?.waitUntil(promise)` is the way to run work after the response is sent on Workers. On Node, `serve()` provides a `waitUntil` shim that tracks the promises and drains them on shutdown.
## Package settings and type safety
`GhuriSettings` is an interface that each package extends with declaration merging. Installing `@ghuri/orm` makes `DATABASES` a known, typed key; `@ghuri/rest` adds `REST_FRAMEWORK`, and so on. You can do the same for your own settings:
src/blog/settings.ts
```ts
declare module '@ghuri/core' {
interface GhuriSettings {
BLOG_POSTS_PER_FEED?: number
}
}
```
```ts
const perFeed = setting('BLOG_POSTS_PER_FEED', 20)
```
Unknown keys are allowed (the interface has an index signature), but declaring them gives you autocompletion and catches typos.
## Validation and checks
When settings are first resolved, Ghuri checks the basics: `SECRET_KEY` must be set unless `DEBUG` is on, and `INSTALLED_APPS` and `ROOT_URLCONF` must be arrays. Then the [system check framework](https://docs.djangoproject.com/en/stable/topics/checks/) takes over: core checks URL patterns and `MIDDLEWARE` entries, and packages register their own (for example, `@ghuri/auth` checks that `AUTH_USER_MODEL` names an installed model). Run them with:
```sh
npx ghuri check
npx ghuri check --deploy # adds Django's security warnings (DEBUG, SECRET_KEY, HSTS, CSRF cookie…)
```
When `DEBUG` is on, checks also run at startup; an error stops the app with a clear message (pass `createApp(settings, { checks: false })` to skip them). Silence messages by id with `SILENCED_SYSTEM_CHECKS: ['security.W004']`.
Register your own checks with `checks.register()`, typically from an `AppConfig.ready()`:
```ts
import { checks } from '@ghuri/core'
checks.register(({ settings }) =>
settings.BLOG_POSTS_PER_FEED === 0
? [checks.error('BLOG_POSTS_PER_FEED must be positive.', { id: 'blog.E001' })]
: [],
{ tags: ['blog'] }, // { deploy: true } for deploy-only checks
)
```
`runChecks({ deploy?, tags? })` runs them programmatically and returns `CheckMessage`s.
## Core settings
| Setting | Default | Meaning |
| ---------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SECRET_KEY` | required | Signs sessions, CSRF tokens, password reset tokens. Optional only with `DEBUG`. |
| `DEBUG` | `false` | Detailed error pages with stack traces; runs checks at startup. Never in production. |
| `ALLOWED_HOSTS` | `['*']` | Host header values the site will serve. Enforced by the app itself on every request (400 `DisallowedHost`). An empty list with `DEBUG` allows `localhost` only. |
| `INSTALLED_APPS` | required | `AppConfig` classes or instances, in order. |
| `MIDDLEWARE` | `[]` | Middleware classes, configured instances, or Hono middleware handlers, outermost first. |
| `ROOT_URLCONF` | required | The root URL pattern array. |
| `APPEND_SLASH` | `true` | Redirect `GET /x` to `/x/` when only the latter matches. |
| `TIME_ZONE` / `USE_TZ` | `'UTC'` / `true` | Time zone for display (the admin uses `TIME_ZONE`). |
| `CACHES` | memory cache | Cache aliases. See [Caching](https://ghurijs.github.io/docs/topics/caching/). |
| `CSRF_TRUSTED_ORIGINS` | `[]` | Extra origins allowed for unsafe requests. |
| `CORS` | `false` | `{ allowOrigins, allowCredentials, … }` for `CorsMiddleware`. |
| `API_PATH_PREFIXES` | `['/api']` | Errors under these paths are always rendered as JSON. |
Security, CSRF and host settings (`SECURE_*`, `CSRF_COOKIE_*`, `X_FRAME_OPTIONS`, `USE_X_FORWARDED_HOST`, `PREPEND_WWW`, …) and every setting from every other package are listed in the [settings reference](https://ghurijs.github.io/docs/reference/settings/).
# Applications
> AppConfig, INSTALLED_APPS, the app registry, and how apps register models, migrations, admin classes and commands.
A Ghuri project is a list of applications. Each app is a directory under `src/` that owns a slice of functionality (models, views, URLs, admin classes, commands) and is described by an `AppConfig` subclass. `ghuri startapp ` creates one.
## AppConfig
src/blog/app.ts
```ts
import { AppConfig, onSchedule } from '@ghuri/core'
import * as models from './models'
import * as migrations from './migrations'
import * as admin from './admin'
import * as signals from './signals'
import { PublishScheduledCommand } from './commands/publish-scheduled'
import { publishScheduledPosts } from './tasks'
export class BlogConfig extends AppConfig {
name = 'blog'
verboseName = 'Blog'
path = import.meta.dirname
models = models
migrations = migrations
admin = admin
modules = { signals }
commands = { publishscheduled: PublishScheduledCommand }
ready() {
onSchedule('0 * * * *', () => publishScheduledPosts())
}
}
```
| Attribute | Purpose |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Required. The app’s name, and its default label. |
| `label` | Unique short name used in model labels (`blog.Post`), permissions (`blog.add_post`) and table names (`blog_post`). Defaults to the last segment of `name`. Read the effective value with `config.appLabel`. |
| `verboseName` | Human-readable name shown in the admin. Defaults to the capitalised label (`config.displayName`). |
| `path` | The app’s directory. Only the CLI uses it, to know where to write migrations. Set it to `import.meta.dirname`. |
| `models` | The app’s models module. Every exported `Model` class is registered under this app’s label. |
| `migrations` | The generated `migrations/index.ts` module. |
| `admin` | The admin module. Importing it runs `admin.site.register(...)` calls. |
| `modules` | Any other modules the app wants loaded at startup: signal receivers, agents, check registrations. Assigning the import is enough; Ghuri does not call anything on them. |
| `commands` | Management commands: `{ name: CommandClass }`. |
| `ready()` | Called once per isolate after every app is loaded and every model is registered. May be async. |
Add the class to `INSTALLED_APPS`:
src/settings.ts
```ts
INSTALLED_APPS: [ContentTypesConfig, AuthConfig, SessionsConfig, AdminConfig, BlogConfig],
```
Entries can be classes (instantiated for you) or instances, which is handy for configuring a third-party app: `new AgentsConfig()` or a subclass with a different `label`.
If you know Django
`AppConfig` is Django’s `AppConfig`, and `ready()` is where you connect signals, as in Django. The difference is that Ghuri never imports modules by convention. Django finds `models.py` and `admin.py` by name at startup; a Worker is a single bundle with no filesystem, so an app **imports** its own modules and hands them to the config. If a model is not exported from the module assigned to `models`, Ghuri does not know it exists. `modules` plays the role of the “import this so its side effects run” lines you would otherwise put in `ready()`.
## Why imports instead of discovery
Explicit imports have three benefits beyond working on Workers:
1. The bundler sees every model, migration and admin class, so tree-shaking and type checking cover all of them.
2. There is no startup scan, which keeps cold starts short.
3. “Where is this registered?” always has an answer you can jump to in your editor.
The cost is one line per module in `app.ts`, which `startapp` writes for you.
## Load order
On the first request in an isolate (or the first cron trigger or queue batch, or when the CLI or a test calls `app.setup(env)`), `apps.populate(INSTALLED_APPS)` runs:
1. Each entry is instantiated, its label is checked for uniqueness, and its `commands` are registered.
2. Hooks registered by packages with `apps.onPopulate()` run. The ORM’s hook walks every config’s `models` and registers each `Model` class with that app’s label, resolving lazy relations (`() => User`, `'auth.User'`) once every model is known.
3. `ready()` is called on every config, in `INSTALLED_APPS` order, and awaited.
`populate()` is idempotent for the same list. If it fails, the registry is reset, so the next request tries again and reports the error rather than serving a half-loaded app.
Order matters in the same places it does in Django: an app that overrides another app’s admin registration or command must come after it.
## The app registry
`apps` is the registry. Packages use it to find models by label; you will mostly use it in generic code, management commands and data migrations.
```ts
import { apps } from '@ghuri/core'
apps.isInstalled('blog') // true
apps.getAppConfig('blog').verboseName // 'Blog'
apps.getAppConfigs() // every config, in INSTALLED_APPS order
const Post = apps.getModel('blog.Post') // or apps.getModel('blog', 'post'); case-insensitive
for (const model of apps.getModels()) { // apps.getModels('blog') for one app
console.log(model._meta.label)
}
```
`getModel()` and `getAppConfig()` throw a `LookupError` for unknown labels, and `getModel()` throws `AppRegistryNotReady` if called before population starts. `apps.ready` is `true` once every `ready()` has finished.
## Reusable apps
Because an app is just a directory with an `AppConfig`, you can publish one as an npm package. Export the config class from the package entry and ship its compiled migrations; users add it to `INSTALLED_APPS` like any built-in app. Ghuri’s own packages are apps built exactly this way: `@ghuri/auth` ships `ContentTypesConfig`, `AuthConfig`, `SessionsConfig`, `AuthTokenConfig` and `TokenBlacklistConfig`; `@ghuri/admin` ships `AdminConfig`; `@ghuri/agents` ships `AgentsConfig`.
Choose a distinctive `label` for a reusable app, since labels must be unique across the project and appear in table names.
# URLs and views
> URL patterns with path() and include(), converters, reverse() and resolve(), function and class-based views, shortcuts and error handling.
Ghuri routes requests the way Django does: a root list of URL patterns (`ROOT_URLCONF`), built with `path()` and `include()`, mapping routes to views. Under the hood the patterns compile to a [Hono](https://hono.dev) router, and views receive Hono’s `Context`.
## URL patterns
src/urls.ts
```ts
import { path, rePath, include } from '@ghuri/core'
import { admin } from '@ghuri/admin'
import * as blog from './blog/urls'
import { home, archive, feed, upload, page } from './views'
import { AboutView } from './views/about'
import { legacyApp } from './legacy'
export const urlpatterns = [
path('', home, { name: 'home' }),
path('about/', AboutView, { name: 'about' }), // View classes are accepted directly
path('blog/', include(blog)),
path('archive///', archive, { name: 'archive' }),
rePath('^feeds/(?Prss|atom)/$', feed, { name: 'feed' }),
path('upload/', upload, { methods: ['POST'] }), // other methods → 405
path('terms/', page, { kwargs: { template: 'terms' } }), // extra kwargs for the view
path('admin/', admin.site.urls),
path('legacy/', legacyApp), // any Hono app
]
```
`path(route, target, options?)` takes:
* **`route`**: a string with optional converters. Routes are matched in order; the first match wins.
* **`target`**: a view function, a `View` class (`asView()` is called for you) or the result of `asView()`, the result of `include()`, another pattern array (for example `admin.site.urls` or `router.urls`), or a `Hono` instance to mount as-is.
* **`options`**: `{ name?, methods?, kwargs? }`. `name` is used by `reverse()`; `methods` restricts the pattern to some HTTP methods (others get a 405 with an `Allow` header); `kwargs` are extra values merged into `kwargs(c)`, like Django’s `path(..., kwargs={...})`.
`rePath()` takes a regular expression with named groups when converters are not enough. Both JavaScript’s `(?…)` and Python’s `(?P…)` group syntax work.
### Converters
| Converter | Matches | Value |
| ------------------ | ----------------------------------- | ------------------------ |
| `` or `` | any non-empty segment without `/` | string |
| `` | `0` or a positive integer | number (via `kwargs(c)`) |
| `` | letters, digits, `-` and `_` | string |
| `` | a lowercase UUID | string |
| `` | any non-empty string, including `/` | string |
A pattern such as `'posts//'` compiles to the Hono route `/posts/:id{[0-9]+}/`, so routing stays fast. Read raw string parameters with `c.req.param('id')`, or converted values (plus any `kwargs` from `path()`) with `kwargs(c)`:
```ts
import { kwargs } from '@ghuri/core'
export async function archive(c: Context) {
const { year, month } = kwargs<{ year: number; month: number }>(c) // numbers, because of
// ...
}
```
Register your own converter with `registerConverter()`, Django’s `register_converter`:
```ts
import { registerConverter } from '@ghuri/core'
registerConverter('year', { regex: '[0-9]{4}', toJs: Number, toUrl: (v) => String(v).padStart(4, '0') })
path('archive//', archive)
```
Register converters before the URL patterns that use them are built (at module top level of `urls.ts` is fine).
Note
Routes Hono cannot express, such as two parameters in one path segment or a `rePath()` regex with character classes, alternations or quantifiers outside its named groups, fall back to regex matching automatically. They work the same, but their parameters are only available through `kwargs(c)`, not `c.req.param()`.
### `include()` and namespaces
`include()` nests patterns under a prefix. It accepts an array, or a module that exports `urlpatterns` (and optionally `appName`). The `urlpatterns(appName, list)` helper builds an array that carries its `appName`, like Django’s `app_name = 'blog'`:
src/blog/urls.ts
```ts
import { path, urlpatterns as patterns } from '@ghuri/core'
import * as views from './views'
export const urlpatterns = patterns('blog', [
path('', views.index, { name: 'index' }),
path('/', views.detail, { name: 'detail' }),
])
```
src/urls.ts
```ts
path('blog/', include(blog)), // namespace 'blog' from appName
path('news/', include(blog.urlpatterns, { namespace: 'news' })), // explicit namespace
```
Exporting a separate `export const appName = 'blog'` next to a plain `urlpatterns` array works too.
### Trailing slashes
With `APPEND_SLASH` on (the default), a `GET` or `HEAD` for `/blog/hello` that matches nothing is redirected with a 301 to `/blog/hello/` when that URL would match. The app does this itself, with or without `CommonMiddleware`. Write routes with trailing slashes, as in Django. `POST`s are never redirected, so post to the slashed URL.
## Reversing and resolving URLs
Never hard-code paths. `reverse(name, params?, { query? })` builds one from a pattern name and parameters:
```ts
import { reverse, redirect } from '@ghuri/core'
reverse('home') // '/'
reverse('blog:detail', { slug: 'hello-ghuri' }) // '/blog/hello-ghuri/'
reverse('archive', { year: 2026, month: 11 }) // '/archive/2026/11/'
reverse('archive', [2026, 11]) // positional parameters
reverse('blog:index', {}, { query: { page: 2 } }) // '/blog/?page=2'
return redirect(c, 'blog:detail', { slug: post.slug })
```
`reverse()` throws `NoReverseMatch` if the name is unknown or the parameters do not fit the converters.
The other direction is `resolve(path)`, which returns a `ResolverMatch` (`route`, `urlName`, `namespace`, `viewName`, `kwargs`, `view`, …) or throws `Resolver404`. Inside a view, `resolverMatch(c)` gives the current request’s match, like Django’s `request.resolver_match`:
```ts
import { resolve, resolverMatch } from '@ghuri/core'
resolve('/blog/hello-ghuri/').viewName // 'blog:detail'
resolverMatch(c)?.urlName // 'detail'
```
## Function views
A view is any function `(c: Context) => Response | Promise`. `c` is Hono’s context: the request is `c.req`, and helpers such as `c.json()`, `c.html()` and `c.text()` build responses. A view may also `throw` a `Response`, which is returned as-is.
src/blog/views.ts
```ts
import type { Context } from 'hono'
import { json, getUser, kwargs, PermissionDenied } from '@ghuri/core'
import { getObjectOr404 } from '@ghuri/orm'
import { Post } from './models'
export async function detail(c: Context) {
const post = await getObjectOr404(Post, { slug: kwargs(c).slug })
if (!post.published && post.authorId !== getUser(c).pk) {
throw new PermissionDenied()
}
return json(c, { title: post.title, body: post.body })
}
```
### Shortcuts
| Shortcut | From | Does |
| ------------------------------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `json(c, data, status?, headers?)` | `@ghuri/core` | JSON response. Objects with `toJSON()` (dates, model instances) serialise as usual; `bigint`, `Map` and `Set` are handled too |
| `render(c, jsx, { status?, headers? })` | `@ghuri/core` | HTML response from Hono JSX or a string; adds `` when the output starts with `
,
)
}
```
JSX output is escaped. For trusted raw markup use `html` or `raw` from `hono/html`.
## Errors
Throw an error from anywhere in a view (or in code it calls), and Ghuri turns it into a response, as Django does:
| Error (from `@ghuri/core` unless noted) | Response |
| ------------------------------------------------------------------ | ---------------------------------------------------- |
| `Http404`, `ObjectDoesNotExist` (and every model’s `DoesNotExist`) | 404 |
| `PermissionDenied`, `CsrfFailure` | 403 |
| `BadRequest`, `SuspiciousOperation`, `DisallowedHost` | 400 |
| `ValidationError` | 400 with `{ detail, errors: { field: [messages] } }` |
| `MethodNotAllowed(method, allowed)` | 405 with an `Allow` header |
| Hono’s `HTTPException` | its status, or its own response |
| anything else | 500 |
The error body is JSON (`{ "detail": "…" }`) when `wantsJson(c)` is true: the path is under one of `API_PATH_PREFIXES` (default `['/api']`), the client accepts JSON but not HTML, the request body is JSON, or it is an `XMLHttpRequest`. Otherwise it is an HTML page. With `DEBUG` on, 500s show a debug page with the stack trace, request details and settings (with secrets masked), and 404s list the URL patterns that were tried. Production pages never reveal details.
Map your own errors with `registerExceptionHandler(ErrorClassOrPredicate, handler)`. Handlers registered later are tried first; return `undefined` to fall through to the default mapping. `@ghuri/rest` uses this for its `APIException`.
```ts
import { registerExceptionHandler } from '@ghuri/core'
registerExceptionHandler(PaymentRequired, (err, c) => c.json({ code: err.code }, 402))
```
For a project-wide hook, pass `createApp(settings, { onError: (err, c) => … })`; it runs before the registered handlers. `handleException(err, c)` applies the whole mapping yourself, for example from a mounted Hono app’s own `onError`.
## Class-based views
`View` dispatches to a method named after the HTTP verb. Mount the class directly, or call `asView(initkwargs)` to override attributes:
src/blog/views.ts
```ts
import type { Context } from 'hono'
import { View, json, redirect, getUser } from '@ghuri/core'
import { loginRequired } from '@ghuri/auth'
import { Post } from './models'
export class PostDraftsView extends View {
pageSize = 20
async get(c: Context) {
const drafts = await Post.objects.filter({ published: false, authorId: getUser(c).pk }).slice(0, this.pageSize)
return json(c, drafts)
}
async post(c: Context) {
const body = await c.req.parseBody()
const post = await Post.objects.create({ title: String(body.title), slug: String(body.slug), author: getUser(c) })
return redirect(c, 'blog:detail', { slug: post.slug })
}
}
```
src/blog/urls.ts
```ts
path('drafts/', loginRequired(PostDraftsView.asView({ pageSize: 50 })), { name: 'drafts' }),
```
`asView(initkwargs)` sets the given properties on each new instance, like Django. A fresh instance is created per request, so storing request state on `this` is safe. Each instance has `this.c` (the Hono context), `this.request` (`c.req`) and `this.kwargs` (converted URL parameters).
* Missing methods answer **405** with an `Allow` header; `HEAD` falls back to `get()`; `OPTIONS` answers 200 with `Allow`.
* Override `setup(c)` or `dispatch(c)` for logic shared by every method, as in Django.
* Set `static csrfExempt = true` to exempt every view the class produces from CSRF checks, and `static xframeOptionsExempt = true` to exempt them from `XFrameOptionsMiddleware`.
Two generic views are built in:
* **`TemplateView`** renders its `template`, a Hono JSX component, with the props returned by `getContextData()` (URL kwargs plus `extraContext` by default):
```tsx
import { TemplateView } from '@ghuri/core'
export class AboutView extends TemplateView {
template = (p: { title: string }) => (
{p.title}
)
async getContextData() {
return { ...(await super.getContextData()), title: 'About us' }
}
}
```
Override `getTemplate()` to pick the component at request time, and set `status` for a non-200 response.
* **`RedirectView`**: `RedirectView.asView({ patternName: 'home', permanent: true })` or `{ url: '/posts/{id}/', queryString: true }`. `{param}` placeholders are filled from the URL kwargs; with neither `url` nor `patternName` it answers 410 Gone.
For JSON APIs, use the views in [`@ghuri/rest`](https://ghurijs.github.io/docs/topics/rest/views/) instead: they add parsing, authentication, permissions and content negotiation.
If you know Django
`path`, `re_path` (`rePath`), `include`, `reverse`, `resolve`, `register_converter` (`registerConverter`), `app_name` (`urlpatterns(appName, …)` or `appName`), namespaces, `View.as_view()` (`asView`), `TemplateView` and `RedirectView` are all here. The request object is Hono’s `Context`: `request.GET['q']` is `c.req.query('q')`, `request.POST` is `await c.req.parseBody()`, `request.body` is `await c.req.json()` or `await c.req.text()`, `request.user` is `getUser(c)` and `request.resolver_match` is `resolverMatch(c)`. Decorators such as `login_required` are plain wrapper functions: `loginRequired(view)`.
## Mounting Hono apps
Any Hono app can be mounted as a pattern target. It sees paths relative to the mount point and runs inside Ghuri’s middleware and request context, so it can use the ORM and `getUser(c)`:
src/webhooks.ts
```ts
import { Hono } from 'hono'
import { csrfExempt } from '@ghuri/core'
import { Order } from './shop/models'
export const webhooks = csrfExempt(new Hono())
webhooks.post('/stripe', async (c) => {
const event = await c.req.json()
await Order.objects.filter({ stripeId: event.data.object.id }).update({ paid: true })
return c.body(null, 204)
})
```
```ts
path('webhooks/', webhooks),
```
This is also the way to use Hono middleware or third-party Hono apps that Ghuri does not wrap. To customise the root Hono app itself, pass `createApp(settings, { hono: (app) => { ... } })`; the callback runs after `MIDDLEWARE` is installed and before the URL patterns.
# Middleware
> The MIDDLEWARE setting, writing middleware classes, Hono middleware, and the built-in security, CSRF, CORS, session and authentication middleware.
Middleware wraps every request. Each entry in `MIDDLEWARE` sees the request on the way in, can short-circuit with its own response, and sees the response on the way out. The first entry is the outermost layer.
src/settings.ts
```ts
import {
SecurityMiddleware, CorsMiddleware, CommonMiddleware, CsrfMiddleware, XFrameOptionsMiddleware,
} from '@ghuri/core'
import { SessionMiddleware, AuthenticationMiddleware } from '@ghuri/auth'
MIDDLEWARE: [
SecurityMiddleware,
CorsMiddleware,
SessionMiddleware,
CommonMiddleware,
CsrfMiddleware,
AuthenticationMiddleware,
XFrameOptionsMiddleware,
],
```
Before any of them run, the app itself sets up the request context, sends the `requestStarted` signal and validates the `Host` header against `ALLOWED_HOSTS`. After them come the URL patterns and error handling.
## Writing middleware
Subclass `Middleware` and implement `handle(c, next)`. Call `await next()` to run the rest of the chain (other middleware, then the view). Afterwards, `c.res` holds the response.
src/middleware.ts
```ts
import type { Context, Next } from 'hono'
import { Middleware } from '@ghuri/core'
export class TimingMiddleware extends Middleware {
async handle(c: Context, next: Next) {
const start = Date.now()
await next()
c.header('Server-Timing', `app;dur=${Date.now() - start}`)
}
}
```
To answer without calling the view, return a `Response` and do not call `next()`. Returning a `Response` after `next()` replaces the view’s response.
```ts
import { getSettings } from '@ghuri/core'
export class MaintenanceMiddleware extends Middleware {
async handle(c: Context, next: Next) {
if (getSettings().MAINTENANCE_MODE && !c.req.path.startsWith('/admin/')) {
return c.text('Back soon.', 503)
}
await next()
}
}
```
Middleware classes are instantiated once, when the app is built for an isolate, so keep per-request data on `c` (with `c.set()`) or in the request context, never on `this`. To pass options, put a configured instance in `MIDDLEWARE` instead of the class: `new CorsMiddleware({ allowOrigins: '*' })`.
Plain [Hono middleware](https://hono.dev/docs/guides/middleware) also works in `MIDDLEWARE`, which gives you the whole Hono ecosystem:
```ts
import { logger } from 'hono/logger'
import { timeout } from 'hono/timeout'
MIDDLEWARE: [logger(), SecurityMiddleware, timeout(10_000), /* ... */],
```
The other direction works too: `toHonoMiddleware(entry)` turns a Ghuri middleware class or instance into a Hono handler, for use in a Hono app outside Ghuri’s `MIDDLEWARE` (for example `legacyApp.use('*', toHonoMiddleware(TimingMiddleware))`).
If you know Django
A Ghuri middleware is Django’s “new-style” middleware with the callable turned inside out: `handle(c, next)` corresponds to `__call__(self, request)`, and `await next()` is `self.get_response(request)`. There are no separate `process_view` / `process_exception` hooks; wrap `next()` in `try`/`catch` to handle exceptions, or use [`registerExceptionHandler()`](https://ghurijs.github.io/docs/topics/urls-and-views/#errors).
## Built-in middleware
### `SecurityMiddleware` (core)
Django’s `SecurityMiddleware`. Adds `X-Content-Type-Options: nosniff` (`SECURE_CONTENT_TYPE_NOSNIFF`), `Referrer-Policy: same-origin` (`SECURE_REFERRER_POLICY`) and `Cross-Origin-Opener-Policy: same-origin` (`SECURE_CROSS_ORIGIN_OPENER_POLICY`) unless the response already set them. It sends `Strict-Transport-Security` on HTTPS requests once `SECURE_HSTS_SECONDS` is above 0 (it is 0 by default), with `SECURE_HSTS_INCLUDE_SUBDOMAINS` and `SECURE_HSTS_PRELOAD`. `SECURE_SSL_REDIRECT` redirects HTTP to HTTPS (honouring `SECURE_SSL_HOST` and `SECURE_REDIRECT_EXEMPT`). Put it first.
Behind a proxy that terminates TLS (common on Node), set `SECURE_PROXY_SSL_HEADER: ['X-Forwarded-Proto', 'https']` so Ghuri knows the request was secure. On Workers the request URL already says `https`.
### `CommonMiddleware` (core)
Rejects requests whose `Host` is not in `ALLOWED_HOSTS` (400), implements `PREPEND_WWW`, and redirects to the slashed URL for `APPEND_SLASH`.
Note
`ALLOWED_HOSTS` and `APPEND_SLASH` are also enforced by the app itself, so they apply even without `CommonMiddleware`. What the middleware adds on top is `PREPEND_WWW`.
### `CorsMiddleware` (core)
Answers preflight requests and adds CORS headers according to the `CORS` setting:
```ts
CORS: {
allowOrigins: ['https://app.example.com'], // or '*'
allowCredentials: true,
// allowMethods, allowHeaders, exposeHeaders, maxAge (seconds, default 86400)
},
```
With `CORS: false` (the default) it does nothing. Place it before any middleware that can return early, so that error responses carry CORS headers too.
### `CsrfMiddleware` (core)
Django’s `CsrfViewMiddleware`. It protects unsafe methods (`POST`, `PUT`, `PATCH`, `DELETE`) from cross-site request forgery, in two layers:
1. **Origin check.** The `Origin` header must match the request host or an entry in `CSRF_TRUSTED_ORIGINS` (which accepts wildcards: `'https://*.example.com'`). HTTPS requests without an `Origin` must send a matching `Referer`.
2. **Token check.** A random secret lives in the `csrftoken` cookie; the request must send a token derived from it in the `X-CSRFToken` header or a `csrfmiddlewaretoken` form field. Tokens use Django’s masked format, so each rendered form gets a different value.
Put the token in forms with `getCsrfToken(c)`. Calling it creates the secret if needed, and the middleware sends the cookie on the way out:
```tsx
```
For JavaScript clients, read the `csrftoken` cookie and send it as `X-CSRFToken`. The helpers, all from `@ghuri/core`:
```ts
path('webhooks/stripe/', csrfExempt(stripeWebhook)) // skip the check (also works on a mounted Hono app)
path('spa/', ensureCsrfCookie(spaShell)) // always set the cookie (Django's ensure_csrf_cookie)
rotateCsrfToken(c) // new secret, e.g. after login
await enforceCsrf(c) // throw CsrfFailure unless the request passes
const reason = await checkCsrf(c) // the failure reason, or null
```
A failed check raises `CsrfFailure`, a 403 whose `reason` says what was wrong. Class-based views can set `static csrfExempt = true`. The cookie and header follow Django’s settings: `CSRF_COOKIE_NAME`, `CSRF_HEADER_NAME`, `CSRF_COOKIE_AGE`, `CSRF_COOKIE_DOMAIN`, `CSRF_COOKIE_PATH`, `CSRF_COOKIE_SECURE`, `CSRF_COOKIE_HTTPONLY`, `CSRF_COOKIE_SAMESITE`.
API views authenticated by tokens or JWTs are not subject to CSRF. Session-based REST authentication (the default `MiddlewareAuthentication`, and `SessionAuthentication` from `@ghuri/auth/rest`) calls `enforceCsrf()` itself, as DRF does.
### `XFrameOptionsMiddleware` (core)
Sets `X-Frame-Options: DENY` (or the value of `X_FRAME_OPTIONS`; `false` disables it) on responses that do not set it themselves, to prevent clickjacking.
To let other pages frame one view (an embed, or a preview shown inside a dashboard), exempt it, like Django’s `@xframe_options_exempt`. Class views can set `static xframeOptionsExempt = true`. A header the view sets itself is always kept, so you can also send `SAMEORIGIN` from one view:
```ts
import { xframeOptionsExempt } from '@ghuri/core'
path('embed/', xframeOptionsExempt(embedView)) // no X-Frame-Options (also works on a mounted Hono app)
```
Pair an exempt view with a `Content-Security-Policy: frame-ancestors …` header if only some origins may frame it.
### `GZipMiddleware` (core)
Compresses responses on Node. On Workers it does nothing, because Cloudflare compresses at the edge.
### `SessionMiddleware` and `AuthenticationMiddleware` (auth)
`SessionMiddleware` loads the session from the `sessionid` cookie and saves it after the response if it changed; the session is `c.get('session')`. `AuthenticationMiddleware` reads the user id from the session and sets the request user, available as `getUser(c)` or `c.get('user')`. `AuthenticationMiddleware` must come after `SessionMiddleware`. See [Authentication](https://ghurijs.github.io/docs/topics/authentication/).
## Ordering
A good default order, outermost first:
1. `SecurityMiddleware`
2. `CorsMiddleware` (if you use CORS)
3. `SessionMiddleware`
4. `CommonMiddleware`
5. `CsrfMiddleware`
6. `AuthenticationMiddleware`
7. `XFrameOptionsMiddleware`
8. Your own middleware
This is the order Django recommends, for the same reasons: security headers should apply to everything, CORS headers should reach early responses, and sessions must exist before CSRF and authentication can use them. `ghuri check --deploy` warns when `SecurityMiddleware` or `CsrfMiddleware` is missing.
# Models and fields
> Defining models with Model(), fields and options, Meta, abstract models, custom managers, instance methods and validation.
A model is the single source of truth about a piece of data: its fields, their types and validation, and its behaviour. Each model maps to one database table. Ghuri’s models work like Django’s, with a syntax adapted so TypeScript can infer every field type.
src/blog/models.ts
```ts
import {
Model, CharField, SlugField, TextField, BooleanField, DateTimeField, PositiveIntegerField,
ForeignKey, ManyToManyField, CASCADE, Manager, MinLengthValidator,
} from '@ghuri/orm'
import { User } from '@ghuri/auth'
export class Post extends Model({
title: new CharField({ maxLength: 200, validators: [new MinLengthValidator(3)] }),
slug: new SlugField({ unique: true }),
body: new TextField({ blank: true }),
status: new CharField({
maxLength: 10,
choices: [['draft', 'Draft'], ['review', 'In review'], ['live', 'Published']],
default: 'draft',
}),
views: new PositiveIntegerField({ default: 0 }),
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'posts' }),
tags: new ManyToManyField(() => Tag, { blank: true, relatedName: 'posts' }), // Tag is defined elsewhere in this file
createdAt: new DateTimeField({ autoNowAdd: true }),
updatedAt: new DateTimeField({ autoNow: true }),
}) {
static Meta = {
ordering: ['-createdAt'],
verboseNamePlural: 'posts',
indexes: [{ fields: ['status', 'createdAt'] }],
}
declare static objects: Manager
toString() {
return this.title
}
get isLive() {
return this.status === 'live'
}
}
```
## How `Model()` works
`Model(fields)` returns a base class built from the field definitions. You extend it to add `Meta`, methods, getters and custom managers. Because the fields are a value rather than a set of class property declarations, TypeScript can infer the instance type:
| Field | Instance property type |
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `CharField`, `TextField`, `SlugField`, `EmailField`, `URLField`, `UUIDField` | `string` |
| `IntegerField` and friends, `FloatField`, `DurationField` (ms) | `number` |
| `DecimalField` | `string` (exact; never a float) |
| `BooleanField` | `boolean` |
| `DateTimeField` | `Date` |
| `DateField`, `TimeField` | `string` (`'YYYY-MM-DD'`, `'HH:MM:SS'`) |
| `JSONField` | `any` (or the type parameter: `new JSONField()`) |
| any field with `null: true` | `T \| null` |
| `ForeignKey` named `author` | `authorId: number` plus `author` (`User \| PromiseLike`: await it, or read it directly once loaded) |
| `ManyToManyField` | a related manager |
Every model gets an implicit `id: new BigAutoField({ primaryKey: true })` unless a field sets `primaryKey: true`. `instance.pk` is an alias for whichever field is the primary key.
### Typing results and reverse relations
`declare static objects: Manager` is what makes `Post.objects.get()` return a `Post` (with your methods and getters). Without it, results are typed from the fields only. Reverse relations are created at runtime when the other model is registered, so declare them for TypeScript too. Always use `declare` (not a class field with an initializer) for these extra typings:
```ts
import { type Manager, type RelatedManager } from '@ghuri/orm'
export class Post extends Model({ /* ... */ }) {
declare static objects: Manager
declare comments: RelatedManager // from Comment.post's relatedName: 'comments'
}
```
`BaseModel` is the real root class. Use it for `instanceof` checks and in generic code: `function describe(obj: BaseModel) { return obj._meta.label }`.
If you know Django
```python
class Post(models.Model):
title = models.CharField(max_length=200)
class Meta:
ordering = ['-created_at']
```
becomes `class Post extends Model({ title: new CharField({ maxLength: 200 }) }) { static Meta = { ordering: ['-createdAt'] } }`. Field options are camelCase; columns are still snake_case in the database (`createdAt` is stored as `created_at`). `__str__` is `toString()`, and properties work as getters.
## Field options
These options work on every field type. The full list per field is in the [field reference](https://ghurijs.github.io/docs/reference/fields/).
| Option | Meaning |
| ------------------------- | ------------------------------------------------------------------------------------------- |
| `null` | Store empty values as `NULL`. Default `false`. |
| `blank` | Allow empty values in validation (forms, serializers, admin). Default `false`. |
| `default` | A value, or a function called for each new instance (`default: () => crypto.randomUUID()`). |
| `dbDefault` | A default computed by the database (`DEFAULT` clause). |
| `choices` | `[value, label][]`, or an enum-like object. Validated, and shown as a select in the admin. |
| `primaryKey` | Make this the primary key. |
| `unique` | Add a unique constraint. |
| `dbIndex` | Add an index. |
| `dbColumn` | Override the column name. |
| `editable` | `false` hides the field from the admin and from `ModelSerializer` writes. |
| `verboseName`, `helpText` | Labels and help text for the admin and OpenAPI schema. |
| `validators` | Extra validators run by `fullClean()`. |
| `errorMessages` | Override messages by code, e.g. `{ unique: 'That slug is taken.' }`. |
As in Django, `null` is about the database and `blank` is about validation. For text fields, prefer `blank: true, default: ''` to `null: true`, so there is only one “empty” value.
## Meta options
| Option | Meaning |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `dbTable` | Table name. Default `${appLabel}_${modelname}`, e.g. `blog_post`. |
| `ordering` | Default ordering for QuerySets: `['-createdAt', 'title']`. |
| `verboseName`, `verboseNamePlural` | Human-readable names. |
| `uniqueTogether` | `[['author', 'slug']]`. |
| `indexes` | `[{ fields: ['status', 'createdAt'], name?: 'post_status_idx' }]`. |
| `constraints` | Check and unique constraints. |
| `abstract` | Make an abstract base model (no table). |
| `permissions` | Extra permissions: `[['publish_post', 'Can publish posts']]`. |
| `defaultPermissions` | Default `['add', 'change', 'delete', 'view']`. |
| `getLatestBy` | Field used by `latest()` / `earliest()`. |
| `appLabel` | Override the app the model belongs to. |
| `managed` | `false` means Ghuri never creates, alters or flushes the table (migrations still track the model’s state). Default `true`. |
| `defaultManagerName` | Manager used by related lookups and internals. Default `objects`. |
| `swappable` | Name of the setting that can replace this model, like `auth.User`’s `'AUTH_USER_MODEL'`. See [Swappable models](#swappable-models). |
Indexes are `{ fields, name?, unique?, condition? }`, where `condition` is a raw SQL `WHERE` clause for a partial index and a leading `-` in `fields` makes that column descending. Constraints are `{ type: 'unique', fields, name, condition? }` or `{ type: 'check', check: 'price >= 0', name }`:
```ts
static Meta = {
indexes: [{ fields: ['-createdAt', 'status'], name: 'post_recent_idx' }],
constraints: [
{ type: 'unique', fields: ['author', 'slug'], name: 'post_author_slug_uniq' },
{ type: 'check', check: 'views >= 0', name: 'post_views_gte_0' },
],
}
```
## Registering models
A model gets its app label (and so its table name, `blog_post`) from the app that lists it:
src/blog/app.ts
```ts
import { AppConfig } from '@ghuri/core'
import * as models from './models'
export class BlogConfig extends AppConfig {
name = 'blog'
models = models
}
```
Outside `INSTALLED_APPS` (scripts, tests), set `Meta.appLabel` or call `registerModels('blog', models)`. Reverse relations only exist once the model declaring the foreign key is registered. To build a model class at runtime, use `createModelClass('Post', fields, { meta, registry })`; this is what migrations use for historical models, with an isolated `new ModelRegistry({ isolated: true })`.
## Model metadata: `_meta`
`Post._meta` exposes the model’s structure. It is a stable, public API that the admin, the REST framework, the agents package and the CLI are built on, and you can use it for generic code:
```ts
Post._meta.label // 'blog.Post'
Post._meta.dbTable // 'blog_post'
Post._meta.pk.name // 'id'
Post._meta.getField('title').maxLength // 200
Post._meta.fields.map((f) => f.name)
Post._meta.relatedObjects // reverse relations, e.g. comments
```
## Abstract base models
Share fields between models with an abstract model:
```ts
export class Timestamped extends Model({
createdAt: new DateTimeField({ autoNowAdd: true }),
updatedAt: new DateTimeField({ autoNow: true }),
}) {
static Meta = { abstract: true }
}
export class Page extends Model(
{ title: new CharField({ maxLength: 200 }), body: new TextField() },
{ extends: Timestamped },
) {}
```
`Page` gets `createdAt` and `updatedAt` and its own table; `Timestamped` has no table. You can also spread fields: `Model({ ...Timestamped.fields, title: ... })`. Multi-table inheritance and proxy models are not supported in 0.1.
## Swappable models
A reusable app can let projects replace one of its models, the way `AUTH_USER_MODEL` replaces `auth.User`. The model names a setting in `Meta.swappable`; a dotted name reads a nested setting:
```ts
export class Conversation extends Model({ ...conversationFields }) {
static Meta = { appLabel: 'agents', swappable: 'AGENTS.CONVERSATION_MODEL' }
}
```
While the setting is unset (or names the model itself), nothing changes. When it names another model (`AGENTS: { CONVERSATION_MODEL: 'shop.Conversation' }`), the built-in model is *swapped*:
* `Conversation._meta.swapped` is `'shop.Conversation'` (otherwise `undefined`).
* It is not installed: `apps.getModels()` and the migration autodetector skip it, and it gets no table. Its migration operations are skipped too (see [Swappable models in migrations](https://ghurijs.github.io/docs/topics/migrations/#swappable-models-in-migrations)).
* Its managers throw `Manager isn't available; 'agents.Conversation' has been swapped for 'shop.Conversation'`, and its relations are not reverse relations of their targets.
Code that should follow the setting asks for the model instead of importing it:
```ts
import { getSwappableModel } from '@ghuri/orm'
const Conversation = getSwappableModel('AGENTS.CONVERSATION_MODEL', 'agents.Conversation')
new ForeignKey(() => getSwappableModel('AGENTS.CONVERSATION_MODEL', 'agents.Conversation'), { … })
```
`getSwappableModel(setting, default)` throws `ImproperlyConfigured` when the setting is not `'app_label.ModelName'` or names a model that is not installed. Packages usually wrap it, like `getUserModel()` in `@ghuri/auth` and `getConversationModel()` in `@ghuri/agents`.
Set a swappable setting before the first `migrate`. The replacement must not be created in a migration that depends on the app it replaces. Changing it on a database that already has the tables needs a hand-written migration; see the agents example in [Your own conversation model](https://ghurijs.github.io/docs/topics/agents/#your-own-conversation-model).
## Managers
`Post.objects` is the default manager, the entry point for queries. Add your own for common filters:
```ts
import { Manager } from '@ghuri/orm'
class LiveManager extends Manager {
getQueryset() {
return super.getQueryset().filter({ status: 'live' })
}
byTag(name: string) {
return this.getQueryset().filter({ tags__name: name })
}
}
export class Post extends Model({ /* ... */ }) {
declare static objects: Manager
static live = new LiveManager()
}
await Post.live.byTag('typescript').count()
```
`objects` always exists, and extra managers are static properties. To change the default manager’s behaviour, assign your own: `static objects = new PostManager()`. Unlike Django, the default manager (used for related lookups) is always `objects` unless you set `Meta.defaultManagerName`.
## Saving, deleting and validating
```ts
const post = new Post({ title: 'Hi', slug: 'hi', authorId: 1 })
await post.save() // INSERT
post.title = 'Hello'
await post.save({ updateFields: ['title'] }) // UPDATE only that column
await post.refreshFromDb() // or refreshFromDb({ fields: ['title'] })
await post.delete() // [total, { 'blog.Post': 1, 'blog.Comment': 3 }]
```
`save()` also accepts `{ forceInsert, forceUpdate, using }`. `delete()` runs the `onDelete` rules of every foreign key pointing at the object, sends delete signals and returns the number of deleted rows, in total and per model.
`save()` does not validate. Call `fullClean()` first when data comes from users (the admin and `ModelSerializer` do this for you). It runs field validation, `choices`, your `clean()` method, foreign-key existence checks and uniqueness checks (`unique`, `uniqueTogether`, unique constraints) against the database, and throws `ValidationError` with a `messageDict`. `fullClean({ exclude: ['slug'], validateUnique: false })` narrows it:
```ts
import { ValidationError } from '@ghuri/core'
export class Post extends Model({ /* ... */ }) {
clean() {
if (this.status === 'live' && !this.body) {
throw new ValidationError({ body: ['A published post needs a body.'] })
}
}
}
try {
await post.fullClean()
} catch (e) {
if (e instanceof ValidationError) console.log(e.messageDict)
}
```
Override `save()` to add behaviour, and call `super.save()`:
```ts
async save(opts?: { updateFields?: string[] }) {
if (!this.slug) this.slug = this.title.toLowerCase().replace(/[^a-z0-9]+/g, '-')
await super.save(opts)
}
```
When the database itself rejects a write, the error is normalised across backends: `IntegrityError` (unique, foreign key, `NOT NULL` or check violations), `NotSupportedError`, or the base `DatabaseError`, all exported from `@ghuri/orm`. Deletes refused by `onDelete` raise `ProtectedError` or `RestrictedError`; an unknown field in a query raises `FieldError`.
For behaviour that should run for every save including `bulkCreate`, prefer [signals](https://ghurijs.github.io/docs/topics/signals/) or explicit service functions; like Django, bulk operations do not call `save()`.
## Serialising instances
`instance.toJSON()` returns a plain object of concrete field values (foreign keys as their `...Id`), so `JSON.stringify(post)` and `json(c, post)` work. For API output with control over fields and relations, use a [serializer](https://ghurijs.github.io/docs/topics/rest/serializers/).
## The escape hatch
QuerySets compile to SQL with the ORM’s own builder (`qs.toSQL()` returns `{ sql, params }`), but each model also has a generated Drizzle table, for queries the ORM cannot express:
```ts
import { getDrizzle } from '@ghuri/orm'
import { sql } from 'drizzle-orm'
const db = await getDrizzle()
const posts = Post.table()
const rows = await db.select({ day: sql`date(${posts.createdAt})`, n: sql`count(*)` })
.from(posts).groupBy(sql`1`)
```
`Post.table()` uses the dialect of the default database; `getTable(Post, 'postgresql')` and `getSchema([Post, Comment], dialect)` (keyed by class name, including auto-created many-to-many tables) build tables for a given dialect, and `field.drizzleColumn(dialect)` builds a single column. Drizzle columns are keyed by attribute name (`posts.createdAt`, `posts.authorId`), and values are converted the same way the ORM converts them.
Code written this way is dialect-specific when it uses raw SQL, so keep it in one place.
# Making queries
> The QuerySet API - filtering, lookups across relations, ordering, slicing, Q and F expressions, aggregation, updates, deletes and raw SQL.
Once you have models, Ghuri gives you a database API to create, read, update and delete objects. It is Django’s QuerySet API, made `async`. This page uses the blog models from the [tutorial](https://ghurijs.github.io/docs/tutorial/part-1-models/).
## QuerySets are lazy
A `QuerySet` describes a query. Building one does no I/O; the database is hit only when you consume it:
```ts
const qs = Post.objects.filter({ published: true }).orderBy('-createdAt') // no query yet
const posts = await qs // runs the query → Post[]
for await (const post of qs) { /* ... */ } // runs the query, then iterates the results
const n = await qs.count() // SELECT COUNT(*)
```
For large tables, `qs.iterator(chunkSize = 2000)` fetches in pages of `chunkSize` rows (ordered by primary key unless the QuerySet is already ordered) instead of loading everything at once:
```ts
for await (const post of Post.objects.filter({ published: true }).iterator(500)) { /* ... */ }
```
Returning a QuerySet from an async function
QuerySets are thenable, so `return qs` from an `async` function resolves it to an array. Return it from a plain function, or wrap it in an object, when you want to keep the QuerySet.
QuerySets are **immutable**. Each method returns a new QuerySet, so you can safely build a base query and refine it:
```ts
const live = Post.objects.filter({ published: true })
const recent = live.filter({ createdAt__gte: lastWeek })
const byRifat = live.filter({ author__username: 'rifat' })
```
If you know Django
Everything is the same except the two TypeScript adaptations: keyword arguments become an object (`filter(title__icontains='x')` → `filter({ title__icontains: 'x' })`), and evaluating a QuerySet is `await qs` rather than iterating, slicing or calling `list()`. Methods are camelCase: `order_by` → `orderBy`, `select_related` → `selectRelated`, `values_list` → `valuesList`, `get_or_create` → `getOrCreate`.
## Creating objects
```ts
const post = await Post.objects.create({ title: 'Hello', slug: 'hello', author: user })
const draft = new Post({ title: 'Draft', slug: 'draft', authorId: user.pk })
await draft.save()
const [tag, created] = await Tag.objects.getOrCreate({ name: 'typescript' })
const [post2, wasCreated] = await Post.objects.updateOrCreate(
{ slug: 'hello' },
{ defaults: { title: 'Hello again' } }, // also: createDefaults (used only when creating)
)
await Tag.objects.bulkCreate([new Tag({ name: 'a' }), new Tag({ name: 'b' })])
await Tag.objects.bulkCreate(tags, { batchSize: 500, ignoreConflicts: true })
await Post.objects.bulkUpdate(posts, ['title', 'status']) // number of rows
```
`getOrCreate()` takes `{ defaults }` as its second argument and returns `[obj, created]`. `bulkCreate()` uses multi-row `INSERT`s and sets primary keys on the instances (except with `ignoreConflicts`); like `bulkUpdate()`, it does not call `save()` or send signals.
## Retrieving objects
```ts
await Post.objects.all()
await Post.objects.filter({ published: true })
await Post.objects.exclude({ title__startswith: 'Draft' })
await Post.objects.get({ slug: 'hello' }) // exactly one, or throws
await Post.objects.filter({ published: true }).first() // Post | null (also last())
await Post.objects.latest('createdAt') // also earliest()
await Post.objects.filter({ slug: 'hello' }).exists()
```
`get()` throws `Post.DoesNotExist` when nothing matches and `Post.MultipleObjectsReturned` when more than one does. Both also extend the generic `ObjectDoesNotExist` and `MultipleObjectsReturned` from `@ghuri/core`, so you can catch them without knowing the model:
```ts
try {
const post = await Post.objects.get({ slug })
} catch (e) {
if (e instanceof Post.DoesNotExist) return c.notFound()
throw e
}
```
In views, `getObjectOr404(Post, { slug })` does that for you, throwing `Http404` instead. It accepts a model, a manager or a QuerySet; `getListOr404(source, filters)` does the same for a list that must not be empty.
### Field lookups
A filter key is a field name, optionally followed by `__` and a lookup. Without a lookup, `exact` is implied.
```ts
Post.objects.filter({ title__icontains: 'ghuri' })
Post.objects.filter({ createdAt__year: 2026, createdAt__month__gte: 6 })
Post.objects.filter({ id__in: [1, 2, 3] })
Post.objects.filter({ body__isnull: false })
Post.objects.filter({ views__range: [100, 1000] })
```
Several keys in one `filter()` are ANDed. The complete list (`exact`, `iexact`, `contains`, `icontains`, `in`, `gt`, `gte`, `lt`, `lte`, `startswith`, `istartswith`, `endswith`, `iendswith`, `range`, `isnull`, `regex`, `iregex`, and the transforms `date`, `year`, `month`, `day`, `hour`, `minute`, `second`, `week_day`, `quarter`, `time`), with the SQL each produces on SQLite and Postgres, is in the [lookup reference](https://ghurijs.github.io/docs/reference/lookups/).
### Lookups that span relations
Follow relations with `__`, as far as you need, forwards and backwards:
```ts
// Posts by a user whose username is 'rifat' (forward FK)
Post.objects.filter({ author__username: 'rifat' })
// Posts tagged 'cloudflare' (M2M)
Post.objects.filter({ tags__name: 'cloudflare' })
// Users who have written a published post (reverse FK, via relatedName 'posts')
User.objects.filter({ posts__published: true })
// Posts with a comment by an author called 'sam'
Post.objects.filter({ comments__author__username: 'sam' })
```
When spanning a multi-valued relation, conditions inside one `filter()` call apply to the same related object, while chained `filter()` calls may match different ones. This is the same subtle rule as Django’s. Unlike Django, multi-valued relations compile to `EXISTS (...)` subqueries, so results are never duplicated and `distinct()` is rarely needed.
### Ordering and slicing
```ts
Post.objects.orderBy('-createdAt', 'title')
Post.objects.orderBy('author__username')
Post.objects.orderBy(F('rating').desc({ nullsLast: true }))
Post.objects.all().slice(0, 10) // LIMIT 10 (also .limit(10))
Post.objects.all().slice(20, 30) // OFFSET 20 LIMIT 10
```
Without `orderBy`, the model’s `Meta.ordering` applies; `reverse()` flips the ordering. NULLs sort first in ascending order on every backend (pass `nullsFirst`/`nullsLast` to change it). `slice()` takes non-negative bounds; negative indexing is not supported (use `orderBy` the other way).
### Values instead of instances
```ts
await Post.objects.values('id', 'title') // { id, title }[]
await Post.objects.values('author__username') // across relations
await Post.objects.valuesList('id', { flat: true }) // number[]
await Post.objects.inBulk([1, 2, 3]) // Map
await Post.objects.inBulk(['a', 'b'], { fieldName: 'slug' }) // Map
```
`inBulk()` returns a `Map`, not a plain object. `only('id', 'title')` and `defer('body')` load instances with fewer columns; deferred fields are `undefined` until `refreshFromDb({ fields: ['body'] })`. `distinct()` takes no field names (`DISTINCT ON` is not supported). `none()` returns an empty QuerySet without querying, and `using('replica')` runs the query on another database alias.
## Complex lookups with `Q`
Use `Q` objects for `OR` and `NOT`:
```ts
import { Q } from '@ghuri/orm'
Post.objects.filter(
Q({ title__icontains: 'edge' }).or(Q({ body__icontains: 'edge' })),
)
Post.objects.filter(
Q({ published: true }).and(Q.not({ author__username: 'bot' })),
)
```
`Q.and()`, `Q.or()` and `Q.not()` combine any number of conditions; `q.not()` negates an existing one. A `Q` and a plain object can be passed together: `filter(Q(...).or(Q(...)), { published: true })`.
## Referring to fields with `F`
`F('field')` refers to a column’s value inside the query, so the database does the work and there is no race between reading and writing:
```ts
import { F } from '@ghuri/orm'
await Post.objects.filter({ slug }).update({ views: F('views').add(1) })
await Post.objects.filter({ updatedAt__gt: F('createdAt') })
await Post.objects.filter({ views__gt: F('likes').mul(2) })
```
`F` supports `add`, `sub`, `mul`, `div` and `mod`, and `asc()`/`desc()` for ordering.
## Aggregation and annotation
```ts
import { Count, Avg, Max, Sum } from '@ghuri/orm'
await Post.objects.aggregate({ total: Count('id'), avgViews: Avg('views') })
// { total: 42, avgViews: 118.5 }
const busy = await Post.objects
.annotate({ numComments: Count('comments') })
.filter({ numComments__gt: 2 })
.orderBy('-numComments')
busy[0].numComments // annotated values are available on instances
```
`values()` before `annotate()` groups by those fields, as in Django:
```ts
await Post.objects.values('author__username').annotate({ posts: Count('id') })
```
Aggregates take `{ distinct, filter }`. Aggregates over reverse or many-to-many relations in `annotate()` compile to correlated subqueries, so combining several of them does not multiply rows:
```ts
await Post.objects.annotate({
approved: Count('comments', { filter: Q({ comments__approved: true }) }),
tagCount: Count('tags', { distinct: true }),
})
```
### Database functions
`annotate()`, `filter()` values, `orderBy()` and `update()` also accept expressions:
| Expression | SQL |
| ----------------------------------------------------- | ------------------------------------------------------- |
| `Value(x)` | a bound literal |
| `Lower('title')`, `Upper('title')`, `Length('title')` | `LOWER(...)`, `UPPER(...)`, `LENGTH(...)` |
| `Coalesce('summary', 'title')` | `COALESCE(...)` |
| `Concat('firstName', Value(' '), 'lastName')` | `\|\|` concatenation; NULL parts count as `''` |
| `Now()` | the current timestamp |
| `new Func('ROUND', ['price'])` | any SQL function; string arguments are field references |
| `new RawSQL('LENGTH("title") > ?', [5])` | raw SQL with `?` parameters (not portable) |
```ts
import { Concat, Lower, Value } from '@ghuri/orm'
await User.objects.annotate({ fullName: Concat('firstName', Value(' '), 'lastName') })
await Tag.objects.orderBy(Lower('name'))
```
## Updating and deleting in bulk
```ts
const updated = await Post.objects.filter({ published: false }).update({ published: true }) // number
const [total, perModel] = await Post.objects.filter({ createdAt__lt: cutoff }).delete()
// total: 14, perModel: { 'blog.Post': 4, 'blog.Comment': 10 }
```
`update()` runs a single `UPDATE` and does not call `save()` or send `preSave`/`postSave`. `delete()` collects related objects according to each foreign key’s `onDelete` rule (cascades, `SET_NULL`, `PROTECT`), sends delete signals and deletes everything in dependency order. See [Relations](https://ghurijs.github.io/docs/topics/relations/#on-delete).
## Performance
* **`selectRelated('author')`** joins forward foreign keys into the same query, so `await post.author` needs no extra round trip.
* **`prefetchRelated('tags', 'comments')`** fetches many-valued relations in one extra query per relation, instead of one per object.
* **`count()` and `exists()`** are cheaper than loading rows.
* **`new Prefetch('comments', { queryset: Comment.objects.filter({ approved: true }), toAttr: 'approvedComments' })`** customises a prefetch; with `toAttr` the results are stored as an array on that attribute.
* On D1, every query is a network round trip from the Worker to the database. Batching reads with `selectRelated`/`prefetchRelated` matters even more than on a local Postgres.
* **Count queries** in tests or while debugging: `const [result, queries] = await captureQueries(() => view())` returns every statement a block executed, and `onQuery((e) => console.log(e.sql, e.durationMs))` subscribes to all of them (it returns an unsubscribe function).
## Raw SQL
When you need SQL the ORM cannot express:
```ts
import { connections } from '@ghuri/orm'
const conn = await connections.get() // 'default' alias
const { rows } = await conn.execute(
'SELECT author_id, COUNT(*) AS n FROM blog_post WHERE created_at > ? GROUP BY author_id',
[cutoff.toISOString()],
)
```
`conn.execute()` passes the SQL to the driver unchanged: use `?` placeholders on D1 and SQLite and `$1`, `$2` on Postgres. For one statement that works on both, build it with the `sql` tag from `@ghuri/orm/migrations` and render it for the connection’s dialect:
```ts
import { sql } from '@ghuri/orm/migrations'
const q = sql`SELECT author_id, COUNT(*) AS n FROM blog_post WHERE created_at > ${cutoff} GROUP BY author_id`
const { sql: text, params } = q.render(conn.dialect) // ? or $1, $2 as needed
const { rows } = await conn.execute(text, params)
```
Raw SQL is where portability ends, so check `conn.dialect` (`'sqlite'` or `'postgresql'`) if you must support both, or use Drizzle through [`getDrizzle()`](https://ghurijs.github.io/docs/topics/models/#the-escape-hatch). `qs.toSQL()` shows the SQL a QuerySet would run.
# Relations
> ForeignKey, OneToOneField and ManyToManyField, related managers, loading related objects, through models and on-delete behaviour.
Ghuri supports Django’s three relationship types: many-to-one (`ForeignKey`), one-to-one (`OneToOneField`) and many-to-many (`ManyToManyField`). Examples use the blog models from the [tutorial](https://ghurijs.github.io/docs/tutorial/part-1-models/).
## Declaring relations
```ts
author: new ForeignKey(() => User, { onDelete: CASCADE, relatedName: 'posts' }),
profile: new OneToOneField(() => User, { onDelete: CASCADE, relatedName: 'profile' }),
tags: new ManyToManyField(() => Tag, { blank: true, relatedName: 'posts' }),
```
The target is a model class, a function returning one, or a string label:
* `() => Tag` works regardless of declaration order and avoids circular import problems, because it is resolved after every app is loaded.
* `'auth.User'` or `'blog.Tag'` works without importing the model at all. Use it to refer to models in apps that import yours, or to a swappable user model (`getUserModel()` returns it at runtime).
* `'Tag'` (no app label) refers to a model in the same app.
* `'self'` makes a recursive relation: `parent: new ForeignKey('self', { null: true, onDelete: CASCADE })`.
Options:
| Option | Meaning |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onDelete` | Required for `ForeignKey`/`OneToOneField`. See [below](#on-delete). |
| `relatedName` | Name of the reverse accessor on the target (`user.posts`). Default: the camelCase model name plus `Set`, e.g. `user.postSet` (for a one-to-one, just `user.profile`). `'+'` hides the reverse relation. |
| `relatedQueryName` | Name used in reverse lookups (`User.objects.filter({ post__title: ... })`). Defaults to `relatedName` when set, otherwise the lower-camel model name (`post`). |
| `toField` | Target field to point at, if not the primary key. |
| `limitChoicesTo` | A filter object (or a function returning one) that restricts choices in the admin and serializers. |
| `dbConstraint` | `false` skips the database foreign key constraint. Default `true`. |
| `through`, `throughFields` | (M2M) an explicit intermediate model, and which two of its foreign keys to use. |
| `null`, `blank`, `dbIndex`, … | As for any field. Foreign keys are indexed by default. |
Django difference
Without `relatedName`, the reverse accessor is camelCase `postSet` (Django: `post_set`) and the lookup name is `post`. Reverse relations exist only once the model declaring the foreign key is registered (through `INSTALLED_APPS` or `registerModels()`), and TypeScript only knows about them if you declare them: `declare posts: RelatedManager` in the `User` subclass, or `declare postSet: RelatedManager` when you kept the default name.
## Forward access: foreign keys
A `ForeignKey` named `author` gives each instance two properties:
```ts
post.authorId // the raw value of the author_id column; no query
await post.author // the related User, loaded on first access and then cached
post.author = user // assignment sets authorId
post.authorId = 7 // and so does setting the id
await post.save()
```
`post.author` is awaitable because loading it may need a query. If the object was fetched with `selectRelated('author')`, or the relation was already loaded, `post.author` is the instance itself (awaiting it still works and needs no I/O). A nullable foreign key is `null` when the id is `null`; a missing non-null relation rejects with `User.DoesNotExist`. You cannot assign an unawaited related object: `post.author = await other.author`.
```ts
const posts = await Post.objects.selectRelated('author').filter({ published: true })
for (const p of posts) {
console.log((await p.author).username) // no extra queries
}
```
If you know Django
`post.author_id` is `post.authorId`, and `post.author` is the same lazily-loaded descriptor, except you `await` it. The classic N+1 problem and its fix (`select_related`) are exactly as in Django. Because a forgotten `selectRelated` costs a round trip to D1 per row, count queries early: `captureQueries()` and `onQuery()` from `@ghuri/orm` report every statement a block runs (see [Making queries](https://ghurijs.github.io/docs/topics/queries/#performance)).
## Reverse access: related managers
The model on the other side of a `ForeignKey` gets a **related manager** named by `relatedName`. It behaves like a manager whose QuerySet is pre-filtered:
```ts
await user.posts.all()
await user.posts.filter({ published: true }).count()
await user.posts.create({ title: 'New', slug: 'new' }) // sets author automatically
await post.comments.orderBy('-createdAt').first()
```
For a `OneToOneField`, the reverse side is a single object: `await user.profile` resolves to the `Profile`, or throws `Profile.DoesNotExist`.
## Many-to-many
Both sides of a `ManyToManyField` get a related manager with extra methods:
```ts
await post.tags.add(ts, cf) // instances or primary keys
await post.tags.remove(cf)
await post.tags.set([ts]) // replace the whole set
await post.tags.clear()
await post.tags.all()
await tag.posts.filter({ published: true }) // reverse side
```
The object must be saved (have a primary key) before you change its many-to-many relations. Changes send the `m2mChanged` signal. Forward assignment (`post.tags = [...]`) is not allowed; use `post.tags.set([...])`.
Ghuri creates the join table for you (`blog_post_tags` with an `id`, `post_id` and `tag_id`, named like Django’s). To store data on the relationship itself, declare a `through` model:
```ts
export class Membership extends Model({
person: new ForeignKey(() => Person, { onDelete: CASCADE }),
group: new ForeignKey(() => Club, { onDelete: CASCADE }),
role: new CharField({ maxLength: 20 }),
joinedAt: new DateField(),
}) {
static Meta = { uniqueTogether: [['person', 'group']] }
}
export class Club extends Model({
name: new CharField({ maxLength: 100 }),
members: new ManyToManyField(() => Person, { through: () => Membership, relatedName: 'clubs' }),
}) {}
await club.members.add(alice, { throughDefaults: { role: 'chair', joinedAt: '2026-11-01' } })
await Membership.objects.filter({ group: club, role: 'chair' })
```
## Loading related objects efficiently
| Method | Use for | Queries |
| -------------------------------------------- | ------------------------- | ---------------------------- |
| `selectRelated('author', 'author__profile')` | forward FK and one-to-one | joined into the main query |
| `prefetchRelated('tags', 'comments')` | M2M and reverse FK | one extra query per relation |
```ts
const posts = await Post.objects
.filter({ published: true })
.selectRelated('author')
.prefetchRelated('tags', 'comments')
for (const p of posts) {
const tags = await p.tags.all() // served from the prefetch cache
}
```
Calling `filter()` on a prefetched manager (`p.tags.filter(...)`) builds a new query, as in Django, so filter in the prefetch rather than per object when you can, with a `Prefetch` object:
```ts
import { Prefetch } from '@ghuri/orm'
const posts = await Post.objects.prefetchRelated(
'tags__posts', // lookups can span relations
new Prefetch('comments', {
queryset: Comment.objects.filter({ approved: true }).orderBy('-createdAt'),
toAttr: 'approvedComments', // stored as an array on each post
}),
)
```
`prefetchRelatedObjects(instances, ...lookups)` does the same for a list of instances you already have.
## On delete
`onDelete` decides what happens to rows that point at an object being deleted:
| Constant | Behaviour |
| --------------------------------- | ---------------------------------------------------------------------------------------------- |
| `CASCADE` | Delete the referring objects too. |
| `PROTECT` | Refuse, throwing `ProtectedError`. |
| `RESTRICT` | Refuse unless the referring objects are also being deleted by a cascade in the same operation. |
| `SET_NULL` | Set the foreign key to `NULL` (requires `null: true`). |
| `SET_DEFAULT` | Set it to the field’s default. |
| `SET(value)` / `SET(() => value)` | Set it to a value, or the result of a function (an instance or a key). |
| `DO_NOTHING` | Do nothing; the database may reject the delete. |
These rules are **enforced by the ORM**, not by database `ON DELETE` clauses, exactly as Django does it. Before deleting, Ghuri collects every affected object, sends `preDelete`/`postDelete` signals for each, and applies updates and deletes in a safe order. That is why behaviour is identical on D1, SQLite and Postgres, and why `qs.delete()` returns per-model counts:
```ts
const [total, perModel] = await User.objects.filter({ username: 'spam' }).delete()
// total: 14, perModel: { 'auth.User': 1, 'blog.Post': 3, 'blog.Comment': 10 }
```
`PROTECT` raises `ProtectedError` and `RESTRICT` raises `RestrictedError` (both exported from `@ghuri/orm`) before anything is deleted. The flip side is the same as Django’s: rows deleted with raw SQL bypass these rules.
Cascades on D1
The collector runs inside `atomic()`, which has no rollback on D1. A failure part-way through a large cascade on D1 can leave some rows deleted. See [Transactions](https://ghurijs.github.io/docs/topics/transactions/#d1).
# Migrations
> How Ghuri migrations work, the operations, data migrations, applying them to D1 and Postgres, and squashing the workflow into a deploy.
Migrations propagate changes you make to your models (adding a field, deleting a model, adding an index) into your database schema. They are generated from your models, stored as TypeScript files in each app, committed to version control, and applied in order. They are **dialect-neutral**: the same files run on D1, SQLite and Postgres, which is what makes moving between databases a settings change.
## The commands
| Command | Does |
| ------------------------------- | ------------------------------------------------------------------------ |
| `ghuri makemigrations [app...]` | Compare models with the migration history and write new migration files. |
| `ghuri migrate [app] [name]` | Apply (or, with a target name, roll back to) migrations. |
| `ghuri showmigrations [app...]` | List migrations and whether each is applied (`[X]` / `[ ]`). |
| `ghuri sqlmigrate ` | Print the SQL a migration would run. |
Their options:
| Command | Options |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `makemigrations` | `--name `, `--empty`, `--dry-run`, `--check` (exit non-zero if changes are missing migrations; writes nothing), `--merge`, `--no-input` |
| `migrate` | `--fake`, `--fake-initial`, `--plan`, `--run-syncdb`, `--no-input`, `--database ` |
| `showmigrations` | `--plan`, `--database ` |
| `sqlmigrate` | `--backwards`, `--dialect sqlite\|postgresql`, `--all [--out ]`, `--database ` |
`--database` picks a key of `DATABASES` (default `default`), with Django’s semantics. Every command also accepts the CLI’s global `--remote` to work against your deployed Cloudflare resources instead of the local simulation. See the [CLI reference](https://ghurijs.github.io/docs/reference/cli/) for details.
If you know Django
This is Django’s migration system, re-implemented: the same autodetector approach, the same operations, a dependency graph between apps, a table recording what ran (`ghuri_migrations` instead of `django_migrations`), and data migrations with historical models. `RunPython(forwards, backwards)` becomes `RunCode(forwards, backwards)` with async functions.
## Migration files
```plaintext
src/blog/migrations/
├── 0001_initial.ts
├── 0002_post_summary.ts
└── index.ts # generated: exports every migration in order
```
An app opts in to migrations with a `migrations` package (created by `ghuri startapp`) and a `path`, which tells the CLI where to write files:
src/blog/app.ts
```ts
import { AppConfig } from '@ghuri/core'
import * as migrations from './migrations'
import * as models from './models'
export class BlogConfig extends AppConfig {
name = 'blog'
path = import.meta.dirname // CLI only: where migrations/ lives
models = models
migrations = migrations // the generated index: works on Workers (no file system)
}
```
A migration is a `Migration` with dependencies and a list of operations:
src/blog/migrations/0002_post_summary.ts
```ts
import { Migration, operations as ops } from '@ghuri/orm/migrations'
export default new Migration({
dependencies: [['blog', '0001_initial'], ['auth', '0001_initial']],
operations: [
ops.AddField({
modelName: 'Post',
name: 'summary',
field: { type: 'CharField', maxLength: 300, blank: true, default: '' },
}),
ops.AddField({
modelName: 'Post',
name: 'slug',
field: { type: 'SlugField' },
oneOffDefault: 'post', // fills existing rows; not kept on the field
}),
],
})
```
Fields are written as plain data (`{ type, ...options }`), produced by each field’s `deconstruct()`. Migrations therefore do not import your models: they describe the state of the schema at that point in history, which is what lets old migrations keep working after the models have moved on. Index and constraint names are always written out explicitly.
The `index.ts` file exists because Workers have no filesystem. `makemigrations` regenerates it every time (it exports every migration plus an ordered `migrations` map), and `AppConfig.migrations` imports it, so migrations are part of your bundle.
## What `makemigrations` detects
* Created, deleted and renamed models and fields; altered fields; many-to-many fields.
* `Meta.indexes`, `Meta.constraints`, `uniqueTogether`, `dbTable` and other Meta options.
* Dependencies between apps (`['auth', '0001_initial']`). Foreign-key cycles between apps are split into two migrations.
It is interactive by default. When a field or model disappears and a similar one appears, it asks whether you renamed it, so you get `RenameField` / `RenameModel` instead of losing data. When you add a `NOT NULL` field without a default (or make a field `NOT NULL`), it asks for a one-off default to fill existing rows, stored as `oneOffDefault` on the operation. Callable defaults (`default: () => ({})`) are evaluated once to fill existing rows, and `autoNow`/`autoNowAdd` fields get the current time.
With `--no-input`, renames are treated as a removal plus an addition. A new `NOT NULL` field without a default is an error; making an existing field `NOT NULL` only prints a warning, and the migration will fail if NULL rows remain. Edit the generated file if you need a rename in a non-interactive run, or call `makeMigrations({ questioner: new NonInteractiveQuestioner({ renames: true, defaults: { 'blog.Post.slug': 'post' } }) })` from code.
Names follow Django: `0001_initial`, `0002_post_slug`, `0003_remove_post_body`, or `auto_YYYYMMDD_HHMM` when no better name fits. `--name` overrides the part after the number.
Not yet supported
`squashmigrations` and `inspectdb` do not exist yet. Swappable models (`AUTH_USER_MODEL`) are written into dependencies as plain app labels rather than swappable-dependency markers, and the autodetector does not handle changing a model’s primary key or auto-field type. Write those changes by hand (for example with `RunSQL`) if you need them.
## Operations
| Operation | Purpose |
| -------------------------------------------------------------------- | --------------------------------------------------------------- |
| `CreateModel`, `DeleteModel`, `RenameModel` | Tables |
| `AlterModelTable`, `AlterModelOptions` | Table name, Meta options (ordering, verbose names, permissions) |
| `AddField`, `RemoveField`, `AlterField`, `RenameField` | Columns |
| `AddIndex`, `RemoveIndex` | Indexes |
| `AddConstraint`, `RemoveConstraint`, `AlterUniqueTogether` | Constraints |
| `RunSQL({ sql?, sqlite?, postgresql?, reverse?, stateOperations? })` | Raw SQL, per dialect |
| `RunCode(forwards, backwards?)` | Data migrations in TypeScript |
`RunSQL` takes SQL for both dialects (`sql`) or per dialect; a dialect without SQL is skipped, which keeps the migration portable. `reverse` makes it reversible (`ops.RunSQL.noop` for a reversible no-op), and `stateOperations` tells the autodetector what schema change the SQL made:
```ts
ops.RunSQL({
sqlite: "UPDATE blog_post SET slug = lower(title) WHERE slug = ''",
postgresql: "UPDATE blog_post SET slug = lower(title) WHERE slug = ''",
reverse: ops.RunSQL.noop,
})
```
## Data migrations
To change data rather than schema, create an empty migration and add a `RunCode` operation:
```sh
npx ghuri makemigrations blog --empty --name backfill_summaries
```
src/blog/migrations/0003_backfill_summaries.ts
```ts
import { Migration, operations as ops } from '@ghuri/orm/migrations'
export default new Migration({
dependencies: [['blog', '0002_post_summary']],
operations: [
ops.RunCode(
async (apps, conn, { using }) => {
const Post = apps.getModel('blog', 'Post') // or apps.getModel('blog.Post')
for await (const post of Post.objects.using(using).filter({ summary: '' })) {
post.summary = String(post.body).slice(0, 280)
await post.save({ updateFields: ['summary'], using })
}
},
ops.RunCode.noop, // reversible as a no-op
),
],
})
```
Always use `apps.getModel()` inside `RunCode`. It returns a **historical model** that matches the schema at this point in the migration history, not your current class, which may have fields the database does not have yet. Custom methods are not available on historical models.
The second argument is the `Connection`, for raw SQL inside the same migration (`await conn.execute('UPDATE ...')`), and the third carries the database alias (`using`) being migrated. Pass `using` on to queries so the migration works with `--database`.
## Swappable models in migrations
Relations to a [swappable model](https://ghurijs.github.io/docs/topics/models/#swappable-models) are written through its setting, so a reusable app’s migrations work whichever model the project picked (Django’s `settings.AUTH_USER_MODEL` and `swappable_dependency()`):
```ts
import { Migration, operations as ops, swappableDependency, swappableModel } from '@ghuri/orm/migrations'
export default new Migration({
dependencies: [['blog', '0001_initial'], swappableDependency('AUTH_USER_MODEL', 'auth.User')],
operations: [
ops.AddField({
modelName: 'Post',
name: 'editor',
field: { type: 'ForeignKey', to: swappableModel('AUTH_USER_MODEL', 'auth.User'), onDelete: 'CASCADE' },
}),
],
})
```
* `makemigrations` writes these for every relation to a model named by a swappable setting (`auth.User`, or your user model when `AUTH_USER_MODEL` points at it). Existing migrations that name the model directly keep working.
* `swappableModel(setting, default)` reads as the label the setting names when the migration runs.
* `swappableDependency(setting, default)` depends on the migration that creates that model (else on the first migration of its app, Django’s `__first__`). It is ignored when it names the migration’s own app, it falls back to `__first__` when the creating migration itself depends on this one, and an already applied migration is not reported as an inconsistent history because of it.
* A `CreateModel` with `options.swappable` (written for models with `Meta.swappable`) is skipped when the setting names another model, together with every later operation on that model, so the swapped model gets no table.
## Dialects: D1, SQLite and Postgres
Operations are dialect-neutral; a schema editor per dialect turns them into SQL.
* **Postgres** uses plain `ALTER TABLE ... ALTER COLUMN TYPE / SET NOT NULL / SET DEFAULT`, named unique and check constraints, and `DEFERRABLE INITIALLY DEFERRED` foreign keys. Each migration runs in a transaction together with its `ghuri_migrations` record.
* **SQLite and D1** use `ALTER TABLE ... ADD / DROP / RENAME COLUMN` where SQLite allows it. Anything else (changing a column, unique / `NOT NULL` / foreign-key columns, check constraints) rebuilds the table like Django’s SQLite backend, in a D1-safe way: D1 cannot disable foreign keys, so Ghuri sets `PRAGMA defer_foreign_keys = ON`, copies the rows through a temporary table, recreates the table and its indexes, and copies the rows back. Data is kept.
Check what will run before applying a migration to a big D1 table:
```sh
npx ghuri sqlmigrate blog 0004 --dialect sqlite
npx ghuri sqlmigrate blog 0004 --dialect postgresql --backwards
```
D1 and transactions
D1 has no interactive transactions. Ghuri sends each migration’s statements, together with its `ghuri_migrations` record, to D1 as a single batch, which D1 executes atomically, so a failing migration does not leave half its statements applied. `RunCode` operations cannot be part of that batch: the statements before a `RunCode` are sent as their own batch first, and the callback’s writes are applied as they happen. Keep data migrations idempotent so a retry is safe. See [Transactions](https://ghurijs.github.io/docs/topics/transactions/#d1).
## Signals
`migrate` sends `preMigrate` before and `postMigrate` after applying migrations, once per installed app, with the `AppConfig` as sender and `{ appConfig, using, plan }` as arguments. `@ghuri/auth` uses `postMigrate` to create content types and permissions. `postMigrate` is also sent after `flush` and by `setupTestDatabase()` in tests.
```ts
import { postMigrate } from '@ghuri/orm'
postMigrate.connect(async ({ appConfig, using }) => {
if (appConfig.appLabel === 'blog') await ensureDefaultCategories(using)
})
```
## Applying migrations in production
On Cloudflare:
```sh
npx ghuri migrate --remote
```
If you would rather let Wrangler own migrations (for example in a CI pipeline that already runs `wrangler d1 migrations apply`), export plain SQL files:
```sh
npx ghuri sqlmigrate --all --out migrations-sql
npx wrangler d1 migrations apply DB --remote
```
and point `migrations_dir` in `wrangler.jsonc` at that directory. `sqlmigrate --all` writes one numbered file per migration in dependency order (`0001_blog_0001_initial.sql`, …), using the SQLite dialect unless you pass `--dialect`. Each file also inserts its own `ghuri_migrations` row, so `ghuri showmigrations` agrees with what Wrangler applied. Re-running it only adds files for new migrations; existing numbers never change. Still, pick one way of applying migrations per database: Wrangler records applied files in its own table and does not read `ghuri_migrations`.
On Node with Postgres, run `npx ghuri migrate` as a release step before starting the new version. See [Node and Postgres](https://ghurijs.github.io/docs/deployment/node-postgres/). With several databases configured, migrate each one: `npx ghuri migrate --database pg`.
## Existing databases: `--fake` and `--fake-initial`
`migrate --fake` records migrations as applied without running them, for when the schema already matches. `migrate --fake-initial` fakes only initial migrations whose tables already exist, which is handy when adopting migrations on an existing database. `migrate --plan` shows what would run without running it, and `--run-syncdb` creates tables for apps that have no migrations.
## Rolling back
`migrate` with an app and a migration name migrates to that state, unapplying later migrations:
```sh
npx ghuri migrate blog 0002 # unapply 0003 and later
npx ghuri migrate blog zero # unapply everything in blog
```
Operations generated by `makemigrations` are reversible. `RunSQL` needs a `reverse` and `RunCode` needs a backwards function to be reversible; otherwise rolling back past them raises `IrreversibleError`.
## Working in a team
* Commit migrations with the model changes that produced them.
* If two branches both add a migration to the same app, `migrate` and `makemigrations` report conflicting leaf nodes. Run `npx ghuri makemigrations --merge` to generate a merge migration that depends on both leaves, as in Django.
* Run `npx ghuri makemigrations --check` in CI to fail when someone changed models without generating a migration.
* Never edit a migration that has been applied somewhere you do not control. Write a new one.
## Programmatic API
`@ghuri/orm/migrations` is Workers-safe (no file system access), so you can migrate from code, for example in a scheduled job or a test:
```ts
import { makeMigrations, migrate, showMigrations, sqlMigrate } from '@ghuri/orm/migrations'
await migrate({ using: 'default' })
await migrate({ appLabel: 'blog', target: 'zero' })
const statements = await sqlMigrate('blog', '0002', { dialect: 'postgresql' }) // string[]
const status = await showMigrations() // [{ app, name, applied, dependencies }]
await makeMigrations({ dryRun: true }) // writing files needs @ghuri/orm/commands (Node)
```
The same entry point exports the building blocks: `Migration`, `operations`, `ProjectState` / `StateApps`, `MigrationLoader`, `MigrationGraph`, `MigrationExecutor`, `MigrationRecorder`, `MigrationAutodetector`, `MigrationWriter`, `sqlMigrateAll`, the schema editors, and the data helpers `dumpData`, `loadData`, `flushDatabase` and `copyData`. `@ghuri/orm/commands` (Node only) exports the command classes, `registerOrmCommands()`, which adds them to core’s command registry, and `setMigrationImporter()`, which replaces how migration files are imported from disk.
# Transactions
> atomic(), savepoints, and what transactions mean on D1, SQLite and Postgres.
Ghuri runs in autocommit mode by default: each query is committed immediately. To make a group of writes all-or-nothing on Postgres and SQLite, wrap them in `atomic()`. On D1, `atomic()` cannot roll back; use [`connection.batch()`](#d1) instead.
```ts
import { atomic, F } from '@ghuri/orm'
await atomic(async () => {
const order = await Order.objects.create({ customer: user, total: '49.00' })
await OrderLine.objects.bulkCreate(lines.map((l) => new OrderLine({ ...l, order })))
await Product.objects.filter({ id__in: lines.map((l) => l.productId) })
.update({ stock: F('stock').sub(1) })
})
```
If the callback throws, everything inside it is rolled back (except on D1) and the error propagates. If it returns, the transaction commits and `atomic()` resolves to the callback’s return value.
Nested `atomic()` calls create savepoints, so an inner block can fail and roll back without aborting the outer one:
```ts
await atomic(async () => {
await post.save()
try {
await atomic(async () => {
await notifySubscribers(post) // may throw
})
} catch {
// the post is still saved; only the inner block was rolled back
}
})
```
Use a different database alias with `atomic(fn, { using: 'analytics' })`. Pass `{ savepoint: false }` to make a nested block join the outer transaction without a savepoint.
If you know Django
`atomic()` is `transaction.atomic`, used as a function wrapper instead of a `with` block or decorator. The request context plays the role of Django’s thread-local connection: queries made anywhere inside the callback (in other functions, in signal receivers) join the transaction automatically. There is no `ATOMIC_REQUESTS` setting; wrap the view body when you need it.
## Behaviour by database
Transactions depend on what the database underneath supports. Each connection reports it as `connection.supportsTransactions` (and `connection.features.supportsSavepoints`).
| Database | `atomic()` | Savepoints |
| ---------------------------------------------------------- | ------------------------------------------ | ---------- |
| Postgres (`postgres()`, Hyperdrive) | real `BEGIN` / `COMMIT` / `ROLLBACK` | yes |
| SQLite (`@ghuri/orm/sqlite`), PGlite (`@ghuri/orm/pglite`) | real transactions | yes |
| D1 (`d1()`) | **no transaction, no rollback**, see below | no |
`connections.inAtomicBlock(alias)` tells you whether code is running inside `atomic()`.
### D1
`atomic()` does not roll back on D1
D1 has no interactive transactions: a Worker cannot hold a transaction open across several round trips. On D1, `atomic()` simply runs the callback. Every statement is committed as soon as it runs, and **nothing is rolled back if the callback throws**. The only thing `atomic()` still does on D1 is defer `onCommit()` callbacks until the callback returns successfully.
This also applies to everything the ORM wraps in `atomic()` internally, such as cascading deletes (`qs.delete()`), `updateOrCreate()` and `getOrCreate()`.
What D1 does offer is a **batch**: a list of statements that D1 executes atomically, all or nothing. Use `connection.batch()` when a group of writes must not be applied partially:
```ts
import { connections } from '@ghuri/orm'
const conn = await connections.get()
await conn.batch([
{ sql: 'UPDATE shop_product SET stock = stock - ? WHERE id = ? AND stock >= ?', params: [1, productId, 1] },
{ sql: 'INSERT INTO shop_orderline (order_id, product_id, quantity) VALUES (?, ?, ?)', params: [orderId, productId, 1] },
])
```
A batch cannot read in between statements (each statement’s parameters are fixed when you build it), and it takes raw SQL, so its statements are dialect-specific. On the other backends `batch()` runs the statements in a transaction, so the same call is all-or-nothing everywhere. Migrations (one batch per migration) and `loaddata` (one batch per 5,000 statements) use batches on D1 for the same reason.
Design write paths on D1 accordingly:
* Prefer single statements that do the whole job: `qs.update()` with `F()` expressions, or `bulkCreate()`.
* Group writes that must succeed together into one `connection.batch()`.
* Make multi-step operations idempotent, so a retry after a failure converges.
* When you need strict multi-statement atomicity with reads in between, that is a strong signal to [move to Postgres](https://ghurijs.github.io/docs/deployment/d1-to-postgres/), possibly through Hyperdrive while staying on Workers.
## Running code after commit
Sending an email or enqueueing a job should happen only if the transaction commits. Use `onCommit()`:
```ts
import { atomic, onCommit } from '@ghuri/orm'
await atomic(async () => {
const user = await User.objects.create({ ... })
await onCommit(() => sendWelcomeEmail(user))
})
```
Callbacks run in order after the outermost `atomic()` block commits, and are dropped if the block (or the savepoint that registered them) rolls back. Outside a transaction the callback runs immediately, which is why `onCommit()` returns a promise you should await. Pass `{ using: 'analytics' }` for another alias. On Workers, if the callback returns a promise that should outlive the response, pass it to `getContext().executionCtx?.waitUntil()`.
# The admin
> Register models with the Ghuri admin, customise change lists and forms, write actions, control permissions and build custom admin sites.
`@ghuri/admin` is a port of Django’s admin: a staff-only interface, generated from your models, for trusted users to create, read, update and delete data. Pages are rendered on the server with Hono JSX and progressively enhanced with a little JavaScript and htmx. One embedded stylesheet provides a Django-admin look with light and dark themes. Users run no build step, and the admin works the same on Workers (D1, R2) and Node (Postgres, SQLite).
This page is a tour. Every option, filter class, action and inline setting is listed in the [Admin reference](https://ghurijs.github.io/docs/topics/admin-reference/).
## Setting it up
The project template already does all three steps:
1. `AdminConfig` (from `@ghuri/admin`, app label `admin`) is in `INSTALLED_APPS`, after `ContentTypesConfig`, `AuthConfig` and `SessionsConfig` from `@ghuri/auth`. The admin checks at startup that `contenttypes` and `auth` are installed. `SessionMiddleware` and `AuthenticationMiddleware` must be in `MIDDLEWARE`, because the admin logs users in with sessions and stores flash messages there.
2. `path('admin/', admin.site.urls)` is in the root `urls.ts`.
3. Each app’s `AppConfig` imports its `admin.ts` module (`admin = admin`). Importing that module runs its registrations.
src/settings.ts
```ts
import { AdminConfig } from '@ghuri/admin'
import {
AuthConfig, AuthenticationMiddleware, ContentTypesConfig, SessionMiddleware, SessionsConfig,
} from '@ghuri/auth'
import { CommonMiddleware, CsrfMiddleware, defineSettings, SecurityMiddleware } from '@ghuri/core'
export default defineSettings((env) => ({
// ...
INSTALLED_APPS: [ContentTypesConfig, AuthConfig, SessionsConfig, AdminConfig, BlogConfig],
MIDDLEWARE: [SecurityMiddleware, SessionMiddleware, CommonMiddleware, CsrfMiddleware, AuthenticationMiddleware],
}))
```
src/urls.ts
```ts
import { path } from '@ghuri/core'
import { admin } from '@ghuri/admin'
export const urlpatterns = [
path('admin/', admin.site.urls),
]
```
src/blog/app.ts
```ts
import { AppConfig } from '@ghuri/core'
import * as admin from './admin'
import * as models from './models'
export class BlogConfig extends AppConfig {
name = 'blog'
models = models
admin = admin
}
```
Then run `npx ghuri migrate` (the admin ships the migration for its `LogEntry` model, table `django_admin_log`) and create a user who can log in with `npx ghuri createsuperuser`.
If you know Django
Django finds `admin.py` through `autodiscover()`. Ghuri has no filesystem to scan, so each app imports its admin module from `app.ts` instead. Everything after that is the same: `admin.site.register()`, `@admin.register()`, `ModelAdmin`, inlines, actions and `AdminSite`. The `admin` export mirrors `django.contrib.admin` (`admin.site`, `admin.register`, `admin.ModelAdmin`, `admin.TabularInline`, `admin.display`, `admin.action`, `admin.SimpleListFilter` and so on), and everything is also a named export.
## Registering models
The shortest registration uses the defaults:
src/blog/admin.ts
```ts
import { admin } from '@ghuri/admin'
import { Tag } from './models'
admin.site.register(Tag)
```
To customise, pass a `ModelAdmin` subclass, either as the second argument or with the decorator:
src/blog/admin.ts
```ts
import { admin, ModelAdmin } from '@ghuri/admin'
import { Post, Tag } from './models'
class TagAdmin extends ModelAdmin {
searchFields = ['name']
}
admin.site.register(Tag, TagAdmin)
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
listDisplay = ['title', 'author', 'published', 'createdAt']
}
```
`@admin.register()` works with standard (TC39) decorators and with `experimentalDecorators`. Without decorators, call it: `admin.register(Post)(PostAdmin)`. `admin.site.register([A, B], SomeAdmin)` registers several models with one class.
`admin.site.unregister(Model)` removes a registration and `admin.site.isRegistered(Model)` checks for one. Registering a model twice throws `AlreadyRegistered`; unregistering an unknown model throws `NotRegistered`. Use `unregister` to replace an admin registered by another app, such as the built-in `UserAdmin`.
## Change list options
These options control the list of objects at `/admin///`. The most common ones:
| Option | Meaning |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `listDisplay` | Columns: field names, `__`-paths such as `'author__username'`, names of methods on the `ModelAdmin` or the model, or functions. Default: `['__str__']` |
| `listDisplayLinks` | Which columns link to the change form. Default: the first; `null` for none |
| `listFilter` | Filters in the sidebar: field names, `SimpleListFilter` subclasses, or `['field', FilterClass]` |
| `searchFields` | Fields searched by the search box. `'title'` is `icontains`, `'^slug'` `istartswith`, `'=email'` `iexact`. Words are ANDed, fields ORed |
| `dateHierarchy` | A date or datetime field that gets year → month → day drill-down links above the list |
| `ordering` | Default ordering, e.g. `['-createdAt']`. Falls back to the model’s `Meta.ordering` |
| `listPerPage` | Page size. Default `100` |
| `listSelectRelated` | `true`, a list of fields to `selectRelated()`, or `false` |
| `listEditable` | Fields edited in place on the change list |
A column can be a method that returns a computed value. It may be async. Use `display()` to set its header, make it sortable or render it as a yes/no icon:
src/blog/admin.ts
```ts
import { admin, display, ModelAdmin } from '@ghuri/admin'
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
listDisplay = ['title', 'author', 'published', 'commentCount', 'isRecent']
listSelectRelated = ['author']
@display({ description: 'Comments' })
async commentCount(post: Post) {
return post.comments.count()
}
@display({ description: 'Recent?', boolean: true, ordering: '-createdAt' })
isRecent(post: Post) {
return post.createdAt > lastWeek()
}
}
```
Columns that map to a database field are sortable, and so are method columns with `display({ ordering })`. Sorting uses Django’s `?o=` parameter, with multi-column sort priority. Values are escaped; return JSX (or `html` from `hono/html`) to render markup.
## Change form options
These options control the add and change forms.
| Option | Meaning |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `fields` | Fields to show, in order. Nest an array to put fields on one line: `['title', ['slug', 'status']]` |
| `fieldsets` | Grouped fields: `[[title \| null, { fields, classes?, description? }], ...]`. `classes: ['collapse']` makes a group collapsible |
| `readonlyFields` | Shown as text, never written. `autoNow`/`autoNowAdd` and non-`editable` fields are always read-only |
| `prepopulatedFields` | `{ slug: ['title'] }` fills a field from others as the user types |
| `rawIdFields` | Foreign keys and many-to-many fields shown as an id input with a lookup link instead of a select. Use for large tables |
| `autocompleteFields` | Foreign keys and many-to-many fields shown as a search-as-you-type select. The related model’s admin must define `searchFields` |
| `filterHorizontal` / `filterVertical` | Many-to-many fields as a filterable multi-select |
| `radioFields` | `{ status: admin.HORIZONTAL }` shows choices or a foreign key as radio buttons |
| `inlines` | Related objects edited on the same page (see below) |
Each widget comes from the model field’s `formHint()`: a `TextField` becomes a textarea, a `BooleanField` a checkbox, a field with `choices` a select, a `DateTimeField` a `datetime-local` input (in UTC), and so on. Validation runs `fullClean()` on the instance, so field validators, `unique` and your model’s own `clean()` show their errors next to the right field. Add form-wide checks by overriding `cleanForm(c, form)`.
The form has the usual buttons: **Save**, **Save and add another** and **Save and continue editing**, plus **Save as new** with `saveAs = true`.
src/blog/admin.ts
```ts
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
prepopulatedFields = { slug: ['title'] }
readonlyFields = ['createdAt', 'updatedAt']
autocompleteFields = ['tags']
rawIdFields = ['author']
fieldsets = [
[null, { fields: ['title', 'slug', 'summary', 'body'] }],
['Publishing', { fields: ['author', 'tags', 'published', 'createdAt', 'updatedAt'], classes: ['collapse'] }],
]
}
```
Note
There are no “+” related-object popups next to foreign-key and many-to-many widgets. To add a related object, open its own add form (in another tab), then come back and pick it. `rawIdFields` shows a lookup link to the related change list rather than a popup window.
## Inlines
Inlines edit related objects on the parent’s change form. `TabularInline` puts each object on a row of a table. `StackedInline` gives each object a full form.
src/blog/admin.ts
```ts
import { admin, ModelAdmin, StackedInline, TabularInline } from '@ghuri/admin'
class CommentInline extends TabularInline {
model = Comment
fields = ['author', 'body', 'approved']
extra = 1 // empty forms shown (default 3)
maxNum = 50
canDelete = true
}
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
inlines = [CommentInline]
}
```
An inline finds its foreign key to the parent automatically. Set `fkName` when the child has more than one foreign key to the parent model. Without JavaScript the `extra` rows are shown; with it an “Add another” link clones rows.
## Actions
Actions run on the rows selected in the change list. Every model gets **Delete selected** (`delete_selected`). It shows a confirmation page that lists everything the delete will cascade to, refuses when objects are protected or the user lacks delete permission on them, then deletes the rows. Add your own with `action()`:
src/blog/admin.ts
```ts
import { action, admin, ModelAdmin } from '@ghuri/admin'
import { Post } from './models'
export const makePublished = action(
{ description: 'Mark selected posts as published', permissions: ['change'] },
async (modelAdmin, c, queryset) => {
const count = await queryset.update({ published: true })
await modelAdmin.messageUser(c, `${count} posts marked as published.`, 'success')
},
)
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
actions = [makePublished]
}
```
An action function receives the `ModelAdmin`, the Hono context and a QuerySet of the selected objects. It can return nothing, which sends the user back to the list, or a `Response`, for example a CSV download or an intermediate confirmation page. `description` is the label in the actions menu; `permissions` limits who is offered the action. Actions can also be `ModelAdmin` methods (decorated with `@action`), and “Select all N” across pages is supported. The details are in the [Admin reference](https://ghurijs.github.io/docs/topics/admin-reference/#actions).
## Permissions
Only users with `isStaff` and `isActive` can log in. After that, each model admin asks four hooks what the user may do. The defaults check the auth permissions that `migrate` creates for every model, and active superusers pass every check:
| Hook | Default |
| ------------------------------ | -------------------------------------- |
| `hasViewPermission(c, obj?)` | `blog.view_post` or `blog.change_post` |
| `hasAddPermission(c, obj?)` | `blog.add_post` |
| `hasChangePermission(c, obj?)` | `blog.change_post` |
| `hasDeletePermission(c, obj?)` | `blog.delete_post` |
| `hasModulePermission(c)` | `user.hasModulePerms('blog')` |
Users with only the view permission get read-only change forms. Override the hooks for row-level rules. They are async, and `obj` is undefined when the question is about the model as a whole. `getQueryset()` must return the QuerySet synchronously (QuerySets are thenable, so an `async` method would resolve it to an array):
src/blog/admin.ts
```ts
import type { Context } from 'hono'
import { getUser } from '@ghuri/core'
@admin.register(Post)
export class PostAdmin extends ModelAdmin {
getQueryset(c: Context) {
const user = getUser(c)
const qs = super.getQueryset(c)
return user.isSuperuser ? qs : qs.filter({ author: user.pk })
}
async hasDeletePermission(c: Context, obj?: Post) {
return getUser(c).isSuperuser ?? false
}
}
```
The app index and the main index list only the models a user can at least view.
## Auth models and history
When `@ghuri/auth` is installed, the admin registers `User` with `UserAdmin` and `Group` with `GroupAdmin`. `UserAdmin` asks for the password twice on the add form (password validators apply), stores a hash, shows the hash summary on the change form and links to a password change form, so a raw password is never stored. To customise it, unregister it and register your subclass:
src/accounts/admin.ts
```ts
import { admin, UserAdmin } from '@ghuri/admin'
import { User } from '@ghuri/auth'
admin.site.unregister(User)
@admin.register(User)
export class CustomUserAdmin extends UserAdmin {
listDisplay = ['username', 'email', 'isStaff', 'dateJoined']
}
```
With a swapped `AUTH_USER_MODEL`, `UserAdmin` is not registered automatically; register your own (for example `admin.site.register(Account, AccountAdmin)`).
Every add, change and delete done through the admin is written to the `LogEntry` model, with a Django-compatible JSON change message. The **History** link on each change form shows those entries, and the admin index shows the current user’s recent actions.
## File uploads
`FileField` and `ImageField` from [`@ghuri/storage`](https://ghurijs.github.io/docs/topics/file-storage/) render as file inputs with the current file’s link, a “Clear” checkbox and a “Change” input; the form is sent as multipart. The upload is assigned to the model and the field’s storage uploads it on save. “Clear” empties the field but keeps the stored file, as in Django. `@ghuri/storage` is optional: the admin detects file fields by their form hint.
## Custom admin sites
`admin.site` is the default `AdminSite`. Change its branding by setting its properties, for example in an `AppConfig.ready()`:
```ts
admin.site.siteHeader = 'Mysite administration'
admin.site.siteTitle = 'Mysite admin'
admin.site.indexTitle = 'Dashboard'
```
For a second, separate admin (say, a limited one for editors), create another site:
src/editors/admin.ts
```ts
import { AdminSite, ModelAdmin } from '@ghuri/admin'
import { Post } from '../blog/models'
export const editorSite = new AdminSite({ name: 'editors', siteHeader: 'Editorial desk' })
editorSite.register(Post, class extends ModelAdmin {
listDisplay = ['title', 'published']
})
```
src/urls.ts
```ts
path('editors/', editorSite.urls), // reverse('editors:index')
```
Override `hasPermission(c)` on an `AdminSite` subclass to change who may enter at all. Custom admin pages (via `getUrls()` and `adminSite.adminView()`) are covered in the [Admin reference](https://ghurijs.github.io/docs/topics/admin-reference/#custom-admin-views).
## Assets and security
The admin loads htmx (used by autocomplete) from jsDelivr by default. To serve it yourself (behind a strict Content Security Policy, say), disable it, or add your own stylesheets and scripts, use `ADMIN_ASSETS`:
src/settings.ts
```ts
ADMIN_ASSETS: { htmx: '/static/htmx.min.js', css: ['/static/admin-brand.css'] }, // htmx: false disables it
```
Every core flow (login, lists, filters, search, sorting, pagination, actions, forms, inline `extra` rows and deletes) works without JavaScript.
The admin checks the CSRF token on every POST itself, even without `CsrfMiddleware`, though keeping the middleware is recommended. Set `CSRF_TRUSTED_ORIGINS` when the admin is served from a domain other than the one in the request’s `Host` header. Redirects after login are restricted to the same host, all output is escaped by Hono JSX, and responses are sent with `Cache-Control: private, no-store`.
Customising markup
The admin’s pages are JSX components, not overridable template files: there is no equivalent of overriding `change_form.html`. Customise through options, hooks, extra CSS in `ADMIN_ASSETS` and custom admin views.
# Admin reference
> Every ModelAdmin option, the built-in and custom list filters, actions and their permissions, inline options, hooks, URL names and AdminSite customisation in @ghuri/admin.
Reference for `@ghuri/admin`. For setup and a guided tour, read [The admin](https://ghurijs.github.io/docs/topics/admin/) first. Options are class fields; Django’s `snake_case` names become `camelCase` (`list_display` is `listDisplay`). Hooks receive the Hono context `c` where Django passes `request`; use `getUser(c)` for `request.user`.
## ModelAdmin options
### Change list
| Option | Default | |
| ---------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `listDisplay` | `['__str__']` | Columns: field names, `'author__username'` paths, `ModelAdmin` method names, model method names, or functions |
| `listDisplayLinks` | first column | Columns linking to the change form; `null` for none |
| `listFilter` | `[]` | Field names (`'published'`, `'author__isStaff'`), `SimpleListFilter` subclasses, or `['field', FilterClass]`. See [List filters](#list-filters) |
| `listSelectRelated` | `false` | `true` (all foreign keys), field names, or `false` (the foreign keys shown in `listDisplay`) |
| `listPerPage` | `100` | Rows per page |
| `listMaxShowAll` | `200` | Largest result count for which “Show all” is offered |
| `listEditable` | `[]` | Fields edited in place on the change list, saved with one “Save” button |
| `searchFields` | `[]` | `'title'` (icontains), `'^slug'` (istartswith), `'=email'` (iexact), `'@body'` (treated as icontains), `'author__username'`. Words are ANDed, fields ORed; `"quoted phrases"` stay together |
| `searchHelpText` | `null` | Text under the search box |
| `dateHierarchy` | `null` | A date or datetime field: year → month → day drill-down links |
| `ordering` | the model’s `Meta.ordering` | Default ordering; the pk is appended for a stable order |
| `sortableBy` | all columns | Restrict sortable columns |
| `showFullResultCount` | `true` | Show “N results (M total)” when filtered; `false` saves a `COUNT` query |
| `actions` | `[]` | Extra actions, added to the site-wide `delete_selected`; `null` disables actions. See [Actions](#actions) |
| `actionsOnTop` / `actionsOnBottom` | `true` / `false` | Where the action bar is shown |
| `actionsSelectionCounter` | `true` | Show “N of M selected” |
| `emptyValueDisplay` | the site’s `'-'` | Shown for empty values |
| `preserveFilters` | `true` | Keep the change list filters across add, change and delete |
Sorting uses Django’s `?o=` parameter (`?o=2.-1` sorts by column 2 ascending, then column 1 descending); column headers show the sort priority with toggle and remove links.
```ts
class PostAdmin extends ModelAdmin {
listDisplay = ['title', 'author', 'status', 'wordCount']
listDisplayLinks = ['title']
listFilter = ['status', 'author', 'createdAt', DecadeFilter, ['category', RelatedOnlyFieldListFilter]]
listSelectRelated = ['author']
searchFields = ['^title', 'body', 'author__username']
dateHierarchy = 'createdAt'
ordering = ['-createdAt']
listPerPage = 50
listEditable = ['status']
}
```
### Forms
| Option | Default | |
| ------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `fields` | all editable fields | Field names; nest an array to put fields on one line: `['title', ['slug', 'status']]` |
| `exclude` | `null` | Fields left off the form |
| `fieldsets` | one unnamed fieldset | `[[name \| null, { fields, classes?, description? }], ...]`. `classes: ['collapse']` renders a ``, `['wide']` widens labels |
| `readonlyFields` | `[]` | Field names, method names or functions, shown as text. Non-editable fields (`autoNowAdd`, …) are always read-only |
| `prepopulatedFields` | `{}` | `{ slug: ['title'] }`: slugified as you type (JavaScript), on new and empty fields |
| `rawIdFields` | `[]` | Foreign key or many-to-many as an id input with a lookup link (comma-separated ids for many-to-many) |
| `autocompleteFields` | `[]` | Foreign key or many-to-many with search-as-you-type (htmx). The related model’s admin needs `searchFields` |
| `filterHorizontal` / `filterVertical` | `[]` | Many-to-many as a filterable multi-select |
| `radioFields` | `{}` | `{ status: HORIZONTAL }`: choices or a foreign key as radio buttons (`HORIZONTAL` / `VERTICAL`) |
| `formfieldOverrides` | `{}` | Per model field type, keyed by `internalType`: `{ TextField: { widget: 'text', attrs: { size: 80 } } }` |
| `saveAs` | `false` | Show “Save as new” |
| `saveAsContinue` | `true` | After “Save as new”, continue editing the new object |
| `saveOnTop` | `false` | Show the save buttons above the form too |
| `viewOnSite` | `true` | “View on site” uses `obj.getAbsoluteUrl()`; or a function `(obj) => url`, or `false` |
| `inlines` | `[]` | Inline classes. See [Inlines](#inlines) |
```ts
class PostAdmin extends ModelAdmin {
fieldsets = [
[null, { fields: ['title', 'slug', 'body'] }],
['Publishing', {
fields: [['published', 'publishedAt'], 'author', 'tags'],
classes: ['collapse'],
description: 'Visible on the site once published.',
}],
]
readonlyFields = ['createdAt', 'wordCount']
prepopulatedFields = { slug: ['title'] }
autocompleteFields = ['author']
filterHorizontal = ['tags']
radioFields = { status: admin.VERTICAL }
saveAs = true
}
```
### Widgets
Forms are built from each model field’s `formHint()`, converted with `field.toPython()` and validated with the model’s `fullClean()` (null, blank, choices, validators, `clean()`, foreign-key existence and uniqueness). Non-field errors appear above the form.
| Model field | Widget |
| ------------------------------------------- | ------------------------------------------------------------------- |
| `CharField`, `SlugField`, `UUIDField`, … | `` with `maxlength` |
| `TextField` | `