Skip to content
/ fastdjango Public template

Finally, a FastAPI template with Django that works. IoC container, per-test isolation, and many delivery channels from one codebase 🎯

License

Notifications You must be signed in to change notification settings

MaksimZayats/fastdjango

Repository files navigation

Fast Django

Production-ready FastAPI template with Django ORM, admin panel, and Celery background tasks β€” featuring dependency injection, type-safe configuration, and comprehensive observability.

Features

  • HTTP API β€” FastAPI with automatic OpenAPI documentation
  • Background Tasks β€” Celery with beat scheduler
  • Dependency Injection β€” punq IoC container
  • Type-Safe Config β€” Pydantic Settings with validation
  • Observability β€” Logfire (OpenTelemetry) integration
  • Production Ready β€” Docker Compose with PostgreSQL, PgBouncer, Redis, MinIO

At a Glance

Define a service with business logic and database operations:

# src/core/todo/services.py
from django.db import transaction
from core.todo.models import Todo

class TodoService:
    def get_todo_by_id(self, todo_id: int) -> Todo | None:
        return Todo.objects.filter(id=todo_id).first()

    def list_todos(self, user_id: int) -> list[Todo]:
        return list(Todo.objects.filter(user_id=user_id))

    @transaction.atomic
    def create_todo(self, user_id: int, title: str) -> Todo:
        return Todo.objects.create(user_id=user_id, title=title)

Create a controller β€” services are auto-injected via the IoC container:

# src/delivery/http/todo/controllers.py
from dataclasses import dataclass
from fastapi import APIRouter, Depends
from pydantic import BaseModel

from core.todo.services import TodoService
from delivery.http.auth.jwt import AuthenticatedRequest, JWTAuth, JWTAuthFactory
from infrastructure.delivery.controllers import Controller

class TodoSchema(BaseModel):
    id: int
    title: str
    completed: bool

@dataclass
class TodoController(Controller):
    _jwt_auth_factory: JWTAuthFactory
    _todo_service: TodoService  # Auto-injected

    def register(self, registry: APIRouter) -> None:
        registry.add_api_route(
            path="/v1/todos",
            endpoint=self.list_todos,
            methods=["GET"],
            dependencies=[Depends(self._jwt_auth_factory())],
        )

    def list_todos(self, request: AuthenticatedRequest) -> list[TodoSchema]:
        todos = self._todo_service.list_todos(user_id=request.state.user.id)
        return [TodoSchema.model_validate(t, from_attributes=True) for t in todos]

The Golden Rule: Controllers never access models directly β†’ all database operations go through services.

Prerequisites

Before getting started, ensure you have installed:

  • uv β€” Blazingly fast Python package manager (Install uv)
  • Docker & Docker Compose β€” For infrastructure services (Install Docker)

Quick Start

1. Clone the Repository

git clone https://github.com/MaksimZayats/fastdjango.git
cd fastdjango

2. Rename the Project

Replace the default project name in pyproject.toml with your own. Use lowercase letters, numbers, and hyphens (e.g., my-awesome-api, backend-service).

3. Install Dependencies

uv sync --locked --all-extras --dev

4. Configure Environment

cp .env.example .env

The .env.example contains sensible defaults for local development. Key variables:

  • DJANGO_SECRET_KEY β€” Django secret key
  • JWT_SECRET_KEY β€” JWT signing key
  • DATABASE_URL β€” PostgreSQL connection string
  • REDIS_URL β€” Redis connection string

5. Start Infrastructure Services

docker compose up -d postgres redis minio

This starts:

  • PostgreSQL 18 β€” Primary database
  • PgBouncer β€” Connection pooling (transaction mode)
  • Redis β€” Cache and Celery broker
  • MinIO β€” S3-compatible object storage

6. Initialize Database and Storage

docker compose up minio-create-buckets migrations collectstatic

This runs one-time setup tasks:

  1. Creates MinIO buckets for static/media files
  2. Applies Django database migrations
  3. Collects static files to MinIO

7. Start Development Server

make dev

The API is available at http://localhost:8000 with interactive docs at /api/docs.

Verify Installation

curl http://localhost:8000/api/v1/health

Expected response:

{
  "status": "ok"
}

Documentation

Full documentation is available at template.zayats.dev.

Section Description
Quick Start Get running in 5 minutes
Project Structure Understand the codebase organization
Development Environment IDE setup and tooling
Tutorial: Build a Todo List Learn by building a complete feature
Concepts Service layer, IoC, controllers, factories
How-To Guides Add domains, tasks, secure endpoints
Reference Environment variables, Makefile, Docker

Tech Stack

Component Technology Documentation
HTTP API FastAPI 0.128+ fastapi.tiangolo.com
ORM & Admin Django 6+ docs.djangoproject.com
Task Queue Celery 5.x docs.celeryq.dev
Validation Pydantic 2.x docs.pydantic.dev
Settings Pydantic Settings docs.pydantic.dev/settings
IoC Container punq github.com/bobthemighty/punq
Observability Logfire Logfire docs
Package Manager uv docs.astral.sh/uv

License

MIT

About

Finally, a FastAPI template with Django that works. IoC container, per-test isolation, and many delivery channels from one codebase 🎯

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •