Repository navigation
let every field's choices= accept what Field.choices already does - #408
Merged
Merged
Conversation
The per-field __new__ overloads listed only the pair iterable, and 17 of 49 named a Choices class, so a dict (Django 5.0), a callable, or a TextChoices class on a TextField was rejected at the constructor while the attribute itself allowed all three. One generic alias replaces the 49 hand-written unions and keeps the existing str/int precision: an IntegerField still refuses a TextChoices class.
This was referenced Sep 15, 2026
related, files, json, generated and the postgres ArrayField had the same pair-only choices parameter; they now use the alias as well.
Both were widened but the test only used spellings upstream already accepted for them.
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
kodiakhq Bot
pushed a commit
that referenced
this pull request
Sep 17, 2026
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. | Stub said | Django actually | | --- | --- | | `sql_flush(style: None, tables: None, sequences: None)` | `(style, tables, *, reset_sequences, allow_cascade) -> list[str]` | | `MigrationLoader.__init__` without `replace_migrations` | has it (defaults `True`) | | `get_query_string(new_params: dict[str, None])` | holds the values to encode | | `refresh_from_db(fields: list[str])` | any iterable | | `URLResolver.url_patterns: list[tuple[str, Callable]]` | `list[URLPattern \| URLResolver]`; `include()` nests resolvers | | `Client.generic` and `AsyncClient.generic` inherited from the request factories | both run the request through the handler and return a response, like every other verb on them | | `Client` / `AsyncClient` verbs: `query_params: str \| None` | a mapping; Django passes it to `urlencode` | | `StreamingHttpResponse(Iterable[bytes])` | `__init__` accepts `str` chunks and encodes them; reads still yield `bytes` | | `Session.get_decoded/encode/save -> dict[str, int]` | heterogeneous by construction | | `NonInteractiveMigrationQuestioner` declared `...` | takes `verbosity` and `log` | Two rows from an earlier revision were withdrawn. `View.dispatch -> HttpResponseBase` is what Django returns, but it breaks the common `def 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`.** `Client` overrides `get`/`post`/`head`/`options`/`put`/`patch`/`delete`/`trace` to return `HttpResponse` but not `generic`, so it inherits `RequestFactory.generic() -> WSGIRequest`; `AsyncClient` has the same gap against `AsyncRequestFactory`. Any `client.generic("POST", ...)` in a test then gets `.status_code` and `.content` flagged as unknown attributes, because the checker thinks it is holding a request. **Session payloads.** `django.contrib.auth` stores the session key as `request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)`, which is a `str`. `dict[str, int]` is wrong for every key, and `get_decoded()` returns whatever `signing.loads` produced. ```python >>> inspect.signature(BaseDatabaseOperations.sql_flush) (self, style, tables, *, reset_sequences=False, allow_cascade=False) >>> inspect.signature(MigrationLoader.__init__) (self, connection, load=True, ignore_no_migrations=False, replace_migrations=True) >>> inspect.signature(RequestFactory.generic) (self, method, path, data='', content_type='application/octet-stream', secure=False, *, headers=None, query_params=None, **extra) ``` Every row has a pyright test in `tests/pyright/test_signatures.py` that fails with that row's stub file reverted. --- Part of a set with #405 (missing symbols), #407 (field descriptors) and #408 (`choices=`). #405 also edits `django-stubs/http/response.pyi`, in a different class; every pair merges 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.
UnknownPlatypus
added a commit
to UnknownPlatypus/django-stubs
that referenced
this pull request
Oct 24, 2026
# I have made things!
`Field.__init__` and the scalar fields already take `choices: _ChoicesInput` (a `Choices` class, a mapping, a callable or an iterable of pairs), like Django does.
`FileField`, the related fields, `ArrayField` and the GIS fields still took the narrower `_Choices` iterable, so `FileField(choices=Kind)`, `ForeignKey(..., choices={...})` or a callable were rejected.
## Related issues
Ported from sbdchd#408
## AI Policy
- [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
UnknownPlatypus
added a commit
to UnknownPlatypus/django-stubs
that referenced
this pull request
Oct 24, 2026
# I have made things!
`Field.__init__` and the scalar fields already take `choices: _ChoicesInput` (a `Choices` class, a mapping, a callable or an iterable of pairs), like Django does.
`FileField`, the related fields, `ArrayField` and the GIS fields still took the narrower `_Choices` iterable, so `FileField(choices=Kind)`, `ForeignKey(..., choices={...})` or a callable were rejected.
## Related issues
Ported from sbdchd#408
## AI Policy
- [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
Merged
1 task done
UnknownPlatypus
added a commit
to UnknownPlatypus/django-stubs
that referenced
this pull request
Oct 25, 2026
`Field.__init__` and the scalar fields already take `choices: _ChoicesInput` (a `Choices` class, a mapping, a callable or an iterable of pairs), like Django does.
`FileField`, the related fields, `ArrayField` and the GIS fields still took the narrower `_Choices` iterable, so `FileField(choices=Kind)`, `ForeignKey(..., choices={...})` or a callable were rejected.
Ported from sbdchd#408
- [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
UnknownPlatypus
added a commit
to typeddjango/django-stubs
that referenced
this pull request
Oct 25, 2026
…3756) `Field.__init__` and the scalar fields already take `choices: _ChoicesInput` (a `Choices` class, a mapping, a callable or an iterable of pairs), like Django does. `FileField`, the related fields, `ArrayField` and the GIS fields still took the narrower `_Choices` iterable, so `FileField(choices=Kind)`, `ForeignKey(..., choices={...})` or a callable were rejected. Ported from sbdchd#408 - [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
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.
Closes #399. Closes #402.
Field.choicesis 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 atype[TextChoices]ortype[IntegerChoices]. So at the constructor, which is the only place anyone writeschoices=, three spellings Django accepts were rejected:choices={"a": "A"}TextField(choices=SomeTextChoices)CharFieldtook it,TextFielddid not (#402)choices=some_callableAll three verified on Django 6.0.8:
One generic alias,
_ChoicesFor[value, choices_class], replaces the hand-written unions on all 63choices=parameters: the 49 infields/__init__.pyiplus the 14 inrelated,files,json,generatedand the postgresArrayField. The second parameter keeps the precision the overloads already had: string fields takeTextChoices, integer fields takeIntegerChoices, the rest take theChoicesbase. AnIntegerFieldhanded aTextChoicesclass 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.pyiandrelated.pyi; the hunks are different declarations and the two merge cleanly in either order.