From dcfbced2e75998a8807b16470a7a226201e66963 Mon Sep 17 00:00:00 2001 From: NorthIsUp Date: Mon, 31 Aug 2026 15:13:43 -0700 Subject: [PATCH 1/6] Add symbols Django exports but the stubs omit Each exists at runtime and is importable from its documented public location, but is missing from the stubs, so a strict checker rejects the import. - django.test: AsyncClient, AsyncRequestFactory - defined in test/client.pyi, never re-exported from the package. - django.http: HttpResponseBase - defined in http/response.pyi, not re-exported. - TestCase.captureOnCommitCallbacks - a context manager since Django 3.2. - django.core.files.storage: storages, StorageHandler, InvalidStorageError - the storage-alias registry added in Django 4.2. - django.utils.http.parse_header_parameters. --- django-stubs/core/files/storage.pyi | 12 ++++++++++++ django-stubs/http/__init__.pyi | 1 + django-stubs/test/__init__.pyi | 2 ++ django-stubs/test/testcases.pyi | 8 +++++++- django-stubs/utils/http.pyi | 1 + 5 files changed, 23 insertions(+), 1 deletion(-) diff --git a/django-stubs/core/files/storage.pyi b/django-stubs/core/files/storage.pyi index abce8ecf6..963e31343 100644 --- a/django-stubs/core/files/storage.pyi +++ b/django-stubs/core/files/storage.pyi @@ -1,3 +1,4 @@ +from django.core.exceptions import ImproperlyConfigured from datetime import datetime from typing import IO, Any @@ -45,3 +46,14 @@ class DefaultStorage(LazyObject): ... default_storage: Storage def get_storage_class(import_path: str | None = ...) -> type[Storage]: ... + +class InvalidStorageError(ImproperlyConfigured): ... + +class StorageHandler: + def __init__(self, backends: dict[str, dict[str, Any]] | None = ...) -> None: ... + def __getitem__(self, alias: str) -> Storage: ... + def create_storage(self, params: dict[str, Any]) -> Storage: ... + @property + def backends(self) -> dict[str, dict[str, Any]]: ... + +storages: StorageHandler diff --git a/django-stubs/http/__init__.pyi b/django-stubs/http/__init__.pyi index a45c8867e..748ac198b 100644 --- a/django-stubs/http/__init__.pyi +++ b/django-stubs/http/__init__.pyi @@ -7,6 +7,7 @@ from .request import UnreadablePostError as UnreadablePostError from .response import BadHeaderError as BadHeaderError from .response import FileResponse as FileResponse from .response import Http404 as Http404 +from .response import HttpResponseBase as HttpResponseBase from .response import HttpResponse as HttpResponse from .response import HttpResponseBadRequest as HttpResponseBadRequest from .response import HttpResponseForbidden as HttpResponseForbidden diff --git a/django-stubs/test/__init__.pyi b/django-stubs/test/__init__.pyi index ad4229296..f6a535be8 100644 --- a/django-stubs/test/__init__.pyi +++ b/django-stubs/test/__init__.pyi @@ -1,5 +1,7 @@ from .client import Client as Client from .client import RequestFactory as RequestFactory +from .client import AsyncClient as AsyncClient +from .client import AsyncRequestFactory as AsyncRequestFactory from .testcases import LiveServerTestCase as LiveServerTestCase from .testcases import SimpleTestCase as SimpleTestCase from .testcases import TestCase as TestCase diff --git a/django-stubs/test/testcases.pyi b/django-stubs/test/testcases.pyi index b6c67aa89..9da170439 100644 --- a/django-stubs/test/testcases.pyi +++ b/django-stubs/test/testcases.pyi @@ -1,6 +1,7 @@ import threading import unittest -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Iterator +from contextlib import contextmanager from types import TracebackType from typing import Any, ClassVar, TypeVar, overload @@ -211,6 +212,11 @@ class TransactionTestCase(SimpleTestCase): ) -> _AssertNumQueriesContext: ... class TestCase(TransactionTestCase): + @classmethod + @contextmanager + def captureOnCommitCallbacks( + cls, *, using: str = ..., execute: bool = ... + ) -> Iterator[list[Callable[[], Any]]]: ... @classmethod def setUpTestData(cls) -> None: ... diff --git a/django-stubs/utils/http.pyi b/django-stubs/utils/http.pyi index bfa869290..e637e4cef 100644 --- a/django-stubs/utils/http.pyi +++ b/django-stubs/utils/http.pyi @@ -44,3 +44,4 @@ def limited_parse_qsl( fields_limit: int | None = ..., ) -> list[tuple[str, str]]: ... def escape_leading_slashes(url: str) -> str: ... +def parse_header_parameters(line: str) -> tuple[str, dict[str, str]]: ... From e7fa48dbda79128b21512e812a21febca24f1b8a Mon Sep 17 00:00:00 2001 From: NorthIsUp Date: Mon, 31 Aug 2026 15:27:41 -0700 Subject: [PATCH 2/6] Add pyright tests for the missing symbols Each import fails on main and resolves with the change. --- tests/pyright/test_missing_symbols.py | 98 +++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 tests/pyright/test_missing_symbols.py diff --git a/tests/pyright/test_missing_symbols.py b/tests/pyright/test_missing_symbols.py new file mode 100644 index 000000000..400d0a74a --- /dev/null +++ b/tests/pyright/test_missing_symbols.py @@ -0,0 +1,98 @@ +from .base import Result, run_pyright + + +def test_async_test_client_is_importable() -> None: + """An async test suite imports AsyncClient from django.test, as the docs show. + + Both AsyncClient and AsyncRequestFactory are defined in django/test/client.pyi + but were never re-exported from the package, so the import itself was rejected + and every annotation using them degraded to Unknown. + """ + results = run_pyright( + """\ +from django.test import AsyncClient, AsyncRequestFactory + +reveal_type(AsyncClient) +reveal_type(AsyncRequestFactory) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_http_response_base_is_importable() -> None: + """Middleware and view code annotates against HttpResponseBase. + + It is the common base of HttpResponse and StreamingHttpResponse, so it is the + honest annotation for anything that may return either. It is defined in + http/response.pyi but was not re-exported from django.http, which is where + Django's own docs import it from. + """ + results = run_pyright( + """\ +from django.http import HttpResponseBase + +def handler() -> HttpResponseBase: ... +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_capture_on_commit_callbacks() -> None: + """A test asserts on work deferred with transaction.on_commit. + + TestCase wraps each test in a transaction that never commits, so on_commit + callbacks never fire; captureOnCommitCallbacks(execute=True) is the documented + way to run them. It has existed since Django 3.2 and was absent from the stub. + """ + results = run_pyright( + """\ +from django.test import TestCase + +class Foo(TestCase): + def test_it(self) -> None: + with self.captureOnCommitCallbacks(execute=True) as callbacks: + reveal_type(callbacks) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_storage_handler_is_importable() -> None: + """Code reads a non-default storage backend by its STORAGES alias. + + Django 4.2 replaced get_storage_class with the storages registry, so + storages["uploads"] is now the supported way to reach a configured backend, + and InvalidStorageError is what it raises for an unknown alias. Neither was + in the stub. + """ + results = run_pyright( + """\ +from django.core.files.storage import InvalidStorageError, Storage, storages + +def get(alias: str) -> Storage: + try: + return storages[alias] + except InvalidStorageError: + raise +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_parse_header_parameters_is_importable() -> None: + """A request handler splits a Content-Type header into its value and params. + + parse_header_parameters is Django's public helper for this - it is what + Django's own multipart parser and FileResponse use - and it was missing from + the django.utils.http stub. + """ + results = run_pyright( + """\ +from django.utils.http import parse_header_parameters + +value, params = parse_header_parameters("text/html; charset=utf-8") +reveal_type(value) +reveal_type(params) +""" + ) + assert [r for r in results if r.type == "error"] == [] From 3cf6a76be1aa752e193fee3f7d7401437b6750d3 Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Wed, 2 Sep 2026 09:25:19 -0700 Subject: [PATCH 3/6] Add AdminSite.get_model_admin Django 5.0 added it as the supported way to reach a registered ModelAdmin, so callers stop reaching into the private _registry dict. The stub declared is_registered but not this. --- django-stubs/contrib/admin/sites.pyi | 1 + tests/pyright/test_missing_symbols.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/django-stubs/contrib/admin/sites.pyi b/django-stubs/contrib/admin/sites.pyi index 044c94c54..ba8e7be11 100644 --- a/django-stubs/contrib/admin/sites.pyi +++ b/django-stubs/contrib/admin/sites.pyi @@ -40,6 +40,7 @@ class AdminSite: ) -> None: ... def unregister(self, model_or_iterable: type[Model] | Iterable[type[Model]]) -> None: ... def is_registered(self, model: type[Model]) -> bool: ... + def get_model_admin(self, model: type[Model]) -> ModelAdmin[Any]: ... def add_action(self, action: Callable[..., Any], name: str | None = ...) -> None: ... def disable_action(self, name: str) -> None: ... def get_action(self, name: str) -> Callable[..., Any]: ... diff --git a/tests/pyright/test_missing_symbols.py b/tests/pyright/test_missing_symbols.py index 400d0a74a..aca413426 100644 --- a/tests/pyright/test_missing_symbols.py +++ b/tests/pyright/test_missing_symbols.py @@ -96,3 +96,23 @@ def test_parse_header_parameters_is_importable() -> None: """ ) assert [r for r in results if r.type == "error"] == [] + + +def test_admin_site_get_model_admin() -> None: + """A test asserts which bulk actions a model's admin exposes. + + AdminSite.get_model_admin is the supported way to reach a registered + ModelAdmin - Django added it in 5.0 precisely so callers stop reading the + private _registry dict - but the stub only declared is_registered, so the + lookup failed to resolve at all. + """ + results = run_pyright( + """\ +from django.contrib.admin.sites import site +from django.contrib.auth.models import User + +model_admin = site.get_model_admin(User) +reveal_type(model_admin) +""" + ) + assert [r for r in results if r.type == "error"] == [] From 399696be5d8d8668bf9d8cd16f44e62e8531fc7c Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Wed, 2 Sep 2026 11:07:17 -0700 Subject: [PATCH 4/6] Add HttpResponseBase.__contains__ Django aliases it to has_header, so `"Retry-After" in response` is the documented spelling. The stub declared only has_header, forcing call sites to be rewritten around the missing dunder. --- django-stubs/http/response.pyi | 1 + tests/pyright/test_missing_symbols.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/django-stubs/http/response.pyi b/django-stubs/http/response.pyi index a2d2aab5b..96073ce5c 100644 --- a/django-stubs/http/response.pyi +++ b/django-stubs/http/response.pyi @@ -40,6 +40,7 @@ class HttpResponseBase: def __delitem__(self, header: str | bytes) -> None: ... def __getitem__(self, header: str | bytes) -> str: ... def has_header(self, header: str) -> bool: ... + def __contains__(self, header: str) -> bool: ... def items(self) -> Iterable[tuple[str, str]]: ... @overload def get(self, header: str | bytes, alternate: str | None) -> str: ... diff --git a/tests/pyright/test_missing_symbols.py b/tests/pyright/test_missing_symbols.py index aca413426..fba953a97 100644 --- a/tests/pyright/test_missing_symbols.py +++ b/tests/pyright/test_missing_symbols.py @@ -116,3 +116,21 @@ def test_admin_site_get_model_admin() -> None: """ ) assert [r for r in results if r.type == "error"] == [] + + +def test_http_response_supports_in() -> None: + """A test asserts a header is present with `in`, the way Django documents it. + + HttpResponseBase aliases __contains__ to has_header, so `"Retry-After" in + response` is the idiomatic spelling. The stub declared only has_header, so + the `in` form was rejected and call sites had to be rewritten around it. + """ + results = run_pyright( + """\ +from django.http import HttpResponse + +response = HttpResponse() +reveal_type("Retry-After" in response) +""" + ) + assert [r for r in results if r.type == "error"] == [] From 7e064b359f4a24cfa5e6971f1fb6ed813cac063e Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 12:43:46 -0700 Subject: [PATCH 5/6] Satisfy the repo's lint: import order, Generator, unused import ruff sorts the re-export blocks, @contextmanager wants Generator rather than Iterator, and the missing-symbols tests never used Result. --- django-stubs/core/files/storage.pyi | 2 +- django-stubs/http/__init__.pyi | 2 +- django-stubs/test/__init__.pyi | 4 ++-- django-stubs/test/testcases.pyi | 4 ++-- tests/pyright/test_missing_symbols.py | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/django-stubs/core/files/storage.pyi b/django-stubs/core/files/storage.pyi index 963e31343..73b4b5de7 100644 --- a/django-stubs/core/files/storage.pyi +++ b/django-stubs/core/files/storage.pyi @@ -1,7 +1,7 @@ -from django.core.exceptions import ImproperlyConfigured from datetime import datetime from typing import IO, Any +from django.core.exceptions import ImproperlyConfigured from django.core.files.base import File from django.utils.functional import LazyObject diff --git a/django-stubs/http/__init__.pyi b/django-stubs/http/__init__.pyi index 748ac198b..f71489dd2 100644 --- a/django-stubs/http/__init__.pyi +++ b/django-stubs/http/__init__.pyi @@ -7,9 +7,9 @@ from .request import UnreadablePostError as UnreadablePostError from .response import BadHeaderError as BadHeaderError from .response import FileResponse as FileResponse from .response import Http404 as Http404 -from .response import HttpResponseBase as HttpResponseBase from .response import HttpResponse as HttpResponse from .response import HttpResponseBadRequest as HttpResponseBadRequest +from .response import HttpResponseBase as HttpResponseBase from .response import HttpResponseForbidden as HttpResponseForbidden from .response import HttpResponseGone as HttpResponseGone from .response import HttpResponseNotAllowed as HttpResponseNotAllowed diff --git a/django-stubs/test/__init__.pyi b/django-stubs/test/__init__.pyi index f6a535be8..c439f00d5 100644 --- a/django-stubs/test/__init__.pyi +++ b/django-stubs/test/__init__.pyi @@ -1,7 +1,7 @@ -from .client import Client as Client -from .client import RequestFactory as RequestFactory from .client import AsyncClient as AsyncClient from .client import AsyncRequestFactory as AsyncRequestFactory +from .client import Client as Client +from .client import RequestFactory as RequestFactory from .testcases import LiveServerTestCase as LiveServerTestCase from .testcases import SimpleTestCase as SimpleTestCase from .testcases import TestCase as TestCase diff --git a/django-stubs/test/testcases.pyi b/django-stubs/test/testcases.pyi index 9da170439..08bad0e4c 100644 --- a/django-stubs/test/testcases.pyi +++ b/django-stubs/test/testcases.pyi @@ -1,6 +1,6 @@ import threading import unittest -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Generator, Iterable from contextlib import contextmanager from types import TracebackType from typing import Any, ClassVar, TypeVar, overload @@ -216,7 +216,7 @@ class TestCase(TransactionTestCase): @contextmanager def captureOnCommitCallbacks( cls, *, using: str = ..., execute: bool = ... - ) -> Iterator[list[Callable[[], Any]]]: ... + ) -> Generator[list[Callable[[], Any]]]: ... @classmethod def setUpTestData(cls) -> None: ... diff --git a/tests/pyright/test_missing_symbols.py b/tests/pyright/test_missing_symbols.py index fba953a97..743ca86aa 100644 --- a/tests/pyright/test_missing_symbols.py +++ b/tests/pyright/test_missing_symbols.py @@ -1,4 +1,4 @@ -from .base import Result, run_pyright +from .base import run_pyright def test_async_test_client_is_importable() -> None: From 4528ad83d9df2727cd6e90400c113ba90a050783 Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 13:42:00 -0700 Subject: [PATCH 6/6] Match Django 6.0's parse_header_parameters and StorageHandler.backends parse_header_parameters takes max_length (default 10000); backends is a cached_property, as it is at runtime and as the other stubs declare it. --- django-stubs/core/files/storage.pyi | 4 +- django-stubs/utils/http.pyi | 2 +- tests/pyright/test_missing_symbols.py | 54 ++++----------------------- 3 files changed, 11 insertions(+), 49 deletions(-) diff --git a/django-stubs/core/files/storage.pyi b/django-stubs/core/files/storage.pyi index 73b4b5de7..b346567c2 100644 --- a/django-stubs/core/files/storage.pyi +++ b/django-stubs/core/files/storage.pyi @@ -3,7 +3,7 @@ from typing import IO, Any from django.core.exceptions import ImproperlyConfigured from django.core.files.base import File -from django.utils.functional import LazyObject +from django.utils.functional import LazyObject, cached_property class Storage: def open(self, name: str, mode: str = ...) -> File: ... @@ -53,7 +53,7 @@ class StorageHandler: def __init__(self, backends: dict[str, dict[str, Any]] | None = ...) -> None: ... def __getitem__(self, alias: str) -> Storage: ... def create_storage(self, params: dict[str, Any]) -> Storage: ... - @property + @cached_property def backends(self) -> dict[str, dict[str, Any]]: ... storages: StorageHandler diff --git a/django-stubs/utils/http.pyi b/django-stubs/utils/http.pyi index e637e4cef..8c78d2866 100644 --- a/django-stubs/utils/http.pyi +++ b/django-stubs/utils/http.pyi @@ -44,4 +44,4 @@ def limited_parse_qsl( fields_limit: int | None = ..., ) -> list[tuple[str, str]]: ... def escape_leading_slashes(url: str) -> str: ... -def parse_header_parameters(line: str) -> tuple[str, dict[str, str]]: ... +def parse_header_parameters(line: str, max_length: int = ...) -> tuple[str, dict[str, str]]: ... diff --git a/tests/pyright/test_missing_symbols.py b/tests/pyright/test_missing_symbols.py index 743ca86aa..12eeb65ce 100644 --- a/tests/pyright/test_missing_symbols.py +++ b/tests/pyright/test_missing_symbols.py @@ -2,12 +2,7 @@ def test_async_test_client_is_importable() -> None: - """An async test suite imports AsyncClient from django.test, as the docs show. - - Both AsyncClient and AsyncRequestFactory are defined in django/test/client.pyi - but were never re-exported from the package, so the import itself was rejected - and every annotation using them degraded to Unknown. - """ + """An async test suite imports AsyncClient from django.test, as the docs show.""" results = run_pyright( """\ from django.test import AsyncClient, AsyncRequestFactory @@ -20,13 +15,7 @@ def test_async_test_client_is_importable() -> None: def test_http_response_base_is_importable() -> None: - """Middleware and view code annotates against HttpResponseBase. - - It is the common base of HttpResponse and StreamingHttpResponse, so it is the - honest annotation for anything that may return either. It is defined in - http/response.pyi but was not re-exported from django.http, which is where - Django's own docs import it from. - """ + """Middleware and view code annotates against HttpResponseBase.""" results = run_pyright( """\ from django.http import HttpResponseBase @@ -38,12 +27,7 @@ def handler() -> HttpResponseBase: ... def test_capture_on_commit_callbacks() -> None: - """A test asserts on work deferred with transaction.on_commit. - - TestCase wraps each test in a transaction that never commits, so on_commit - callbacks never fire; captureOnCommitCallbacks(execute=True) is the documented - way to run them. It has existed since Django 3.2 and was absent from the stub. - """ + """A test asserts on work deferred with transaction.on_commit.""" results = run_pyright( """\ from django.test import TestCase @@ -58,13 +42,7 @@ def test_it(self) -> None: def test_storage_handler_is_importable() -> None: - """Code reads a non-default storage backend by its STORAGES alias. - - Django 4.2 replaced get_storage_class with the storages registry, so - storages["uploads"] is now the supported way to reach a configured backend, - and InvalidStorageError is what it raises for an unknown alias. Neither was - in the stub. - """ + """Code reads a non-default storage backend by its STORAGES alias.""" results = run_pyright( """\ from django.core.files.storage import InvalidStorageError, Storage, storages @@ -80,17 +58,12 @@ def get(alias: str) -> Storage: def test_parse_header_parameters_is_importable() -> None: - """A request handler splits a Content-Type header into its value and params. - - parse_header_parameters is Django's public helper for this - it is what - Django's own multipart parser and FileResponse use - and it was missing from - the django.utils.http stub. - """ + """A request handler splits a Content-Type header into its value and params.""" results = run_pyright( """\ from django.utils.http import parse_header_parameters -value, params = parse_header_parameters("text/html; charset=utf-8") +value, params = parse_header_parameters("text/html; charset=utf-8", max_length=4096) reveal_type(value) reveal_type(params) """ @@ -99,13 +72,7 @@ def test_parse_header_parameters_is_importable() -> None: def test_admin_site_get_model_admin() -> None: - """A test asserts which bulk actions a model's admin exposes. - - AdminSite.get_model_admin is the supported way to reach a registered - ModelAdmin - Django added it in 5.0 precisely so callers stop reading the - private _registry dict - but the stub only declared is_registered, so the - lookup failed to resolve at all. - """ + """A test asserts which bulk actions a model's admin exposes.""" results = run_pyright( """\ from django.contrib.admin.sites import site @@ -119,12 +86,7 @@ def test_admin_site_get_model_admin() -> None: def test_http_response_supports_in() -> None: - """A test asserts a header is present with `in`, the way Django documents it. - - HttpResponseBase aliases __contains__ to has_header, so `"Retry-After" in - response` is the idiomatic spelling. The stub declared only has_header, so - the `in` form was rejected and call sites had to be rewritten around it. - """ + """A test asserts a header is present with `in`, the way Django documents it.""" results = run_pyright( """\ from django.http import HttpResponse