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.
pip install django-stubsNo compatibility data collected yet for this library.
To use django-stubs, you need to configure Mypy to use its plugin. Create or update your `mypy.ini` or `pyproject.toml` file as shown. Replace `my_project.settings` with the actual path to your Django settings module. This configuration allows Mypy to understand Django's dynamic nature, especially with models and querysets.
Ensure your `django-stubs` version matches your `Django` version. For example, use `django-stubs==6.*` with `Django==6.*`.
Ensure you have `plugins = mypy_django_plugin.main` configured in your `mypy.ini` or `pyproject.toml` file, and point `django_settings_module` to your project's settings. No `import django_stubs` is necessary or correct.
Check `django-stubs` release notes or documentation for the officially supported `mypy` versions. For example, `django-stubs 6.0.2` officially supports `mypy@1.20`.
Upgrade to `django-stubs` version `6.0.1` or newer. This issue was resolved in version `6.0.1`.
Ensure that your Mypy configuration file is correctly placed (e.g., `mypy.ini` in the project root) and that you are invoking the `mypy` command-line tool to perform type checking. For example: `mypy your_project_path/` or `python -m mypy your_project_path/`. Do not try to execute the configuration file directly with the Python interpreter.
Ensure your Mypy configuration is stored in a `mypy.ini` or `pyproject.toml` file and is invoked correctly by the `mypy` command (e.g., `mypy --config-file mypy.ini` or by placing it in a default location), rather than attempting to execute the configuration file directly as a Python script.
Ensure the `mypy_django_plugin.main` is correctly configured in your `mypy.ini` or `pyproject.toml`. For generic model parameters, you might also need to explicitly hint the manager, e.g., `objects: models.Manager["MyModel"]` on the model class itself.
Use `django_stubs_ext.monkeypatch()` at an early stage of your application (e.g., in an `AppConfig.ready` method) to enable generic support for Django types, or use string literal type annotations like `'QuerySet[MyModel]'` and `'Manager[MyModel]'`.
Declare your custom manager with your specific model as the type variable, for example: `class MyManager(models.Manager["MyModel"]):`.