This package contains type stubs and a custom mypy plugin to provide more precise static types and type inference for Django framework. Django uses some Python "magic" that makes having precise types for some code patterns problematic. This is why we need this project. The final goal is to be able to get precise types for most common patterns.
Supported type checkers
- mypy: full and complete support with multiple advanced features with our custom mypy plugin, checked in CI
- pyright: basic support, checked in CI
- pyrefly: basic support, checked in CI
- ty: basic support, checked in CI
Installation
ty, pyrefly, pyright
pip install django-stubs
MyPy
pip install 'django-stubs[compatible-mypy]'
To make mypy aware of the plugin, you need to add
[mypy]
plugins =
mypy_django_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = "myproject.settings"
in your mypy.ini or setup.cfg file.
pyproject.toml configurations are also supported:
[tool.mypy]
plugins = ["mypy_django_plugin.main"]
[tool.django-stubs]
django_settings_module = "myproject.settings"
Two things happening here:
- We need to explicitly list our plugin to be loaded by
mypy - You can either specify
django_settings_moduleas seen above, or letdjango_stubsuse theDJANGO_SETTINGS_MODULEvariable from your environment.
This fully working typed boilerplate can serve you as an example.
Version compatibility
We rely on different django and mypy versions:
| django-stubs | Mypy version | Django version | Django partial support | Python version |
|---|---|---|---|---|
| unreleased | 1.16 - 2.4 | 6.1 | 6.0, 5.2 | 3.11 - 3.15 |
| 6.1.2 | 1.13 - 2.4 | 6.1 | 6.0, 5.2 | 3.11 - 3.14 |
| 6.1.1 | 1.13 - 2.3 | 6.1 | 6.0, 5.2 | 3.11 - 3.14 |
| 6.1.0 | 1.13 - 2.3 | 6.1 | 6.0, 5.2 | 3.11 - 3.14 |
| 6.0.9 | 1.13 - 2.3 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.8 | 1.13 - 2.3 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.7 | 1.13 - 2.3 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.6 | 1.13 - 2.1 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.5 | 1.13 - 2.1 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.4 | 1.13 - 2.0 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.3 | 1.13 - 1.20 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.2 | 1.13 - 1.20 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.1 | 1.13 - 1.19 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 6.0.0 | 1.13 - 1.19 | 6.0 | 5.2, 5.1, 5.0 | 3.10 - 3.14 |
| 5.2.9 | 1.13 - 1.19 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.8 | 1.13 - 1.19 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.7 | 1.13 - 1.18 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.6 | 1.13 - 1.18 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.5 | 1.13 - 1.18 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.4 | 1.13 - 1.18 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.3 | 1.13 - 1.18 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.2 | 1.13 - 1.17 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.1 | 1.13 - 1.16 | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
| 5.2.0 | 1.13+ | 5.2 | 5.1, 5.0 | 3.10 - 3.13 |
What "partial" support means, and why we don't pin to the exact Django/mypy version, is explained in https://github.com/typeddjango/django-stubs/discussions/2101#discussioncomment-9276632.
Sponsors
Features
Type checking of Model Meta attributes
[!NOTE] If you are using the mypy plugin and have
django_stub_extinstalled, your modelMetaclasses will be automatically type-checked without further changes.
By inheriting from the TypedModelMeta class, you can ensure you're using correct types for
attributes:
from django.db import models
from django_stubs_ext.db.models import TypedModelMeta
class MyModel(models.Model):
example = models.CharField(max_length=100)
class Meta(TypedModelMeta):
ordering = ["example"]
constraints = [
models.UniqueConstraint(fields=["example"], name="unique_example"),
]
Other typed base classes
django_stubs_ext.db.router.TypedDatabaseRoutercan be used as base when implementing custom database routers.
Settings
django-stubs has a few settings, which you can list in:
pyproject.toml, under the table[tool.django-stubs]mypy.iniunder the table[mypy.plugins.django-stubs]
The supported settings are:
django_settings_module, a string, default toos.getenv(DJANGO_SETTINGS_MODULE).
Specify the import path of your settings module, the same as Django’s DJANGO_SETTINGS_MODULE environment variable.
strict_settings, a boolean, defaulttrue.
Set to false if using dynamic settings, as described below.
strict_model_abstract_attrs, a boolean, defaulttrue.
Set to false if you want to keep .objects, .DoesNotExist, .NotUpdated, and
.MultipleObjectsReturned attributes on models.Model type.
See here why
this is dangerous to do by default.
FAQ
### Is this an official Django project?
No, it is not. We are independent from Django at the moment. There's a [proposal](https://github.com/django/deps/pull/65) to merge our project into the Django itself. You can show your support by liking the PR.### Is it safe to use this in production?
Yes, it is! This project does not affect your runtime at all. It only affects `mypy` type checking process. But, it does not make any sense to use this project without `mypy`.### mypy crashes when I run it with this plugin installed
The current implementation uses Django's runtime to extract information about models, so it might crash if your installed apps or `models.py` are broken. In other words, if your `manage.py runserver` crashes, mypy will crash too. You can also run `mypy` with [`--tb`](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-show-traceback) option to get extra information about the error.### I cannot use QuerySet or Manager with type annotations
You can get a `TypeError: 'type' object is not subscriptable` when you will try to use `QuerySet[MyModel]`, `Manager[MyModel, MyQuerySet]` or some other Django-based Generic types. This happens because these Django classes do not support [`__class_getitem__`](https://www.python.org/dev/peps/pep-0560/#class-getitem) magic method in runtime. 1. You can go with our [`django_stubs_ext`](https://github.com/typeddjango/django-stubs/tree/master/ext) helper, that patches all the types we use as Generic in django. Install it: ```bash pip install django-stubs-ext # as a production dependency ``` And then place in your top-level settings: ```python import django_stubs_ext django_stubs_ext.monkeypatch() ``` You can add extra types to patch with `django_stubs_ext.monkeypatch(extra_classes=[YourDesiredType])` **If you use generic symbols in `django.contrib.auth.forms`**, you will have to do the monkeypatching manually in your first [`AppConfig.ready`](https://docs.djangoproject.com/en/stable/ref/applications/#django.apps.AppConfig.ready). This is currently required because `django.contrib.auth.forms` cannot be imported until django is initialized. ```python import django_stubs_ext from django.apps import AppConfig class ClientsConfig(AppConfig): name = "clients" def ready(self) -> None: from django.contrib.auth.forms import SetPasswordMixin, SetUnusablePasswordMixin # For Django version prior to 5.1, use `extra_classes=[SetPasswordForm, AdminPasswordChangeForm]` instead. django_stubs_ext.monkeypatch(extra_classes=[SetPasswordMixin, SetUnusablePasswordMixin]) ``` 2. You can use strings instead: `'QuerySet[MyModel]'` and `'Manager[MyModel, MyQuerySet]'`, this way it will work as a type for `mypy` and as a regular `str` in runtime.### How can I create a HttpRequest that's guaranteed to have an authenticated user?
Django's built in [`HttpRequest`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest) has the attribute `user` that resolves to the type `User | AnonymousUser` where `User` is the user model specified by the `AUTH_USER_MODEL` setting. If you want a `HttpRequest` that you can type-annotate with where you know that the user is authenticated you can subclass the normal `HttpRequest` class like so:from django.http import HttpRequest
from my_user_app.models import MyUser
class AuthenticatedHttpRequest(HttpRequest):
user: MyUser
### Why am I getting incompatible return type errors on my custom managers?
If you declare your custom managers without generics and override built-in methods you might see an error message about incompatible error messages, something like this:from django.db import models
class MyManager(models.Manager):
def create(self, **kwargs) -> "MyModel":
pass
class MyManager(models.Manager["MyModel"]): ...
class MyQuerySet(models.QuerySet): ...
class MyManager(models.Manager):
def get_queryset(self) -> MyQuerySet:
return MyQuerySet(self.model, using=self._db)
class MyQuerySet(models.QuerySet["MyModel"]): ...
class MyManager(models.Manager["MyModel", MyQuerySet]):
def get_queryset(self) -> MyQuerySet:
return MyQuerySet(self.model, using=self._db)
from typing import TypeVar
_M = TypeVar("_M", bound=models.Model)
class MyQuerySet(models.QuerySet[_M]): ...
class MyManager(models.Manager[_M, MyQuerySet[_M]]):
def get_queryset(self) -> MyQuerySet[_M]:
return MyQuerySet(self.model, using=self._db)
class BookManager(MyManager["Book"]): ...
class Book(models.Model):
objects = BookManager() # Book.objects.filter() is MyQuerySet[Book]
### Why are my custom queryset methods lost after `values()` or `values_list()`?
These methods change the row type of the queryset, so they return a plain `QuerySet` by default. To keep your custom queryset class, give it a row type variable defaulting to the model:from typing_extensions import Self, TypeVar
_M = TypeVar("_M", bound=models.Model)
_Row = TypeVar("_Row", default=_M)
class BookQuerySet(models.QuerySet[_M, _Row]):
def published(self) -> Self:
return self.filter(is_published=True)
class Book(models.Model):
title = models.CharField(max_length=100)
is_published = models.BooleanField()
objects = BookQuerySet.as_manager()
Book.objects.values("title").published() # BookQuerySet[Book, TypedDict({'title': str})]
### How do I annotate cases where I called QuerySet.annotate?
Django-stubs provides a special type, `django_stubs_ext.WithAnnotations[Model,from typing import TypedDict
from django_stubs_ext import WithAnnotations
from django.db import models
from django.db.models.expressions import Value
class MyModel(models.Model):
username = models.CharField(max_length=100)
class MyTypedDict(TypedDict):
foo: str
def func(m: WithAnnotations[MyModel, MyTypedDict]) -> str:
print(m.bar) # Error, since field "bar" is not in MyModel or MyTypedDict.
return m.foo # OK, since we said field "foo" was allowed
func(MyModel.objects.annotate(foo=Value("")).get(id=1)) # OK
func(MyModel.objects.annotate(bar=Value("")).get(id=1)) # Error
from typing import TypeVar, TypedDict
from django.db import models
from django.db.models import Manager
from django_stubs_ext import WithAnnotations
class SalesDict(TypedDict):
total_sales: int
_Model = TypeVar("_Model", bound=models.Model, covariant=True)
class ProductQuerySet(models.QuerySet[_Model]):
def with_sales(self) -> "ProductQuerySet[WithAnnotations[_Model, SalesDict]]":
return self.annotate(total_sales=models.Sum("order__amount"))
ProductManager = Manager.from_queryset(ProductQuerySet)
class Product(models.Model):
name = models.CharField(max_length=100)
objects = ProductManager()
product = Product.objects.with_sales().get(id=1)
product.total_sales # OK, int
product.name # OK, str
### Why am I getting incompatible argument type mentioning `_StrPromise`?
The lazy translation functions of Django (such as `gettext_lazy`) return a `Promise` instead of `str`. These two types [cannot be used interchangeably](https://github.com/typeddjango/django-stubs/pull/1139#issuecomment-1232167698). The return type of these functions was therefore [changed](https://github.com/typeddjango/django-stubs/pull/689) to reflect that. If you encounter this error in your own code, you can either cast the `Promise` to `str` (causing the translation to be evaluated), or use the `StrPromise` or `StrOrPromise` types from `django-stubs-ext` in type hints. Which solution to choose depends depends on the particular case. See [working with lazy translation objects](https://docs.djangoproject.com/en/stable/topics/i18n/translation/#working-with-lazy-translation-objects) in the Django documentation for more information. If this is reported on Django code, please report an issue or open a pull request to fix the type hints.### How do I annotate a test client response?
The test client adds attributes such as `context`, `templates` and `json()` to its responses, so `HttpResponse` is not enough. Use `ClientResponse`, or `AsyncClientResponse` for `AsyncClient`, from `django-stubs-ext`:from django_stubs_ext import ClientResponse
def assert_has_form(response: ClientResponse) -> None:
assert "form" in response.context
### How to use a custom library to handle Django settings?
Using something like [`django-split-settings`](https://github.com/wemake-services/django-split-settings) or [`django-configurations`](https://github.com/jazzband/django-configurations) will make it hard for mypy to infer your settings. This might also be the case when using something like:try:
from .local_settings import *
except Exception:
pass
from django.conf import settings
settings.CUSTOM_VALUE # E: 'Settings' object has no attribute 'CUSTOM_VALUE'
[tool.django-stubs]
strict_settings = false
[mypy.plugins.django-stubs]
strict_settings = false
from typing import reveal_type
# Works:
reveal_type(settings.EXISTS_AT_RUNTIME) # N: Any
# Errors:
reveal_type(settings.MISSING) # E: 'Settings' object has no attribute 'MISSING'
### How to use `type[Model]` annotation with `.objects` attribute?
Let's say you have a function similar to this one, which accepts a model type and accesses its `.object` attribute:from django.db import models
def assert_zero_count(model_type: type[models.Model]) -> None:
assert model_type.objects.count() == 0
error: "type[Model]" has no attribute "objects" [attr-defined]
def assert_zero_count(model_type: type[models.Model]) -> None:
assert model_type._default_manager.count() == 0
### How do I annotate `apps` in a `RunPython` migration?
Use `StateApps`, not `Apps`:from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
def forwards(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
Book = apps.get_model("myapp", "Book") # type[Any]
### Do I need to annotate reverse relations?
Not if you use our mypy plugin. It reads your app registry and declares every reverse accessor for you, as `RelatedManager[Model]`, or `ManyRelatedManager[Model, Through]` for a `ManyToManyField`. pyright, pyrefly and ty do not run the plugin, so under those you declare them yourself. Reach for `RelatedManager` rather than `Manager`: a reverse accessor is read from a model instance, whereas a regular manager such as `objects` only exists on the model class.from django.db import models
from django_stubs_ext.db.models.manager import ManyRelatedManager, RelatedManager
class Article(models.Model):
category_set: RelatedManager[Category]
tags: ManyRelatedManager[Tag, ArticleTag]
class CategoryQuerySet(models.QuerySet["Category"]): ...
class Article(models.Model):
category_set: RelatedManager[Category, CategoryQuerySet]
### How to type a custom `models.Field`?
> [!NOTE] > This require type generic support, see this section to enable it. Django `models.Field` (and subclasses) are generic types with two parameters: - `_ST_contra`: type that can be used when setting a value - `_GT_co`: type that will be returned when getting a value The `null=...` flag is resolved at the call site by the fields' constructor overloads. For ex: - `IntegerField()` and `IntegerField(null=False)` are an `IntegerField[float | int | str, int]`. - `IntegerField(null=True)` is an `IntegerField[float | int | str | None, int | None]`. When defining a custom field subclass, you have to declare the type parameters' defaults yourself. For ex a custom integer field repeats the ones of `IntegerField`:from typing_extensions import TypeVar, assert_type
from django.db import models
_ST_contra = TypeVar("_ST_contra", contravariant=True, default=float | int | str)
_GT_co = TypeVar("_GT_co", covariant=True, default=int)
class MyIntegerField(models.IntegerField[_ST_contra, _GT_co]):
pass
class User(models.Model):
custom_int = MyIntegerField()
custom_int_nullable = MyIntegerField(null=True)
assert_type(User().custom_int, int)
assert_type(User().custom_int_nullable, int | None)
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal, overload
from typing_extensions import TypeVar, Unpack, assert_type, deprecated
from django.db import models
if TYPE_CHECKING:
# A type-check-only `TypedDict` of the keyword arguments shared by every `Field`
from django.db.models.fields import FieldInitKwargs
_ST_contra = TypeVar("_ST_contra", contravariant=True, default=float | int | str)
_GT_co = TypeVar("_GT_co", covariant=True, default=int)
class MyIntegerField(models.IntegerField[_ST_contra, _GT_co]):
# `MyIntegerField()` or `MyIntegerField(null=False)`: keeps the type var defaults.
@overload
def __init__(
self,
verbose_name: str | None = None,
name: str | None = None,
*,
null: Literal[False] = False,
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `MyIntegerField(null=True)`: the `self` annotation gives the nullable type.
@overload
def __init__(
self: MyIntegerField[float | int | str | None, int | None],
verbose_name: str | None = None,
name: str | None = None,
*,
null: Literal[True],
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `Sub(null=True)` for `class Sub(MyIntegerField): ...`: its bound types can't match the overload above.
@overload
def __init__(
self,
verbose_name: str | None = None,
name: str | None = None,
*,
null: Literal[True],
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `MyIntegerField(null=flag)` with `flag: bool`. Stays last, as `bool` also matches `True`.
@overload
@deprecated("`null` must be a literal `True` or `False` for the field type to be inferred")
def __init__(
self,
verbose_name: str | None = None,
name: str | None = None,
*,
null: bool,
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class User(models.Model):
custom_int = MyIntegerField()
custom_int_nullable = MyIntegerField(null=True)
assert_type(User().custom_int, int)
assert_type(User().custom_int_nullable, int | None)
### How to type a custom `ArrayField`?
`ArrayField` reads its element types from `base_field`. For ex: - `ArrayField(models.IntegerField())` is an `ArrayField[Sequence[float | int | str], list[int]]`. - `ArrayField(models.IntegerField(), null=True)` is an `ArrayField[Sequence[float | int | str] | None, list[int] | None]`. A subclass that changes the container binds the type parameters, and no longer reads the element types:from typing import Any
from typing_extensions import assert_type
from django.contrib.postgres.fields import ArrayField
from django.db import models
class SetArrayField(ArrayField[set[Any], set[Any]]):
pass
class Post(models.Model):
tag_ids = SetArrayField(models.IntegerField())
assert_type(Post().tag_ids, set[Any])
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Literal, overload
from typing_extensions import TypeVar, Unpack, assert_type, deprecated
from django.contrib.postgres.fields import ArrayField
from django.db import models
if TYPE_CHECKING:
from django.db.models.fields import FieldInitKwargs
_ST_contra = TypeVar("_ST_contra", contravariant=True, default=Sequence[Any])
_GT_co = TypeVar("_GT_co", covariant=True, default=list[Any])
_ElemST = TypeVar("_ElemST")
_ElemGT = TypeVar("_ElemGT")
class MyArrayField(ArrayField[_ST_contra, _GT_co]):
# `MyArrayField(models.IntegerField())`: the element types come from `base_field`.
@overload
def __init__(
self: MyArrayField[Sequence[_ElemST], list[_ElemGT]],
base_field: models.Field[_ElemST, _ElemGT],
size: int | None = None,
*,
verbose_name: str | None = None,
name: str | None = None,
null: Literal[False] = False,
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `MyArrayField(models.IntegerField(), null=True)`: the same element types, in the nullable containers.
@overload
def __init__(
self: MyArrayField[Sequence[_ElemST] | None, list[_ElemGT] | None],
base_field: models.Field[_ElemST, _ElemGT],
size: int | None = None,
*,
verbose_name: str | None = None,
name: str | None = None,
null: Literal[True],
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `Sub(models.IntegerField())` for `class Sub(MyArrayField[set[Any], set[Any]]): ...`: neither above matches.
@overload
def __init__(
self,
base_field: models.Field[Any, Any],
size: int | None = None,
*,
verbose_name: str | None = None,
name: str | None = None,
null: Literal[False] = False,
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `Sub(models.IntegerField(), null=True)` for the same subclass, kept off the deprecated overload.
@overload
def __init__(
self,
base_field: models.Field[Any, Any],
size: int | None = None,
*,
verbose_name: str | None = None,
name: str | None = None,
null: Literal[True],
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
# `MyArrayField(models.IntegerField(), null=flag)` with `flag: bool`. Stays last, as `bool` also matches `True`.
@overload
@deprecated("`null` must be a literal `True` or `False` for the field type to be inferred")
def __init__(
self,
base_field: models.Field[Any, Any],
size: int | None = None,
*,
verbose_name: str | None = None,
name: str | None = None,
null: bool,
primary_key: bool = False,
max_length: int | None = None,
db_default: Any = ...,
**kwargs: Unpack[FieldInitKwargs],
) -> None: ...
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class Post(models.Model):
scores = MyArrayField(models.IntegerField())
scores_nullable = MyArrayField(models.IntegerField(), null=True)
assert_type(Post().scores, list[int])
assert_type(Post().scores_nullable, list[int] | None)
Related projects
awesome-python-typing- Awesome list of all typing-related things in Python.djangorestframework-stubs- Stubs for Django REST Framework.pytest-mypy-plugins-pytestplugin that we use for testingmypystubs and plugins.wemake-django-template- Create new typed Django projects in seconds.django-modern-rest- Modern REST framework for Django with everything properly typed.
Contributing
This project is open source and community driven. As such we encourage contributions big and small. You can contribute by doing any of the following:
- Contribute code (e.g. improve stubs, add plugin capabilities, write tests etc) - to do so please follow the contribution guide.
- Assist in code reviews and discussions in issues.
- Identify bugs and issues and report these
- Ask and answer questions on StackOverflow
You can always also reach out in gitter to discuss your contributions!