From dd334b8ba4a6e430e2f3fbc5d1c90b9df26501c1 Mon Sep 17 00:00:00 2001 From: NorthIsUp Date: Mon, 31 Aug 2026 15:13:44 -0700 Subject: [PATCH 1/7] Correct signatures that misdescribe Django's own API Each checked against the runtime it describes. - BaseDatabaseOperations.sql_flush: was (style: None, tables: None, sequences: None) -> Any; Django takes (style: Style, tables, *, reset_sequences, allow_cascade) and returns list[str]. - MigrationLoader.__init__: add replace_migrations. - View.dispatch -> HttpResponseBase: a view may return StreamingHttpResponse or FileResponse, neither of which is an HttpResponse. - ChangeList.get_query_string: new_params holds the values to encode. - Model.refresh_from_db/arefresh_from_db: fields takes any iterable of names. - URLResolver.url_patterns: list[URLPattern | URLResolver] - include() nests resolvers, so the list is heterogeneous. - MultiValueDict.__getitem__ returns the last value; getlist() returns the list. - Client.generic: Client runs the request through the handler, so it returns a response like every other verb on it, not RequestFactory's WSGIRequest. - StreamingHttpResponse accepts str chunks; Django encodes them. - Session encode/save/get_decoded: the payload is heterogeneous - Django itself stores _auth_user_id as a str via value_to_string - so dict[str, int] is wrong for every key. --- django-stubs/contrib/admin/views/main.pyi | 2 +- django-stubs/contrib/sessions/base_session.pyi | 8 ++++---- django-stubs/db/backends/base/operations.pyi | 4 +++- django-stubs/db/migrations/loader.pyi | 8 +++++++- django-stubs/db/models/base.pyi | 4 ++-- django-stubs/http/response.pyi | 4 ++-- django-stubs/test/client.pyi | 12 ++++++++++++ django-stubs/urls/resolvers.pyi | 2 +- django-stubs/utils/datastructures.pyi | 2 +- django-stubs/views/generic/base.pyi | 2 +- 10 files changed, 34 insertions(+), 14 deletions(-) diff --git a/django-stubs/contrib/admin/views/main.pyi b/django-stubs/contrib/admin/views/main.pyi index 467133319..7b3ec02af 100644 --- a/django-stubs/contrib/admin/views/main.pyi +++ b/django-stubs/contrib/admin/views/main.pyi @@ -69,7 +69,7 @@ class ChangeList: def get_filters(self, request: HttpRequest) -> tuple[list[ListFilter], bool, dict[str, bool | str], bool]: ... def get_query_string( self, - new_params: dict[str, None] | None = ..., + new_params: dict[str, Any] | None = ..., remove: list[str] | None = ..., ) -> str: ... result_count: Any = ... diff --git a/django-stubs/contrib/sessions/base_session.pyi b/django-stubs/contrib/sessions/base_session.pyi index d45c75804..e160bf821 100644 --- a/django-stubs/contrib/sessions/base_session.pyi +++ b/django-stubs/contrib/sessions/base_session.pyi @@ -1,5 +1,5 @@ from datetime import datetime -from typing import ClassVar, TypeVar +from typing import Any, ClassVar, TypeVar from django.contrib.sessions.backends.base import SessionBase from django.db import models @@ -8,8 +8,8 @@ from typing_extensions import Self _SessionT = TypeVar("_SessionT", bound=AbstractBaseSession) class BaseSessionManager(models.Manager[_SessionT]): - def encode(self, session_dict: dict[str, int]) -> str: ... - def save(self, session_key: str, session_dict: dict[str, int], expire_date: datetime) -> _SessionT: ... + def encode(self, session_dict: dict[str, Any]) -> str: ... + def save(self, session_key: str, session_dict: dict[str, Any], expire_date: datetime) -> _SessionT: ... class AbstractBaseSession(models.Model): objects: ClassVar[BaseSessionManager[Self]] # pyright: ignore[reportIncompatibleVariableOverride] @@ -25,4 +25,4 @@ class AbstractBaseSession(models.Model): @classmethod def get_session_store_class(cls) -> type[SessionBase] | None: ... - def get_decoded(self) -> dict[str, int]: ... + def get_decoded(self) -> dict[str, Any]: ... diff --git a/django-stubs/db/backends/base/operations.pyi b/django-stubs/db/backends/base/operations.pyi index 05b1923b9..6ba4ffa48 100644 --- a/django-stubs/db/backends/base/operations.pyi +++ b/django-stubs/db/backends/base/operations.pyi @@ -65,7 +65,9 @@ class BaseDatabaseOperations: def savepoint_commit_sql(self, sid: str) -> str: ... def savepoint_rollback_sql(self, sid: str) -> str: ... def set_time_zone_sql(self) -> str: ... - def sql_flush(self, style: None, tables: None, sequences: None, allow_cascade: bool = ...) -> Any: ... + def sql_flush( + self, style: Style, tables: list[str], *, reset_sequences: bool = ..., allow_cascade: bool = ... + ) -> list[str]: ... def execute_sql_flush(self, using: str, sql_list: list[str]) -> None: ... def sequence_reset_by_name_sql(self, style: None, sequences: list[Any]) -> list[Any]: ... def sequence_reset_sql(self, style: Style, model_list: Sequence[type[Model]]) -> list[Any]: ... diff --git a/django-stubs/db/migrations/loader.pyi b/django-stubs/db/migrations/loader.pyi index 4cb1f46b2..6dab45857 100644 --- a/django-stubs/db/migrations/loader.pyi +++ b/django-stubs/db/migrations/loader.pyi @@ -16,7 +16,13 @@ class MigrationLoader: disk_migrations: dict[tuple[str, str], Migration] = ... applied_migrations: set[tuple[str, str]] = ... ignore_no_migrations: bool = ... - def __init__(self, connection: Any, load: bool = ..., ignore_no_migrations: bool = ...) -> None: ... + def __init__( + self, + connection: Any, + load: bool = ..., + ignore_no_migrations: bool = ..., + replace_migrations: bool = ..., + ) -> None: ... @classmethod def migrations_module(cls, app_label: str) -> tuple[str | None, bool]: ... unmigrated_apps: set[str] = ... diff --git a/django-stubs/db/models/base.pyi b/django-stubs/db/models/base.pyi index 6a792529d..78220d49d 100644 --- a/django-stubs/db/models/base.pyi +++ b/django-stubs/db/models/base.pyi @@ -80,13 +80,13 @@ class Model(metaclass=ModelBase): def refresh_from_db( self, using: str | None = ..., - fields: list[str] | None = ..., + fields: Iterable[str] | None = ..., from_queryset: QuerySet[Self] | None = ..., ) -> None: ... async def arefresh_from_db( self, using: str | None = ..., - fields: list[str] | None = ..., + fields: Iterable[str] | None = ..., from_queryset: QuerySet[Self] | None = ..., ) -> None: ... def get_deferred_fields(self) -> set[str]: ... diff --git a/django-stubs/http/response.pyi b/django-stubs/http/response.pyi index a2d2aab5b..f5c49975e 100644 --- a/django-stubs/http/response.pyi +++ b/django-stubs/http/response.pyi @@ -100,9 +100,9 @@ class HttpResponse(HttpResponseBase, Iterable[bytes]): class StreamingHttpResponse(HttpResponseBase, Iterable[bytes], AsyncIterable[bytes]): streaming: bool - streaming_content: Iterable[bytes] | AsyncIterable[bytes] + streaming_content: Iterable[bytes | str] | AsyncIterable[bytes | str] def __init__( - self, streaming_content: Iterable[bytes] | AsyncIterable[bytes] = ..., *args: Any, **kwargs: Any + self, streaming_content: Iterable[bytes | str] | AsyncIterable[bytes | str] = ..., *args: Any, **kwargs: Any ) -> None: ... def getvalue(self) -> bytes: ... @property diff --git a/django-stubs/test/client.pyi b/django-stubs/test/client.pyi index 07d52e72c..0cef1d6ed 100644 --- a/django-stubs/test/client.pyi +++ b/django-stubs/test/client.pyi @@ -281,6 +281,18 @@ class Client(ClientMixin, RequestFactory): query_params: str | None = ..., **extra: str, ) -> HttpResponse: ... + def generic( # type: ignore [override] + self, + method: str, + path: _StrOrPromise, + data: _RequestData = ..., + content_type: str | None = ..., + secure: bool = ..., + *, + headers: Mapping[str, Any] | None = ..., + query_params: str | None = ..., + **extra: str, + ) -> HttpResponse: ... def trace( # type: ignore [override] self, path: _StrOrPromise, diff --git a/django-stubs/urls/resolvers.pyi b/django-stubs/urls/resolvers.pyi index 5ff4605da..df31c11df 100644 --- a/django-stubs/urls/resolvers.pyi +++ b/django-stubs/urls/resolvers.pyi @@ -85,7 +85,7 @@ class URLPattern: def resolve(self, path: str) -> ResolverMatch | None: ... class URLResolver: - url_patterns: list[tuple[str, Callable[..., Any]]] + url_patterns: list[URLPattern | URLResolver] urlconf_module: list[tuple[str, Callable[..., Any]]] | None pattern: Any = ... urlconf_name: str | None = ... diff --git a/django-stubs/utils/datastructures.pyi b/django-stubs/utils/datastructures.pyi index bb36ca9d2..a36999942 100644 --- a/django-stubs/utils/datastructures.pyi +++ b/django-stubs/utils/datastructures.pyi @@ -61,7 +61,7 @@ class MultiValueDict(dict[_K, _V]): @overload def __init__(self, key_to_list_mapping: Iterable[tuple[_K, list[_V]]] = ()) -> None: ... @override - def __getitem__(self, key: _K) -> _V | list[object]: ... # type: ignore[override] + def __getitem__(self, key: _K) -> _V: ... # type: ignore[override] @override def __setitem__(self, key: _K, value: _V) -> None: ... def __copy__(self) -> Self: ... diff --git a/django-stubs/views/generic/base.pyi b/django-stubs/views/generic/base.pyi index 55139f3fc..abf7488cb 100644 --- a/django-stubs/views/generic/base.pyi +++ b/django-stubs/views/generic/base.pyi @@ -15,7 +15,7 @@ class View: @classmethod def as_view(cls, **initkwargs: Any) -> Callable[..., http.HttpResponse]: ... def setup(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> None: ... - def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... + def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponseBase: ... def http_method_not_allowed(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... def options(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... From 4f2859ccc89ed1bf36776177b7596a39b186327d Mon Sep 17 00:00:00 2001 From: NorthIsUp Date: Mon, 31 Aug 2026 15:29:41 -0700 Subject: [PATCH 2/7] Add pyright tests for the signature corrections Six tests, each failing on main and passing with the change: Client.generic returning a response, url_patterns holding resolvers, QueryDict[...] giving a value rather than a union, str chunks into StreamingHttpResponse, a heterogeneous session payload, and refresh_from_db taking any iterable. View.dispatch is not covered: the change widens the return to HttpResponseBase, and this repo sets reportIncompatibleMethodOverride to false, so no test here discriminates. --- tests/pyright/test_signatures.py | 122 +++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 tests/pyright/test_signatures.py diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py new file mode 100644 index 000000000..61a8081eb --- /dev/null +++ b/tests/pyright/test_signatures.py @@ -0,0 +1,122 @@ +from .base import Result, run_pyright + + +def test_client_generic_returns_a_response() -> None: + """A test sends a verb the Client has no named helper for - PATCH, or a + content-type negotiation case - via client.generic(). + + Client overrides get/post/head/options/put/patch/delete/trace to return a + response, but not generic(), so it inherited RequestFactory.generic() and the + result typed as a WSGIRequest. Every .status_code and .content on it was then + an unknown attribute of a request object. + """ + results = run_pyright( + """\ +from django.test import Client + +client = Client() +response = client.generic("PATCH", "/x/", data=b"{}", content_type="application/json") +reveal_type(response.status_code) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_url_patterns_is_heterogeneous() -> None: + """A URL-introspection helper walks the resolver tree to enumerate routes. + + include() nests a URLResolver inside url_patterns, so walking it means + branching on URLResolver vs URLPattern. The stub declared the list as + list[tuple[str, Callable]], which matches neither. + """ + results = run_pyright( + """\ +from django.urls import get_resolver +from django.urls.resolvers import URLResolver + +for entry in get_resolver().url_patterns: + if isinstance(entry, URLResolver): + reveal_type(entry.namespace) + else: + reveal_type(entry.name) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_multivaluedict_getitem_returns_the_value() -> None: + """A view reads a single query parameter and converts it. + + QueryDict[...] returns the last value for the key; getlist() is the API that + returns every value. The stub returned the union of both, so int(params["pk"]) + was rejected on the list arm that subscripting never produces. + """ + results = run_pyright( + """\ +from django.http import QueryDict + +def read(params: QueryDict) -> int: + return int(params["pk"]) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_streaming_response_accepts_str_chunks() -> None: + """A view streams rendered text - SSE, CSV, NDJSON - a chunk at a time. + + StreamingHttpResponse encodes str chunks itself, so yielding str is ordinary + usage, but the stub accepted only bytes. + """ + results = run_pyright( + """\ +from django.http import StreamingHttpResponse + +StreamingHttpResponse(iter(["a", "b"])) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_session_payload_is_heterogeneous() -> None: + """One decoded session holds several unrelated value types at once. + + Django itself writes _auth_user_id as a str (pk.value_to_string), + _session_expiry as an int and _auth_user_backend as a str, and any installed + app adds keys of its own. So no single value type fits - the stub said + dict[str, int], wrong for two of the three keys Django writes - and there is + no union to close over, because the key space is open. This test is what a + narrower annotation would have to satisfy. + """ + results = run_pyright( + """\ +from django.contrib.sessions.base_session import AbstractBaseSession + +def read(session: AbstractBaseSession) -> tuple[str, int, list[dict[str, int]]]: + data = session.get_decoded() + user_id: str = data["_auth_user_id"] + expiry: int = data["_session_expiry"] + cart: list[dict[str, int]] = data["myapp_cart"] + return user_id, expiry, cart +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_refresh_from_db_takes_any_iterable() -> None: + """A caller refreshes a named subset of fields, passing a tuple. + + The field names are a fixed set at the call site, so a tuple is the natural + literal; the stub required list[str] specifically. + """ + results = run_pyright( + """\ +from django.db import models + +class Foo(models.Model): + pass + +Foo().refresh_from_db(fields=("a", "b")) +""" + ) + assert [r for r in results if r.type == "error"] == [] From 0dfe69f0d9faa24d3ca6a2d7b73c4500ff2bb7fc Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 11:52:24 -0700 Subject: [PATCH 3/7] Accept callable choices and the questioner's verbosity/log Django 5.0 lets a field take a choices callable so a new member needs no migration; Field.choices allowed one but the per-field __new__ overloads did not. NonInteractiveMigrationQuestioner also takes verbosity and log, which the stub dropped by declaring the subclass as a bare ellipsis. --- django-stubs/db/migrations/questioner.pyi | 13 +++++- django-stubs/db/models/fields/__init__.pyi | 51 ++++++++++++++-------- tests/pyright/test_signatures.py | 43 ++++++++++++++++++ 3 files changed, 89 insertions(+), 18 deletions(-) diff --git a/django-stubs/db/migrations/questioner.pyi b/django-stubs/db/migrations/questioner.pyi index f7865344e..69dec2827 100644 --- a/django-stubs/db/migrations/questioner.pyi +++ b/django-stubs/db/migrations/questioner.pyi @@ -1,3 +1,4 @@ +from collections.abc import Callable from typing import Any from django.db.migrations.state import ModelState @@ -28,4 +29,14 @@ class MigrationQuestioner: def ask_auto_now_add_addition(self, field_name: str, model_name: str) -> None: ... class InteractiveMigrationQuestioner(MigrationQuestioner): ... -class NonInteractiveMigrationQuestioner(MigrationQuestioner): ... +class NonInteractiveMigrationQuestioner(MigrationQuestioner): + verbosity: int + log: Callable[[str], None] | None + def __init__( + self, + defaults: dict[str, bool] | None = ..., + specified_apps: set[str] | None = ..., + dry_run: bool | None = ..., + verbosity: int = ..., + log: Callable[[str], None] | None = ..., + ) -> None: ... diff --git a/django-stubs/db/models/fields/__init__.pyi b/django-stubs/db/models/fields/__init__.pyi index 8ef9e05b5..499668401 100644 --- a/django-stubs/db/models/fields/__init__.pyi +++ b/django-stubs/db/models/fields/__init__.pyi @@ -139,7 +139,8 @@ class IntegerField(Field[_I | Combinable, _I], Generic[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -168,7 +169,8 @@ class IntegerField(Field[_I | Combinable, _I], Generic[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -202,7 +204,8 @@ class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -231,7 +234,8 @@ class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -262,7 +266,8 @@ class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]) unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -291,7 +296,8 @@ class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]) unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -322,7 +328,8 @@ class SmallIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -351,7 +358,8 @@ class SmallIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -382,7 +390,8 @@ class BigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -411,7 +420,8 @@ class BigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -442,7 +452,8 @@ class PositiveBigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -471,7 +482,8 @@ class PositiveBigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -632,7 +644,8 @@ class AutoField(AutoFieldMixin, IntegerField[int], metaclass=AutoFieldMeta): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -663,7 +676,8 @@ class BigAutoField(AutoFieldMixin, BigIntegerField[int]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -694,7 +708,8 @@ class SmallAutoField(AutoFieldMixin, SmallIntegerField[int]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] = ..., + | type[IntegerChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -728,7 +743,8 @@ class CharField(Field[_C | Combinable, _C], Generic[_C]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_C, _StrOrPromise] | tuple[str, Iterable[tuple[_C, _StrOrPromise]]]] - | type[TextChoices] = ..., + | type[TextChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -758,7 +774,8 @@ class CharField(Field[_C | Combinable, _C], Generic[_C]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_C, _StrOrPromise] | tuple[str, Iterable[tuple[_C, _StrOrPromise]]]] - | type[TextChoices] = ..., + | type[TextChoices] + | Callable[[], _LiteralFieldChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py index 61a8081eb..d711fe371 100644 --- a/tests/pyright/test_signatures.py +++ b/tests/pyright/test_signatures.py @@ -120,3 +120,46 @@ class Foo(models.Model): """ ) assert [r for r in results if r.type == "error"] == [] + + +def test_callable_field_choices() -> None: + """A choices callable keeps a new enum member from needing a migration. + + Django serializes the reference rather than the values, so a callable is the + documented way to avoid a migration per member. `Field.choices` already + admitted one; the per-field `__new__` overloads did not, so the supported + spelling was rejected at the only place it is ever written. + """ + results = run_pyright( + """\ +from django.db import models + +def flag_choices() -> list[tuple[str, str]]: + return [("a", "A")] + +class Foo(models.Model): + flag = models.CharField(max_length=64, choices=flag_choices) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_non_interactive_questioner_verbosity_and_log() -> None: + """A migration-graph check drives the autodetector and wants its reasons. + + NonInteractiveMigrationQuestioner takes `verbosity` and `log` so a caller can + route the field-level reason somewhere other than stdout. The stub declared + the subclass as a bare `...`, inheriting a base `__init__` without either. + """ + results = run_pyright( + """\ +from django.db.migrations.questioner import NonInteractiveMigrationQuestioner + +def _eprint(message: str) -> None: ... + +questioner = NonInteractiveMigrationQuestioner( + specified_apps=set(), dry_run=True, verbosity=1, log=_eprint +) +""" + ) + assert [r for r in results if r.type == "error"] == [] From 5b0c70bfcdc92f95920df9dcb057d7a53afe3d72 Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 12:46:17 -0700 Subject: [PATCH 4/7] Satisfy the repo's lint, and keep this PR self-contained base.pyi imported HttpResponseBase through django.http, which only re-exports it in the missing-symbols PR; import it from django.http.response so this one stands alone. The MultiValueDict override no longer needs its type: ignore, and the signature tests never used Result. --- django-stubs/db/migrations/questioner.pyi | 1 + django-stubs/utils/datastructures.pyi | 2 +- django-stubs/views/generic/base.pyi | 3 ++- tests/pyright/test_signatures.py | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/django-stubs/db/migrations/questioner.pyi b/django-stubs/db/migrations/questioner.pyi index 69dec2827..db20e5ec8 100644 --- a/django-stubs/db/migrations/questioner.pyi +++ b/django-stubs/db/migrations/questioner.pyi @@ -29,6 +29,7 @@ class MigrationQuestioner: def ask_auto_now_add_addition(self, field_name: str, model_name: str) -> None: ... class InteractiveMigrationQuestioner(MigrationQuestioner): ... + class NonInteractiveMigrationQuestioner(MigrationQuestioner): verbosity: int log: Callable[[str], None] | None diff --git a/django-stubs/utils/datastructures.pyi b/django-stubs/utils/datastructures.pyi index a36999942..392d364cd 100644 --- a/django-stubs/utils/datastructures.pyi +++ b/django-stubs/utils/datastructures.pyi @@ -61,7 +61,7 @@ class MultiValueDict(dict[_K, _V]): @overload def __init__(self, key_to_list_mapping: Iterable[tuple[_K, list[_V]]] = ()) -> None: ... @override - def __getitem__(self, key: _K) -> _V: ... # type: ignore[override] + def __getitem__(self, key: _K) -> _V: ... @override def __setitem__(self, key: _K, value: _V) -> None: ... def __copy__(self) -> Self: ... diff --git a/django-stubs/views/generic/base.pyi b/django-stubs/views/generic/base.pyi index abf7488cb..228fc063a 100644 --- a/django-stubs/views/generic/base.pyi +++ b/django-stubs/views/generic/base.pyi @@ -2,6 +2,7 @@ from collections.abc import Callable from typing import Any import django.http as http +from django.http.response import HttpResponseBase class ContextMixin: def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... @@ -15,7 +16,7 @@ class View: @classmethod def as_view(cls, **initkwargs: Any) -> Callable[..., http.HttpResponse]: ... def setup(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> None: ... - def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponseBase: ... + def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ... def http_method_not_allowed(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... def options(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py index d711fe371..d0d6c62f9 100644 --- a/tests/pyright/test_signatures.py +++ b/tests/pyright/test_signatures.py @@ -1,4 +1,4 @@ -from .base import Result, run_pyright +from .base import run_pyright def test_client_generic_returns_a_response() -> None: From 3b5d5bba414dfc65fae59b076b32b278ebb00bec Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 13:19:41 -0700 Subject: [PATCH 5/7] Hand the choices change to its own PR The callable-choices widening was one third of a wider gap (dict and Choices class on most fields were rejected too), so it moves to a PR that fixes all of it and closes the two open issues about it. --- django-stubs/db/models/fields/__init__.pyi | 51 ++++++++-------------- tests/pyright/test_signatures.py | 22 ---------- 2 files changed, 17 insertions(+), 56 deletions(-) diff --git a/django-stubs/db/models/fields/__init__.pyi b/django-stubs/db/models/fields/__init__.pyi index 499668401..8ef9e05b5 100644 --- a/django-stubs/db/models/fields/__init__.pyi +++ b/django-stubs/db/models/fields/__init__.pyi @@ -139,8 +139,7 @@ class IntegerField(Field[_I | Combinable, _I], Generic[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -169,8 +168,7 @@ class IntegerField(Field[_I | Combinable, _I], Generic[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -204,8 +202,7 @@ class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -234,8 +231,7 @@ class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -266,8 +262,7 @@ class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]) unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -296,8 +291,7 @@ class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_I]) unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -328,8 +322,7 @@ class SmallIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -358,8 +351,7 @@ class SmallIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -390,8 +382,7 @@ class BigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -420,8 +411,7 @@ class BigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -452,8 +442,7 @@ class PositiveBigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -482,8 +471,7 @@ class PositiveBigIntegerField(IntegerField[_I]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_I, _StrOrPromise] | tuple[str, Iterable[tuple[_I, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -644,8 +632,7 @@ class AutoField(AutoFieldMixin, IntegerField[int], metaclass=AutoFieldMeta): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -676,8 +663,7 @@ class BigAutoField(AutoFieldMixin, BigIntegerField[int]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -708,8 +694,7 @@ class SmallAutoField(AutoFieldMixin, SmallIntegerField[int]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[int, _StrOrPromise] | tuple[str, Iterable[tuple[int, _StrOrPromise]]]] - | type[IntegerChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[IntegerChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -743,8 +728,7 @@ class CharField(Field[_C | Combinable, _C], Generic[_C]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_C, _StrOrPromise] | tuple[str, Iterable[tuple[_C, _StrOrPromise]]]] - | type[TextChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[TextChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., @@ -774,8 +758,7 @@ class CharField(Field[_C | Combinable, _C], Generic[_C]): unique_for_month: str | None = ..., unique_for_year: str | None = ..., choices: Iterable[tuple[_C, _StrOrPromise] | tuple[str, Iterable[tuple[_C, _StrOrPromise]]]] - | type[TextChoices] - | Callable[[], _LiteralFieldChoices] = ..., + | type[TextChoices] = ..., help_text: _StrOrPromise = ..., db_column: str | None = ..., db_comment: str | None = ..., diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py index d0d6c62f9..fdf51e321 100644 --- a/tests/pyright/test_signatures.py +++ b/tests/pyright/test_signatures.py @@ -122,28 +122,6 @@ class Foo(models.Model): assert [r for r in results if r.type == "error"] == [] -def test_callable_field_choices() -> None: - """A choices callable keeps a new enum member from needing a migration. - - Django serializes the reference rather than the values, so a callable is the - documented way to avoid a migration per member. `Field.choices` already - admitted one; the per-field `__new__` overloads did not, so the supported - spelling was rejected at the only place it is ever written. - """ - results = run_pyright( - """\ -from django.db import models - -def flag_choices() -> list[tuple[str, str]]: - return [("a", "A")] - -class Foo(models.Model): - flag = models.CharField(max_length=64, choices=flag_choices) -""" - ) - assert [r for r in results if r.type == "error"] == [] - - def test_non_interactive_questioner_verbosity_and_log() -> None: """A migration-graph check drives the autodetector and wants its reasons. From 3b1a899704c131a0d1a027a670a92068a23d96bf Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 13:39:48 -0700 Subject: [PATCH 6/7] Keep dispatch and streaming reads as they were; fix query_params on every verb Returning HttpResponseBase from View.dispatch broke the usual override, so that row is withdrawn. streaming_content reads always yield bytes; only __init__ takes str chunks. The MultiValueDict row is #300's fix and Django does return [] for an empty list, so it is withdrawn too. query_params is a mapping Django urlencodes, on every verb of both clients and on generic(); AsyncClient inherits the same generic() bug as Client and gets the same override. --- django-stubs/http/response.pyi | 2 +- django-stubs/test/client.pyi | 64 ++++++++------ django-stubs/utils/datastructures.pyi | 2 +- django-stubs/views/generic/base.pyi | 3 +- tests/pyright/test_signatures.py | 118 +++++++++++++------------- 5 files changed, 102 insertions(+), 87 deletions(-) diff --git a/django-stubs/http/response.pyi b/django-stubs/http/response.pyi index f5c49975e..aaa2bd734 100644 --- a/django-stubs/http/response.pyi +++ b/django-stubs/http/response.pyi @@ -100,7 +100,7 @@ class HttpResponse(HttpResponseBase, Iterable[bytes]): class StreamingHttpResponse(HttpResponseBase, Iterable[bytes], AsyncIterable[bytes]): streaming: bool - streaming_content: Iterable[bytes | str] | AsyncIterable[bytes | str] + streaming_content: Iterable[bytes] | AsyncIterable[bytes] def __init__( self, streaming_content: Iterable[bytes | str] | AsyncIterable[bytes | str] = ..., *args: Any, **kwargs: Any ) -> None: ... diff --git a/django-stubs/test/client.pyi b/django-stubs/test/client.pyi index 0cef1d6ed..9de27bb04 100644 --- a/django-stubs/test/client.pyi +++ b/django-stubs/test/client.pyi @@ -78,7 +78,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def post( @@ -89,7 +89,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def head( @@ -99,7 +99,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def trace( @@ -108,7 +108,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def options( @@ -119,7 +119,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def put( @@ -130,7 +130,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def patch( @@ -141,7 +141,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def delete( @@ -152,7 +152,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... def generic( @@ -164,7 +164,7 @@ class RequestFactory: secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: object, ) -> WSGIRequest: ... @@ -207,7 +207,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def post( # type: ignore [override] @@ -219,7 +219,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def head( # type: ignore [override] @@ -230,7 +230,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def options( # type: ignore [override] @@ -242,7 +242,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def put( # type: ignore [override] @@ -254,7 +254,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def patch( # type: ignore [override] @@ -266,7 +266,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def delete( # type: ignore [override] @@ -278,7 +278,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def generic( # type: ignore [override] @@ -290,7 +290,7 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... def trace( # type: ignore [override] @@ -301,11 +301,23 @@ class Client(ClientMixin, RequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... class AsyncClient(ClientMixin, AsyncRequestFactory): + async def generic( # type: ignore [override] + self, + method: str, + path: _StrOrPromise, + data: _RequestData = ..., + content_type: str | None = ..., + secure: bool = ..., + *, + headers: Mapping[str, Any] | None = ..., + query_params: Mapping[str, Any] | None = ..., + **extra: str, + ) -> HttpResponse: ... handler: AsyncClientHandler raise_request_exception: bool exc_info: tuple[type[BaseException], BaseException, TracebackType] | None @@ -330,7 +342,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def post( # type: ignore [override] @@ -342,7 +354,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def head( # type: ignore [override] @@ -353,7 +365,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def options( # type: ignore [override] @@ -365,7 +377,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def put( # type: ignore [override] @@ -377,7 +389,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def patch( # type: ignore [override] @@ -389,7 +401,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def delete( # type: ignore [override] @@ -401,7 +413,7 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... async def trace( # type: ignore [override] @@ -412,6 +424,6 @@ class AsyncClient(ClientMixin, AsyncRequestFactory): secure: bool = ..., *, headers: Mapping[str, Any] | None = ..., - query_params: str | None = ..., + query_params: Mapping[str, Any] | None = ..., **extra: str, ) -> HttpResponse: ... diff --git a/django-stubs/utils/datastructures.pyi b/django-stubs/utils/datastructures.pyi index 392d364cd..bb36ca9d2 100644 --- a/django-stubs/utils/datastructures.pyi +++ b/django-stubs/utils/datastructures.pyi @@ -61,7 +61,7 @@ class MultiValueDict(dict[_K, _V]): @overload def __init__(self, key_to_list_mapping: Iterable[tuple[_K, list[_V]]] = ()) -> None: ... @override - def __getitem__(self, key: _K) -> _V: ... + def __getitem__(self, key: _K) -> _V | list[object]: ... # type: ignore[override] @override def __setitem__(self, key: _K, value: _V) -> None: ... def __copy__(self) -> Self: ... diff --git a/django-stubs/views/generic/base.pyi b/django-stubs/views/generic/base.pyi index 228fc063a..55139f3fc 100644 --- a/django-stubs/views/generic/base.pyi +++ b/django-stubs/views/generic/base.pyi @@ -2,7 +2,6 @@ from collections.abc import Callable from typing import Any import django.http as http -from django.http.response import HttpResponseBase class ContextMixin: def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... @@ -16,7 +15,7 @@ class View: @classmethod def as_view(cls, **initkwargs: Any) -> Callable[..., http.HttpResponse]: ... def setup(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> None: ... - def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ... + def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... def http_method_not_allowed(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... def options(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> http.HttpResponse: ... diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py index fdf51e321..aa35144b0 100644 --- a/tests/pyright/test_signatures.py +++ b/tests/pyright/test_signatures.py @@ -2,14 +2,7 @@ def test_client_generic_returns_a_response() -> None: - """A test sends a verb the Client has no named helper for - PATCH, or a - content-type negotiation case - via client.generic(). - - Client overrides get/post/head/options/put/patch/delete/trace to return a - response, but not generic(), so it inherited RequestFactory.generic() and the - result typed as a WSGIRequest. Every .status_code and .content on it was then - an unknown attribute of a request object. - """ + """A test sends a verb the Client has no named helper for - PATCH, or a""" results = run_pyright( """\ from django.test import Client @@ -23,12 +16,7 @@ def test_client_generic_returns_a_response() -> None: def test_url_patterns_is_heterogeneous() -> None: - """A URL-introspection helper walks the resolver tree to enumerate routes. - - include() nests a URLResolver inside url_patterns, so walking it means - branching on URLResolver vs URLPattern. The stub declared the list as - list[tuple[str, Callable]], which matches neither. - """ + """A URL-introspection helper walks the resolver tree to enumerate routes.""" results = run_pyright( """\ from django.urls import get_resolver @@ -44,30 +32,8 @@ def test_url_patterns_is_heterogeneous() -> None: assert [r for r in results if r.type == "error"] == [] -def test_multivaluedict_getitem_returns_the_value() -> None: - """A view reads a single query parameter and converts it. - - QueryDict[...] returns the last value for the key; getlist() is the API that - returns every value. The stub returned the union of both, so int(params["pk"]) - was rejected on the list arm that subscripting never produces. - """ - results = run_pyright( - """\ -from django.http import QueryDict - -def read(params: QueryDict) -> int: - return int(params["pk"]) -""" - ) - assert [r for r in results if r.type == "error"] == [] - - def test_streaming_response_accepts_str_chunks() -> None: - """A view streams rendered text - SSE, CSV, NDJSON - a chunk at a time. - - StreamingHttpResponse encodes str chunks itself, so yielding str is ordinary - usage, but the stub accepted only bytes. - """ + """A view streams rendered text - SSE, CSV, NDJSON - a chunk at a time.""" results = run_pyright( """\ from django.http import StreamingHttpResponse @@ -79,15 +45,7 @@ def test_streaming_response_accepts_str_chunks() -> None: def test_session_payload_is_heterogeneous() -> None: - """One decoded session holds several unrelated value types at once. - - Django itself writes _auth_user_id as a str (pk.value_to_string), - _session_expiry as an int and _auth_user_backend as a str, and any installed - app adds keys of its own. So no single value type fits - the stub said - dict[str, int], wrong for two of the three keys Django writes - and there is - no union to close over, because the key space is open. This test is what a - narrower annotation would have to satisfy. - """ + """One decoded session holds several unrelated value types at once.""" results = run_pyright( """\ from django.contrib.sessions.base_session import AbstractBaseSession @@ -104,11 +62,7 @@ def read(session: AbstractBaseSession) -> tuple[str, int, list[dict[str, int]]]: def test_refresh_from_db_takes_any_iterable() -> None: - """A caller refreshes a named subset of fields, passing a tuple. - - The field names are a fixed set at the call site, so a tuple is the natural - literal; the stub required list[str] specifically. - """ + """A caller refreshes a named subset of fields, passing a tuple.""" results = run_pyright( """\ from django.db import models @@ -123,12 +77,7 @@ class Foo(models.Model): def test_non_interactive_questioner_verbosity_and_log() -> None: - """A migration-graph check drives the autodetector and wants its reasons. - - NonInteractiveMigrationQuestioner takes `verbosity` and `log` so a caller can - route the field-level reason somewhere other than stdout. The stub declared - the subclass as a bare `...`, inheriting a base `__init__` without either. - """ + """A migration-graph check drives the autodetector and wants its reasons.""" results = run_pyright( """\ from django.db.migrations.questioner import NonInteractiveMigrationQuestioner @@ -141,3 +90,58 @@ def _eprint(message: str) -> None: ... """ ) assert [r for r in results if r.type == "error"] == [] + + +def test_get_query_string_takes_values_to_encode() -> None: + """ChangeList.get_query_string carries real values, not a dict[str, None].""" + results = run_pyright( + """\ +from django.contrib.admin.views.main import ChangeList + +def f(cl: ChangeList) -> str: + return cl.get_query_string({"p": "2", "o": "-1"}, remove=["q"]) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_sql_flush_is_keyword_only_and_returns_statements() -> None: + """sql_flush takes reset_sequences/allow_cascade by keyword and returns list[str].""" + results = run_pyright( + """\ +from django.core.management.color import no_style +from django.db import connection + +statements: list[str] = connection.ops.sql_flush(no_style(), ["app_thing"], reset_sequences=True, allow_cascade=False) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_migration_loader_takes_replace_migrations() -> None: + """MigrationLoader accepts replace_migrations, as it has since Django 3.0.""" + results = run_pyright( + """\ +from django.db import connection +from django.db.migrations.loader import MigrationLoader + +loader = MigrationLoader(connection, replace_migrations=False) +""" + ) + assert [r for r in results if r.type == "error"] == [] + + +def test_client_query_params_is_a_mapping() -> None: + """query_params is a mapping Django urlencodes, on every verb and on generic().""" + results = run_pyright( + """\ +from django.test.client import AsyncClient, Client + +def f(c: Client) -> int: + return c.get("/", query_params={"q": "x", "page": 2}).status_code + +async def g(c: AsyncClient) -> int: + return (await c.generic("PATCH", "/", query_params={"q": "x"})).status_code +""" + ) + assert [r for r in results if r.type == "error"] == [] From 534b126257fd9014d30b06eb6a643b2dff9837de Mon Sep 17 00:00:00 2001 From: Adam Hitchcock Date: Tue, 15 Sep 2026 13:57:09 -0700 Subject: [PATCH 7/7] Type the receiver in the sql_flush test so it checks something connection.ops is Any in the stubs, so the call was never checked; against BaseDatabaseOperations the test fails on the upstream signature. --- tests/pyright/test_signatures.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/pyright/test_signatures.py b/tests/pyright/test_signatures.py index aa35144b0..d5184a2ea 100644 --- a/tests/pyright/test_signatures.py +++ b/tests/pyright/test_signatures.py @@ -2,7 +2,7 @@ def test_client_generic_returns_a_response() -> None: - """A test sends a verb the Client has no named helper for - PATCH, or a""" + """Client.generic returns a response, like every other verb on Client.""" results = run_pyright( """\ from django.test import Client @@ -110,9 +110,10 @@ def test_sql_flush_is_keyword_only_and_returns_statements() -> None: results = run_pyright( """\ from django.core.management.color import no_style -from django.db import connection +from django.db.backends.base.operations import BaseDatabaseOperations -statements: list[str] = connection.ops.sql_flush(no_style(), ["app_thing"], reset_sequences=True, allow_cascade=False) +def f(ops: BaseDatabaseOperations) -> list[str]: + return ops.sql_flush(no_style(), ["app_thing"], reset_sequences=True, allow_cascade=False) """ ) assert [r for r in results if r.type == "error"] == []