Skip to content

HyperDjango Documentation

Hypermodern web framework with native Zig performance. Django-inspired ergonomics, compiled HTTP server, SIMD validation, native PostgreSQL driver. Free-threaded Python 3.14t.

15,000+ tests. 16 example apps. 150 configurable settings. Zero external runtime dependencies.

Quick Start

uv add hyperdjango
uv run hyper-build --release
uv run hyper new myapp --full
cd myapp && uv run hyper run
from hyperdjango import HyperApp, Response

app = HyperApp("myapp", database="postgres://localhost/mydb")

@app.get("/")
async def index(request):
    return {"message": "Hello from HyperDjango!"}

@app.get("/articles/{id:int}")
async def article(request, id: int):
    article = await Article.objects.get(id=id)
    return Response.json(article.to_dict())

For the full walkthrough, see the Getting Started guide.


Learn

Start here if you're new to HyperDjango.

Doc What you'll learn
Architecture System diagram, request lifecycle, module dependency map
Getting Started Install, build, first app, models, views, templates, forms, admin, REST, deploy
Tutorial Step-by-step project from scratch
Patterns Standard coding patterns used across all 16 example apps

Models & Database

Define your data, query it, migrate it.

Doc What it covers
Models Model class, Field types, Meta options, inheritance (abstract/proxy/STI/unlogged), save/delete, to_dict
Models Guide Practical guide — defining models, relationships, FKs, composite PKs
Queries Guide filter, exclude, order_by, select_related, prefetch_related, annotate, aggregate
Expressions F, Q, Value, Count, Sum, Avg, Max, Min, Case/When, Subquery
Lookups 21 built-in lookups (including pgvector), 12 transforms
Custom Lookups Register your own lookup and transform types
Database pg.zig native driver, connection pool, prepared statements, COPY protocol
Transactions atomic(), savepoints, on_commit()
Migrations Introspect, diff, migrate, rollback, verify, snapshot
Migrations Guide Practical migration workflows
Multi-Database ConnectionManager, DatabaseRouter, PrimaryReplicaRouter
PostgreSQL Extensions ArrayField, SearchVector/Query/Rank, trigrams, aggregates, ranges, indexes
Pool Optimization Connection pool tuning, SlowQueryLog, PoolHealthChecker, heartbeat
Query Cache Transparent query cache with FK dependency tracking
DB Instrumentation Query profiling, slow query detection
PostgreSQL PostgreSQL-specific features and types
Embeddings pgvector embeddings, HNSW indexes, cosine/L2/inner product

Views, Routing & Templates

Handle requests and render responses.

Doc What it covers
Request & Response Request (JSON/form/cookies/files/stream), Response (json/html/text/redirect/sse/file)
Routing URL routing, {param:type} syntax, radix trie
Views Function views, decorators, shortcuts
Views Guide Practical patterns for views
Class-Based Views ListView, DetailView, CreateView, UpdateView, DeleteView + auth mixins
Templates Zig-compiled Jinja2-compatible engine — filters, macros, extends, include
Templates Guide Practical template usage, custom filters, backend config
Middleware CORS, Security, RateLimit, Timing, CSRF, Compression, Version, Logging
Static Files StaticFilesFinder, ManifestStaticFilesStorage, collectstatic, content-hash filenames
Conditional Views ETag, Cache-Control, 304 Not Modified

REST API

Build production-grade APIs.

Doc What it covers
REST Framework ModelViewSet, APIRouter, pagination (4 styles), filters (3 backends), permissions, throttling, bulk ops, nested routers, ETag caching, @action
Serializers ModelSerializer, read/write shapes, nested, computed fields, validation
OpenAPI OpenAPI 3.1 auto-generation, Swagger UI, @api_input/@api_output decorators
Pagination PageNumber, LimitOffset, keyset CursorPagination, ServerCursorPagination

Auth & Security

Sessions, OAuth2, RBAC, API keys, CSRF, and access control.

Doc What it covers
Auth & RBAC SessionAuth, AuthMiddleware, User/SessionUser/AnonymousUser, hierarchical RBAC (CTE), object permissions, 5 rule types
Auth Guide Practical auth setup — custom backends, LDAP, SAML
Guard HyperGuard access control — Require.authenticated(), Require.has_perm(), Require.has_active_status(), WebSocket guards
Sessions Session stores, cookie configuration, session lifecycle
Signing TokenEngine — HMAC-signed tokens with key rotation, XOR obfuscation, SignedSessionMixin, SignedAPIKeyMixin
Security Security headers, audit log
Security Guide CSRF, CORS, headers, hardening checklist
CSRF CSRF protection — double-submit cookie, trusted origins
Content Security Policy CSP header configuration
Unified IDs Anti-enumeration IDs — 4 modes (raw/encoded/signed/random), HMAC key rotation, time-windowed, per-user
Public IDs Legacy PublicIDMixin reference

Forms

Validate user input with Django-style forms.

Doc What it covers
Forms Form, ModelForm, 12 field types, custom validators, error display
Forms Guide Practical form patterns — validation, cross-field clean, rendering
FormSets FormSets for multiple form instances

Admin

Auto-generate CRUD admin panels from your models.

Doc What it covers
Admin HyperAdmin — register models, list/search/filter/create/edit/delete, bulk actions, RBAC management UI
Admin Guide Customization — fieldsets, actions, inlines, themes

Real-Time & WebSocket

WebSocket, pub/sub, rooms, live queries, notifications.

Doc What it covers
Channels Channel, ChannelGroup, InMemoryChannelLayer, PgChannelLayer (LISTEN/NOTIFY), presence, history
Real-time Patterns Room (chat/moderation), NotificationManager, LiveQuery (model change subscriptions), ConnectionManager

Background Tasks

In-process task queue with priority, retry, scheduling, and dead letter queue.

Doc What it covers
Tasks @task decorator, .delay(), TaskPriority, retry with exponential backoff, TaskScheduler (cron), TaskGroup, DLQ

Uploads & Streaming

Three-mode file uploads — memory, disk spill, pass-through streaming.

Doc What it covers
File Uploads request.files(), request.stream(), UploadedFile API, settings
Files & Storage FileSystemStorage, MemoryStorage, pluggable backends
Custom Storage Build your own storage backend

Caching & Performance

Multiple caching layers and performance monitoring.

Doc What it covers
Cache LocMemCache (LRU) + DatabaseCache (PostgreSQL UNLOGGED), @cached decorator
Cache Adapters ConsistentHashRing (native Zig, 3x), StampedeProtection (XFetch), TwoTierCache (L1+L2)
Rate Limiting InMemory + PostgreSQL UNLOGGED, tiered limits, per-path/method/cost rules
Performance PerformanceMiddleware — query tracking, slow queries, N+1 detection, dashboard
Performance Guide Optimization workflows, profiling, benchmarks
Profiling Nanosecond profiler, @profile_handler, X-Profile header, flame graphs

Telemetry & Observability

Native metrics and distributed tracing.

Doc What it covers
Telemetry Tracer, Span, Counter/Gauge/Histogram, W3C traceparent, sampling, sinks, auto log correlation
Metrics Prometheus-compatible metrics export
Logging Production logging — loguru-compatible API, JSON/console/file sinks, rotation, color markup

Multi-Tenancy & Metering

SaaS features — tenant isolation, usage tracking, quotas.

Doc What it covers
Multi-Tenancy TenantMixin, TenantMiddleware, auto-scoped queries, tenant resolvers
Usage Metering MeterEngine, events, aggregates, quotas, alert hooks
Timeline StatusTimeline — temporal status tracking (ban/mute/lock/staff with time ranges, actor, history, auto-escalation)

Asset Versioning

Cache busting, HTMX mismatch detection, blue/green deployments.

Doc What it covers
Versioning AppVersion, VersionMiddleware, X-App-Version header, /version endpoint, /cache/bust, blue/green routing

Internationalization

Translation, locale-aware formatting, plural rules.

Doc What it covers
i18n gettext/ngettext, PO file parsing, 40+ language plural rules, LocaleMiddleware, URL prefixing
Formats Locale-aware date/time/number/currency formatting, template filters

Contrib Modules

Batteries-included modules for common web patterns.

Doc What it covers
Custom Fields 14 built-in types — MoneyField, EmailField, SlugField, URLField, ColorField, PhoneField, EncryptedField, etc.
Mixins TimestampMixin, SoftDeleteMixin, OwnershipMixin, VersionedMixin
Email EmailMessage — SMTP/console/memory backends, HTML+text
Messages Flash messages across redirects (session-based)
Signals Signal class — pre/post_save, pre/post_delete, 9 built-in
Redirects RedirectRegistry, O(1) lookup, prefix matching, open-redirect protection
Flatpages Simple CMS pages, auth-gated, template rendering
Sitemaps XML sitemap generation, 50K pagination, ETag caching
Syndication RSS/Atom feed generation, enclosures, podcast support
Humanize ordinal, intcomma, intword, naturaltime, filesizeformat
Fixtures dumpdata/loaddata, JSON, FK dependency sorting, natural keys, UPSERT
Search Full-text search integration
Async Async reference
Async Guide Async usage patterns

Production & Deployment

Ship to production with confidence.

Doc What it covers
Deployment Deployment reference
Deployment Guide Docker, systemd, nginx, env templates, health probes, checklist
Tuning All configurable tuning parameters — task queue, perf middleware, slow query, rate limit, hot reload
Error Reporting Error handling and reporting

Configuration & CLI

Settings, commands, diagnostics.

Doc What it covers
Settings 150 settings with validation — 4-tier resolution (Django → env → .env → defaults)
CLI Commands hyper CLI — new, run, start, stop, restart, status, routes, migrate, doctor, benchmark, systemd
System Checks @register, CheckMessage, run_checks, 5 built-in checks
Commands Custom management commands — @command decorator, typed args, CLI discovery

Testing

Test your application with built-in tools.

Doc What it covers
Testing TestClient, auth helpers, cookie persistence
Testing Guide Practical testing patterns, E2E testing, Hypothesis fuzz

Internals

For contributors and deep understanding.

Doc What it covers
Validation Native Zig validation engine (4,350 lines)
Server Zig HTTP server — 24-thread pool, radix trie router, graceful shutdown
Legacy Databases Working with existing databases (inspectdb)
API Reference Complete API reference

Performance

Component Metric vs Baseline
HTTP server 13K req/s 2.1x uvicorn
Route resolve 808ns Radix trie
SELECT by PK 21K ops/s 2.06x psycopg3
COPY import 536K rows/s 42.8x INSERT
JSON parse 94ns 6.1x stdlib
Template render 36us 1.7x Jinja2
Template compile 7.1us 234x Jinja2
Model validation 0.6us 4.3x Python
SQL cache lookup 520K qps 2x+ uncached