Repository navigation
correct signatures that misdescribe Django's own API - #406
Merged
Merged
Conversation
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.
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.
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.
This was referenced Sep 15, 2026
NorthIsUp
marked this pull request as draft
September 15, 2026 19:43
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.
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.
…very 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 sbdchd#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.
connection.ops is Any in the stubs, so the call was never checked; against BaseDatabaseOperations the test fails on the upstream signature.
kodiakhq Bot
pushed a commit
that referenced
this pull request
Sep 17, 2026
These symbols all exist at runtime and are importable from the documented public location, but the stubs don't declare them, so a strict checker rejects the import. | Symbol | Where it lives | Gap | | --- | --- | --- | | `AsyncClient`, `AsyncRequestFactory` | `django.test` | defined in `test/client.pyi`, never re-exported from `test/__init__.pyi` | | `HttpResponseBase` | `django.http` | defined in `http/response.pyi`, not re-exported | | `TestCase.captureOnCommitCallbacks` | `django.test` | context manager since Django 3.2, absent | | `storages`, `StorageHandler`, `InvalidStorageError` | `django.core.files.storage` | storage-alias registry added in Django 4.2, absent | | `parse_header_parameters` | `django.utils.http` | absent; declared with the Django 6.0 signature, `(line, max_length=10000)` | | `AdminSite.get_model_admin` | `django.contrib.admin` | added in Django 5.0 as the supported alternative to reading the private `_registry`, absent | | `HttpResponseBase.__contains__` | `django.http` | aliased to `has_header` at runtime, so `"Retry-After" in response` is the documented spelling; only `has_header` was declared | Verified against Django 6.0.8: ```python >>> from django.core.files.storage import storages, InvalidStorageError # OK >>> from django.utils.http import parse_header_parameters # OK >>> from django.contrib.admin.sites import AdminSite >>> AdminSite.get_model_admin # OK >>> "X" in HttpResponse() # OK, __contains__ = has_header ``` `StorageHandler.backends` is declared as `cached_property`, which is what Django uses and how the other stubs in this repo declare the same pattern. Each row has a pyright test in `tests/pyright/test_missing_symbols.py` that fails with that row's stub file reverted. --- Part of a set with #406 (signatures), #407 (field descriptors) and #408 (`choices=`). #406 also edits `django-stubs/http/response.pyi`, in a different class; every pair merges cleanly in either order.
sbdchd
marked this pull request as ready for review
September 17, 2026 01:38
Owner
|
Thanks! |
kodiakhq Bot
pushed a commit
that referenced
this pull request
Sep 17, 2026
Closes #399. Closes #402. `Field.choices` is typed `_FieldChoices`: the pair/named-group iterable, a mapping, or a zero-argument callable returning either. The per-field `__new__` overloads never caught up. Every one of them lists only the pair iterable, and 17 add a `type[TextChoices]` or `type[IntegerChoices]`. So at the constructor, which is the only place anyone writes `choices=`, three spellings Django accepts were rejected: | Spelling | Django | Stub before | | --- | --- | --- | | `choices={"a": "A"}` | accepted since 5.0 | rejected on every field (#399) | | `TextField(choices=SomeTextChoices)` | accepted | rejected; `CharField` took it, `TextField` did not (#402) | | `choices=some_callable` | accepted; serializes the reference, so adding a member needs no migration | rejected on every field | All three verified on Django 6.0.8: ```python >>> models.CharField(max_length=8, choices={"a": "A"}).choices [('a', 'A')] >>> models.TextField(choices=Kind).choices [('a', 'A')] >>> models.CharField(max_length=8, choices=lambda: [("a", "A")]).choices <django.utils.choices.CallableChoiceIterator object at ...> ``` One generic alias, `_ChoicesFor[value, choices_class]`, replaces the hand-written unions on all 63 `choices=` parameters: the 49 in `fields/__init__.pyi` plus the 14 in `related`, `files`, `json`, `generated` and the postgres `ArrayField`. The second parameter keeps the precision the overloads already had: string fields take `TextChoices`, integer fields take `IntegerChoices`, the rest take the `Choices` base. An `IntegerField` handed a `TextChoices` class was an error before and still is; there is a test for that so the widening can't quietly become a loosening. Five pyright tests in `tests/pyright/test_choices.py`. The positive ones fail against the current stub; the precision test passes both before and after. --- Part of a set with #405 (missing symbols), #406 (signatures) and #407 (field descriptors). #407 also edits `fields/__init__.pyi`, `files.pyi`, `json.pyi` and `related.pyi`; the hunks are different declarations and the two merge cleanly in either order.
kodiakhq Bot
pushed a commit
that referenced
this pull request
Oct 9, 2026
Closes #116. Four field descriptor types that force a `cast()` or a dead guard at the call site. ### `ForeignKey`/`OneToOneField` with a lazy string reference ```python class M(models.Model): fk = models.ForeignKey("labs.LabOrder", on_delete=models.CASCADE, null=True) reveal_type(m.fk) # before: None <-- not "unknown", *absent* # after: Any | None ``` With `to: type[_M] | str`, a string reference gives `_M` nothing to solve from, and on the `null=True` overload the unsolved var collapses the whole field type to `None`. Every read of the field then errors, and the error reads like a nullable-FK bug in the application. Giving `_M` a PEP 696 default of `Any` makes the field `Any` (required) or `Any | None` (`null=True`): unknown rather than absent, with the same nullable shape a class reference gets. `Any` is only the default. An explicit parameter still resolves to the model, and composes with `null=True`: ```python untyped = models.ForeignKey("app.Thing", on_delete=models.CASCADE) # -> Any typed = models.ForeignKey[Thing]("app.Thing", on_delete=models.CASCADE) # -> Thing typed_null = models.ForeignKey[Thing | None]("app.Thing", ..., null=True) # -> Thing | None ``` The lazy string is usually there to avoid an import cycle, and the model can still be imported under `TYPE_CHECKING` and named in the subscript. No separate overload is added for the string case: `to: type[_M] | str` with the default on `_M` is enough. A string reference still goes through the same overloads as a class reference, so a misspelt `related_name` is still an error, two stray positionals still fail rather than being bound to `related_name`/`related_query_name`, and a `null=True` `OneToOneField` reads `Any | None`. All three are pinned by tests. One trade-off to state: with a default on `_M`, strict-mode pyright no longer reports `reportMissingTypeArgument` for a bare `ForeignKey` annotation, since it now has a type argument. That is the intended behaviour of PEP 696, but it does mean a bare annotation silently reads as `Any`. ### `JSONField` `_A` has no PEP 696 default, so an unparameterized `models.JSONField(...)` leaves the var unsolved; mypy errors on the declaration and strict-mode pyright on every read. This defaults it to `Any`, the same pattern `query.pyi` already uses for `_Row`. ### `FileField` Assignment accepts a `File` or a path `str`; reads return the descriptor. Assigning a `SimpleUploadedFile`, which is the normal thing to do in a test, was rejected. ### `Field.max_length` Declared `int` as a class attribute while `__init__` in the same file accepts `int | None`. `CharField(max_length=None)` is legal wherever the backend reports `supports_unlimited_charfield` (Postgres does), and Django's own `cast_db_type` and `description` branch on it being `None`, so a `max_length is None` guard in application code is live, not dead. Code that assigned `f.max_length` straight to an `int` will now need the guard. Every change has a pyright test in `tests/pyright/test_field_descriptors.py` that fails with its stub file reverted. --- Part of a set with #405 (missing symbols), #406 (signatures) and #408 (`choices=`). #408 also edits `fields/__init__.pyi`, `files.pyi`, `json.pyi` and `related.pyi`; the hunks are different declarations and the two merge cleanly in either order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Ten stub signatures that don't match what Django does. Each one was checked against the Django 6.0.8 runtime rather than inferred from the checker error.
sql_flush(style: None, tables: None, sequences: None)(style, tables, *, reset_sequences, allow_cascade) -> list[str]MigrationLoader.__init__withoutreplace_migrationsTrue)get_query_string(new_params: dict[str, None])refresh_from_db(fields: list[str])URLResolver.url_patterns: list[tuple[str, Callable]]list[URLPattern | URLResolver];include()nests resolversClient.genericandAsyncClient.genericinherited from the request factoriesClient/AsyncClientverbs:query_params: str | NoneurlencodeStreamingHttpResponse(Iterable[bytes])__init__acceptsstrchunks and encodes them; reads still yieldbytesSession.get_decoded/encode/save -> dict[str, int]NonInteractiveMigrationQuestionerdeclared...verbosityandlogTwo rows from an earlier revision were withdrawn.
View.dispatch -> HttpResponseBaseis what Django returns, but it breaks the commondef dispatch(...) -> HttpResponse: return super().dispatch(...)override, so it isn't worth it.MultiValueDict.__getitem__is the same change as #300, and Django does return[]for an empty list, so that one is left to #300.generic.Clientoverridesget/post/head/options/put/patch/delete/traceto returnHttpResponsebut notgeneric, so it inheritsRequestFactory.generic() -> WSGIRequest;AsyncClienthas the same gap againstAsyncRequestFactory. Anyclient.generic("POST", ...)in a test then gets.status_codeand.contentflagged as unknown attributes, because the checker thinks it is holding a request.Session payloads.
django.contrib.authstores the session key asrequest.session[SESSION_KEY] = user._meta.pk.value_to_string(user), which is astr.dict[str, int]is wrong for every key, andget_decoded()returns whateversigning.loadsproduced.Every row has a pyright test in
tests/pyright/test_signatures.pythat fails with that row's stub file reverted.Part of a set with #405 (missing symbols), #407 (field descriptors) and #408 (
choices=). #405 also editsdjango-stubs/http/response.pyi, in a different class; every pair merges cleanly in either order.