{"id":7184,"library":"djangorestframework-types","title":"Django REST Framework Types","description":"djangorestframework-types provides essential type stubs for Django REST Framework, enabling robust static type checking with tools like MyPy. As of version 0.9.0, it targets DRF 3.14+ and Python 3.8+, with updates typically released to support new DRF versions and features.","status":"active","version":"0.9.0","language":"en","source_language":"en","source_url":"https://github.com/sbdchd/djangorestframework-types","tags":["django","rest-framework","types","mypy","type-stubs","static-analysis"],"install":[{"cmd":"pip install djangorestframework-types mypy","lang":"bash","label":"Install package and MyPy"}],"dependencies":[{"reason":"Provides type stubs for this library; an existing DRF project is assumed.","package":"djangorestframework","optional":false},{"reason":"Highly recommended for full type coverage as DRF builds on Django's core types.","package":"django-stubs","optional":true},{"reason":"Required to actually perform static type checking using these stubs.","package":"mypy","optional":false}],"imports":[{"note":"This symbol is referenced in `mypy.ini` for configuration, not directly imported into Python code at runtime.","symbol":"DrfPlugin","correct":"plugins = drf_types.plugin.DrfPlugin"}],"quickstart":{"code":"# mypy.ini (create or update this file in your project root):\n# [mypy]\n# plugins =\n#    drf_types.plugin.DrfPlugin\n#\n# [drf-types]\n# # Optional: List your custom DRF apps for deeper introspection\n# # apps =\n# #   my_app\n# #   another_app\n\n\n# quickstart_example.py (save this as a Python file):\nfrom rest_framework import serializers\nimport os # For os.environ.get if needed for real data/auth\n\nclass UserSerializer(serializers.Serializer):\n    id: serializers.IntegerField = serializers.IntegerField(read_only=True)\n    username: serializers.CharField = serializers.CharField(max_length=150)\n    email: serializers.EmailField = serializers.EmailField()\n\n    def create(self, validated_data: dict[str, str]) -> dict[str, str]:\n        # In a real application, this would create a User model instance.\n        # This example just returns the data for demonstration.\n        print(f\"Creating user: {validated_data.get('username', 'N/A')}\")\n        return validated_data\n\n    def update(self, instance: dict, validated_data: dict[str, str]) -> dict:\n        # In a real application, this would update a User model instance.\n        print(f\"Updating user: {instance.get('id', 'N/A')}\")\n        instance['username'] = validated_data.get('username', instance.get('username', ''))\n        instance['email'] = validated_data.get('email', instance.get('email', ''))\n        return instance\n\n# Example usage with type checking:\ninitial_data = {\n    \"username\": \"testuser_\" + os.environ.get('TEST_ID', '1'),\n    \"email\": \"test@example.com\"\n}\n\nserializer = UserSerializer(data=initial_data)\nserializer.is_valid(raise_exception=True)\n\n# `validated_data` is now correctly typed thanks to djangorestframework-types\nvalidated_data: dict[str, str] = serializer.validated_data\n\n# MyPy will detect issues like accessing non-existent keys:\n# print(validated_data['non_existent_field']) # Mypy would flag this as an error\n\nprint(f\"Validated username: {validated_data['username']}\")\n\n# To run type checking, ensure mypy.ini is configured as above, then:\n# mypy quickstart_example.py\n","lang":"python","description":"To enable type checking for Django REST Framework, you *must* configure your `mypy.ini` file in your project root, adding the `drf_types.plugin.DrfPlugin` (see warnings section for details on `mypy.ini`). The Python example demonstrates how `djangorestframework-types` allows MyPy to correctly infer types for DRF serializers and their validated data, catching potential issues at development time. Save this as a Python file and run `mypy your_file.py` after installation and `mypy.ini` setup."},"warnings":[{"fix":"Create or update `mypy.ini` in your project root with:\n```ini\n[mypy]\nplugins =\n    drf_types.plugin.DrfPlugin\n```","message":"As of version 0.8.0, the `drf_types.plugin.DrfPlugin` must be explicitly listed in your `mypy.ini` under the `[mypy]` section. Omitting it will result in incomplete or incorrect type checking for DRF components.","severity":"breaking","affected_versions":">=0.8.0"},{"fix":"Ensure your `djangorestframework` package is version 3.14 or newer (`pip install 'djangorestframework>=3.14'`).","message":"Version 0.7.0 dropped support for Django REST Framework versions older than 3.14. Using `djangorestframework-types` with DRF < 3.14 may lead to type errors or unexpected behavior.","severity":"breaking","affected_versions":">=0.7.0"},{"fix":"Install `django-stubs` via `pip install django-stubs` and ensure its plugin (if applicable) is also configured in `mypy.ini`.","message":"For comprehensive type checking in a Django project, it is highly recommended to also install and configure `django-stubs`. `djangorestframework-types` builds upon `django-stubs` for core Django types.","severity":"gotcha","affected_versions":"*"},{"fix":"In your `mypy.ini`, add an `apps` key under `[drf-types]` (e.g., `apps = my_custom_app, another_app`).","message":"If you have custom DRF applications that define their own serializers, views, or models, MyPy's type checking might not fully understand them without explicit configuration. List them under the `[drf-types]` section in your `mypy.ini`.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure `djangorestframework-types` is installed in the same environment MyPy is running in, and that the `plugins` line in `mypy.ini` is correct: `plugins = drf_types.plugin.DrfPlugin`.","cause":"The `drf_types.plugin.DrfPlugin` module or class could not be located by MyPy, likely due to incorrect path or missing installation.","error":"mypy: Plugin 'drf_types.plugin.DrfPlugin' was not found"},{"fix":"Verify that `plugins = drf_types.plugin.DrfPlugin` is correctly placed in your `mypy.ini` file under the `[mypy]` section, and that your DRF version is supported (>=3.14).","cause":"MyPy is unable to resolve the correct types for DRF components, often indicating that the `drf_types.plugin.DrfPlugin` is not active or correctly configured.","error":"error: Module \"rest_framework.serializers\" has no attribute \"Serializer\"  [attr-defined]"},{"fix":"Ensure both `djangorestframework-types` and `django-stubs` are installed and their respective plugins are configured in `mypy.ini`. Check that you're using supported versions of Django and DRF.","cause":"This generic MyPy error, when related to DRF code, often means the type stubs for DRF (or Django) are not being fully applied, leading MyPy to infer `Any` instead of specific types.","error":"error: Incompatible types in assignment (expression has type \"Any\", variable has type \"dict[str, str]\")"}]}