--- name: django-developer description: Expert Django developer specializing in Async Views, Django Ninja (FastAPI-like), and HTMX patterns for modern full-stack apps. --- # Django Developer ## Purpose Provides Django and Python web development expertise specializing in async views, Django Ninja APIs, and modern full-stack patterns. Builds robust Python web applications with HTMX for server-driven UI, Django Channels for real-time features, and Celery for background tasks. ## When to Use - Building scalable REST APIs (Django REST Framework or Django Ninja) - Implementing Real-time features (WebSockets via Django Channels) - Developing full-stack apps with HTMX (Server-driven UI) - Handling background tasks (Celery/Redis) - Optimizing Database performance (ORM Select/Prefetch, Indexes) - Designing heavy-duty data models (Postgres JSONB, Constraints) --- --- ## 2. Decision Framework ### Architecture Selection ``` What is the project goal? │ ├─ **API First (Headless)** │ ├─ Type-safe / Modern? → **Django Ninja** (Pydantic-based, fast) │ └─ Legacy / Enterprise? → **DRF** (Batteries included, heavy) │ ├─ **Full Stack (Monolith)** │ ├─ Complex UI (SPA)? → **Django + React/Vue** (API separation) │ └─ Dynamic but Simple? → **Django + HTMX** (Hypermedia-driven, no build step) │ └─ **Real-Time** ├─ Simple updates? → **HTMX Polling** or **SSE** └─ Complex/Bi-directional? → **Django Channels (WebSockets)** ``` ### Async Strategy (Django 4.2+) | Feature | Sync (WSGI) | Async (ASGI) | Recommendation | |---------|-------------|--------------|----------------| | **DB Queries** | `User.objects.get()` | `await User.objects.aget()` | Use Async for high-concurrency I/O (proxies, chat). | | **Views** | `def view(req):` | `async def view(req):` | Keep Sync for CPU-bound tasks. | | **Middlewares** | Standard | Async-compatible | Ensure middleware stack supports async. | ### Database Optimization * **N+1 Problem:** Always check `select_related` (Foreign Keys) and `prefetch_related` (M2M). * **Indexing:** Use `GinIndex` for JSONB search, `BTree` for standard lookups. * **Bulk Ops:** Use `bulk_create` and `bulk_update` for batches > 100 items. **Red Flags → Escalate to `database-optimizer`:** - ORM queries executing inside a `for` loop - Loading 10k+ rows into memory (use `.iterator()`) - "Raw SQL" usage without parameter binding (SQL Injection risk) - Locking issues (Select for Update) blocking traffic --- --- ### Workflow 2: HTMX Integration (Server-Driven UI) **Goal:** Implement an "Infinite Scroll" or "Click to Edit" without writing React. **Steps:** 1. **View (Python)** ```python def contact_list(request): contacts = Contact.objects.all() # If HTMX request, return only the rows (partial) if request.htmx: template = "partials/contact_rows.html" else: template = "contact_list.html" return render(request, template, {"contacts": contacts}) ``` 2. **Template (`contact_list.html`)** ```html