django
Django development patterns and conventions (2025). Auto-loads when working with Django models, views, URLs, forms, templates, management commands, or project structure. Includes async support and type hints.
What this skill does
# Django Development (2025)
## Project Structure
```
project_name/
├── config/ # Project config (rename from project_name/)
│ ├── settings/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── dev.py
│ │ └── prod.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py # Required for async
├── apps/
│ ├── __init__.py
│ └── core/ # Shared utilities, base models
├── templates/
├── static/
├── manage.py
├── pyproject.toml # Modern Python packaging
└── requirements/
├── base.txt
├── dev.txt
└── prod.txt
```
## Environment & Settings
```python
# config/settings/base.py
import environ
env = environ.Env(
DEBUG=(bool, False),
)
environ.Env.read_env()
SECRET_KEY = env("SECRET_KEY")
DEBUG = env("DEBUG")
DATABASES = {"default": env.db()}
```
```bash
# .env
SECRET_KEY=your-secret-key
DEBUG=True
DATABASE_URL=postgres://user:pass@localhost:5432/dbname
```
## Naming Conventions
| Component | Convention | Example |
|-----------|------------|---------|
| App | singular, lowercase | `blog`, `user_profile` |
| Model | singular PascalCase | `Article`, `UserProfile` |
| View (function) | `noun_action` | `article_detail` |
| View (class) | `NounActionView` | `ArticleDetailView` |
| URL name | `app:noun-action` | `blog:article-detail` |
| Template | `app/noun_action.html` | `blog/article_detail.html` |
## Models
```python
from django.db import models
from django.urls import reverse
class TimestampedModel(models.Model):
"""Abstract base for created/updated timestamps."""
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Article(TimestampedModel):
class Status(models.TextChoices):
DRAFT = "draft", "Draft"
PUBLISHED = "published", "Published"
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
"auth.User",
on_delete=models.CASCADE,
related_name="articles",
)
status = models.CharField(
max_length=20,
choices=Status.choices,
default=Status.DRAFT,
db_index=True,
)
class Meta:
ordering = ["-created_at"]
indexes = [
models.Index(fields=["status", "created_at"]),
]
def __str__(self) -> str:
return self.title
def get_absolute_url(self) -> str:
return reverse("blog:article-detail", kwargs={"slug": self.slug})
```
**Key patterns:**
- Use `TextChoices` / `IntegerChoices` for choices (not tuples)
- Type hints on methods
- Always set `related_name`, `db_index` on filtered fields
## Views
### Sync Views (Standard)
```python
from django.views.generic import ListView, DetailView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
class ArticleListView(ListView):
model = Article
template_name = "blog/article_list.html"
context_object_name = "articles"
paginate_by = 20
def get_queryset(self):
qs = super().get_queryset().select_related("author")
if q := self.request.GET.get("q"):
qs = qs.filter(Q(title__icontains=q) | Q(body__icontains=q))
return qs
```
### Async Views
Use async for I/O-bound operations (external APIs, file ops). Requires ASGI server.
```python
import httpx
from django.http import JsonResponse
from asgiref.sync import sync_to_async
async def weather_view(request):
"""Async view calling external API."""
city = request.GET.get("city", "London")
async with httpx.AsyncClient() as client:
response = await client.get(f"https://api.weather.com/{city}")
return JsonResponse(response.json())
async def article_list_async(request):
"""Async view with ORM (requires sync_to_async wrapper)."""
articles = await sync_to_async(list)(
Article.objects.select_related("author")[:20]
)
return JsonResponse({"articles": [a.title for a in articles]})
```
**When to use async views:**
- External HTTP calls → use `httpx` (async) not `requests`
- Multiple concurrent I/O operations
- High-concurrency endpoints
**Note:** Django ORM is not fully async. Wrap ORM calls with `sync_to_async()`.
## URLs
```python
# apps/blog/urls.py
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.ArticleListView.as_view(), name="article-list"),
path("<slug:slug>/", views.ArticleDetailView.as_view(), name="article-detail"),
]
# config/urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("blog/", include("apps.blog.urls")),
]
```
## Forms
```python
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ["title", "body", "status"]
widgets = {
"body": forms.Textarea(attrs={"rows": 10}),
}
def clean_title(self) -> str:
title = self.cleaned_data["title"]
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters.")
return title
```
## Templates
```
templates/
├── base.html
├── includes/
│ ├── _pagination.html
│ └── _messages.html
└── blog/
├── article_list.html
└── article_detail.html
```
Prefix partials with underscore. Use `{% url %}` not hardcoded paths:
```html
{% extends "base.html" %}
{% block content %}
<a href="{% url 'blog:article-detail' slug=article.slug %}">
{{ article.title }}
</a>
{% endblock %}
```
## Type Hints
Add type hints throughout for mypy / IDE support:
```python
from django.http import HttpRequest, HttpResponse
from django.db.models import QuerySet
def article_list(request: HttpRequest) -> HttpResponse:
articles: QuerySet[Article] = Article.objects.filter(status="published")
return render(request, "blog/article_list.html", {"articles": articles})
```
```bash
# pyproject.toml
[tool.mypy]
plugins = ["mypy_django_plugin.main"]
django_settings_module = "config.settings.dev"
# Run
mypy apps/
```
## Running with ASGI (for async)
```bash
# Install
pip install uvicorn
# Development
uvicorn config.asgi:application --reload
# Production
gunicorn config.asgi:application -k uvicorn.workers.UvicornWorker -w 4
```
## Testing
```python
import pytest
from django.test import Client
from django.urls import reverse
@pytest.mark.django_db
def test_article_list_view(client: Client):
response = client.get(reverse("blog:article-list"))
assert response.status_code == 200
assert "articles" in response.context
@pytest.mark.django_db
async def test_async_view():
"""Async test for async views."""
from django.test import AsyncClient
client = AsyncClient()
response = await client.get("/api/weather/?city=Paris")
assert response.status_code == 200
```
Use `pytest-django` + `factory_boy` for ergonomic testing.
## Common Pitfalls
1. **N+1 queries**: Use `select_related` (FK) and `prefetch_related` (M2M). Check with django-debug-toolbar.
2. **Sync calls in async views**: Wrap ORM with `sync_to_async()`. Use `httpx` not `requests`.
3. **Missing migrations**: Run `makemigrations` after model changes. Commit migrations.
4. **Hardcoded URLs**: Use `{% url %}` in templates, `reverse()` in Python.
5. **No indexes**: Add `db_index=True` or `Meta.indexes` for filtered/ordered fields.
6. **Fat views**: Move business logic to model methods or a service layer.
## Modern Tooling
```bash
# pyproject.toml dev dependencies
django-debug-toolbar # Query debugging
django-extensions # shell_plus, show_urls
django-environ # Environment variables
pytest-django # Testing
factory-boy # Test fixtures
mypy + django-stubs # Type checking
ruff # Linting (replaces flake8/isort/black)
```
## Management Commands
Keep commands thin — delegate logic to services.
### SRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.