Django Stubs
Django Stubs provides Mypy type stubs for the Django framework, enabling static type checking for Django projects. It includes a Mypy plugin that understands Django's ORM, models, and settings to provide accurate type inference. The library is actively maintained with frequent updates, often aligning its major versions with Django's release cycle, ensuring compatibility and comprehensive coverage for new Django features.
Warnings
- breaking Major versions of `django-stubs` are tightly coupled with major versions of `Django`. Upgrading `django-stubs` (e.g., from 5.x to 6.x) typically requires upgrading your `Django` version to match (e.g., from Django 5.x to Django 6.x). Incompatible versions can lead to incorrect type checking or Mypy plugin errors.
- gotcha `django-stubs` does not expose symbols for direct import. Its functionality is exclusively provided through Mypy's plugin system. Users commonly misunderstand that it's a library to be imported rather than a Mypy extension.
- gotcha Specific `mypy` versions are required for full compatibility. While `django-stubs` generally aims for broad `mypy` support, new features or critical bug fixes often necessitate upgrading `mypy` itself.
- gotcha Version `6.0.0` of `django-stubs` contained a crash bug in the Mypy plugin when checking code that used `QuerySet.order_by()` with abstract models. This caused Mypy to fail unexpectedly.
Install
-
pip install django-stubs
Quickstart
[mypy] plugins = mypy_django_plugin.main [mypy.plugins.django] django_settings_module = "my_project.settings" # Example of a Django model file (e.g., my_app/models.py) # from django.db import models # # class MyModel(models.Model): # name = models.CharField(max_length=100) # value = models.IntegerField(default=0) # # # Example of using type hints # def get_model_by_name(name: str) -> MyModel | None: # return MyModel.objects.filter(name=name).first() # # # Run mypy from your project root: # # mypy .