django-typing
Skill4 starsChanged 14 months agoBSD-3-ClauseView on GitHub
Type safety and mypy best practices for Django projects. Covers django-stubs configuration, type hints for models/views/forms/DRF, advanced typing patterns, and automated type checking.
- Installs packages
In this repository3 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- django-best-practicesSkill
- django-securitySkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 37
Create mypy.ini in project root:
- Distinctive: line 433
Ask about type hints in Django
- Distinctive: line 437
Ask about django-stubs configuration
- Very specific: line 470
Create mypy.ini configuration (see assets/mypy.ini)
- Very specific: line 471
Run python scripts/typing_checker.py to check current project
- Very specific: line 472
Use type_hint_generator.py to add hints to existing code
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Django Typing and mypy Best Practices
Complete guide to type safety in Django applications using mypy and django-stubs.
Quick Start
Installation
# Install mypy and django-stubs
pip install mypy django-stubs django-stubs-ext
# For Django REST Framework
pip install djangorestframework-stubs
# Add to requirements.txt
mypy==1.8.0
django-stubs==4.2.7
django-stubs-ext==4.2.7
djangorestframework-stubs==3.14.5 # If using DRFBasic Configuration
Create mypy.ini in project root:
[mypy]
plugins = mypy_django_plugin.main, mypy_drf_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = myproject.settings
[mypy-*.migrations.*]
ignore_errors = TrueQuick Reference
Models
from django.db import models
from typing import ClassVar
class Article(models.Model):
title: str = models.CharField(max_length=200)
published: bool = models.BooleanField(default=False)
# Declare manager type
objects: ClassVar[models.Manager["Article"]] = models.Manager()
def get_title(self) -> str:
return self.titleViews
from django.http import HttpRequest, HttpResponse
from django.views.generic import ListView
from typing import Any
# Function-based view
def article_list(request: HttpRequest) -> HttpResponse:
return HttpResponse("Articles")
# Class-based view
class ArticleListView(ListView[Article]):
model = Article
template_name = "articles/list.html"
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
context = super().get_context_data(**kwargs)
return contextForms
from django import forms
from typing import Any
class ArticleForm(forms.ModelForm[Article]):
class Meta:
model = Article
fields = ["title", "published"]
def clean_title(self) -> str:
title = self.cleaned_data["title"]
return title.strip()Django REST Framework
from rest_framework import serializers, viewsets
from typing import Any
class ArticleSerializer(serializers.ModelSerializer[Article]):
class Meta:
model = Article
fields = ["id", "title", "published"]
def validate_title(self, value: str) -> str:
return value.strip()
class ArticleViewSet(viewsets.ModelViewSet[Article]):
queryset = Article.objects.all()
serializer_class = ArticleSerializerCustom Managers and QuerySets
from django.db import models
from typing import TypeVar, Generic
_T = TypeVar("_T", bound=models.Model)
class CustomQuerySet(models.QuerySet[_T], Generic[_T]):
def published(self) -> "CustomQuerySet[_T]":
return self.filter(published=True)
class CustomManager(models.Manager[_T]):
def get_queryset(self) -> CustomQuerySet[_T]:
return CustomQuerySet(self.model, using=self._db)
def published(self) -> CustomQuerySet[_T]:
return self.get_queryset().published()
class Article(models.Model):
title: str = models.CharField(max_length=200)
published: bool = models.BooleanField(default=False)
objects: ClassVar[CustomManager["Article"]] = CustomManager()Common Patterns
Type Narrowing
from django.http import HttpRequest, HttpResponse, JsonResponse
from typing import Union
def api_view(request: HttpRequest) -> Union[HttpResponse, JsonResponse]:
if request.method == "GET":
# Type narrowing with isinstance
return JsonResponse({"status": "ok"})
return HttpResponse("Invalid method")Protocol for Duck Typing
from typing import Protocol
class Publishable(Protocol):
published: bool
def publish(self) -> None: ...
def publish_item(item: Publishable) -> None:
if not item.published:
item.publish()TypedDict for Settings
from typing import TypedDict
class DatabaseConfig(TypedDict):
ENGINE: str
NAME: str
USER: str
PASSWORD: str
HOST: str
PORT: int
DATABASES: dict[str, DatabaseConfig] = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydb",
"USER": "user",
"PASSWORD": "pass",
"HOST": "localhost",
"PORT": 5432,
}
}Multi-Tenant Typing
from django.db import models
from typing import TypeVar, Generic, ClassVar
T = TypeVar("T", bound="TenantBaseModel")
class TenantBaseModel(models.Model):
tenant: models.ForeignKey["Tenant"] = models.ForeignKey(
"Tenant", on_delete=models.CASCADE
)
class Meta:
abstract = True
class TenantQuerySet(models.QuerySet[T], Generic[T]):
def for_tenant(self, tenant: "Tenant") -> "TenantQuerySet[T]":
return self.filter(tenant=tenant)
class TenantManager(models.Manager[T]):
def get_queryset(self) -> TenantQuerySet[T]:
return TenantQuerySet(self.model, using=self._db)
def for_tenant(self, tenant: "Tenant") -> TenantQuerySet[T]:
return self.get_queryset().for_tenant(tenant)Automated Tools
This skill includes scripts for automated type checking and improvement:
1. Type Checker
# Run mypy with Django-specific configuration
python scripts/typing_checker.py
# Check specific app
python scripts/typing_checker.py --app myapp
# Strict mode
python scripts/typing_checker.py --strict
# Generate HTML report
python scripts/typing_checker.py --html-report2. Type Hint Generator
# Auto-add type hints to models
python scripts/type_hint_generator.py --target models --app myapp
# Add hints to views
python scripts/type_hint_generator.py --target views --app myapp
# Generate for all apps
python scripts/type_hint_generator.py --all3. Configuration Validator
# Validate mypy configuration
python scripts/config_validator.py
# Check django-stubs setup
python scripts/config_validator.py --check-stubs
# Suggest improvements
python scripts/config_validator.py --suggestResources
Reference Documentation
- django-typing-guide.md - Complete guide to typing Django (models, views, forms, etc.)
- mypy-django-configuration.md - mypy setup and configuration for Django
- drf-typing-patterns.md - Django REST Framework typing patterns
- advanced-typing-patterns.md - Generics, Protocols, TypedDict, type guards
- multi-tenant-typing.md - Type safety for multi-tenant architectures
- troubleshooting-mypy-django.md - Common mypy errors and solutions
Templates and Examples
- mypy.ini - Complete mypy configuration template
- pyproject.toml - Alternative mypy configuration
- .pre-commit-config.yaml - Pre-commit hooks for type checking
- typed_model_template.py - Fully typed Django model examples
- typed_view_template.py - Typed views (CBV and FBV)
- typed_serializer_template.py - DRF serializer typing
- typed_manager_template.py - Custom manager and queryset typing
Common mypy Errors
Error: Need type annotation for variable
# ❌ Error
items = []
# ✅ Fix
from typing import List
items: List[Article] = []Error: Incompatible types in assignment
# ❌ Error
article: Article = Article.objects.first() # Returns Article | None
# ✅ Fix
from django.shortcuts import get_object_or_404
article: Article = get_object_or_404(Article, pk=1)
# Or
article = Article.objects.first()
if article is not None:
# mypy knows article is Article here
print(article.title)Error: Cannot determine type of field
# ❌ Error
class Article(models.Model):
title = models.CharField(max_length=200)
# ✅ Fix
class Article(models.Model):
title: str = models.CharField(max_length=200)Best Practices
1. Use Strict Mode Gradually
[mypy]
# Start with these
check_untyped_defs = True
disallow_untyped_defs = False # Enable later
# Enable gradually
disallow_any_generics = True
disallow_subclassing_any = True2. Ignore Migrations
[mypy-*.migrations.*]
ignore_errors = True3. Type QuerySets Properly
# ✅ Good
articles: models.QuerySet[Article] = Article.objects.filter(published=True)
# ❌ Avoid
articles = Article.objects.filter(published=True) # Type is unknown4. Use ClassVar for Class-Level Attributes
from typing import ClassVar
class Article(models.Model):
# Instance attribute
title: str = models.CharField(max_length=200)
# Class attribute
objects: ClassVar[models.Manager["Article"]] = models.Manager()5. Annotate Request and Response
from django.http import HttpRequest, HttpResponse
def my_view(request: HttpRequest) -> HttpResponse:
return HttpResponse("OK")Integration with CI/CD
Pre-commit Hook
Add to .pre-commit-config.yaml:
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
additional_dependencies: [django-stubs, djangorestframework-stubs]
args: [--config-file=mypy.ini]GitHub Actions
name: Type Check
on: [push, pull_request]
jobs:
mypy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- run: pip install -r requirements.txt
- run: mypy .When to Use This Skill
Claude will automatically use this skill when you:
- Ask about type hints in Django
- Request help with mypy errors
- Want to add type checking to a Django project
- Need typing for models, views, forms, or serializers
- Ask about django-stubs configuration
- Request type-safe patterns for Django REST Framework
- Need help with generic types, Protocols, or TypedDict
- Want to implement type-safe multi-tenant patterns
Related Skills
- django-best-practices - Multi-tenant patterns and Django best practices
- django-security - Security hardening and vulnerability detection
Quick Commands
# Run type checker
python scripts/typing_checker.py
# Add type hints to existing code
python scripts/type_hint_generator.py --app myapp
# Validate mypy configuration
python scripts/config_validator.py
# Install pre-commit hooks
pre-commit install
# Check types in CI
mypy --config-file=mypy.ini .Next Steps:
- Install mypy and django-stubs
- Create
mypy.iniconfiguration (seeassets/mypy.ini) - Run
python scripts/typing_checker.pyto check current project - Use
type_hint_generator.pyto add hints to existing code - Set up pre-commit hooks for automatic checking
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

