524 Commits

Author SHA1 Message Date
Dave Halter
7c995572c6 Model.objects should be a ClassVar
Model.objects is only available on classes and while we cannot force this, without ClassVar it's kind of only available on instances.

I have noticed this when I was writing a Jedi plugin that makes django-stubs work properly.
2022-11-03 13:36:03 +00:00
Adam Johnson
1d78b8ffac Add SQLite backend is_in_memory_db() functions (#1218)
* Add SQLite backend is_in_memory_db() functions

* Update django-stubs/db/backends/sqlite3/creation.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-11-03 16:18:05 +03:00
Nikita Sobolev
e865c5b40f Update README.md 2022-11-03 16:10:49 +03:00
Nikita Sobolev
5edf2e8217 Cancel old pipelines (#1226)
* Cancel old pipelines

Closes #1225

* Update setup.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-11-03 16:05:54 +03:00
Nikita Sobolev
7f0dd143f7 Delete pre-commit-autoupdate.yml 2022-11-03 15:54:12 +03:00
Nikita Sobolev
3fbfa1e13c Enable pre-commit.ci (#1222)
* Update .pre-commit-config.yaml

* Update setup.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-11-03 15:53:53 +03:00
Sigurd Ljødal
a82c83f897 Fix types for sessions (#1173)
Co-authored-by: Adam Johnson <me@adamj.eu>
2022-11-03 11:37:51 +00:00
sobolevn
d4899596de Release django-stubs and django-stubs-ext 2022-11-03 13:24:13 +03:00
Adam Johnson
0381fdb022 Add some types to views (#1221)
* Add some types to views

* Remove GeoModelAdmin.formfield_for_dbfield
2022-10-31 20:43:49 +03:00
Adam Johnson
f566734799 Re-allow expressions in UniqueConstraint (#1220) 2022-10-31 15:11:07 +03:00
Adam Johnson
2a17d3f08f Remove bad redirect_chain attributes (#1148) 2022-10-31 14:35:45 +03:00
Marti Raudsepp
8f475fa0a6 Fill remaining missing hints with Any & disallow partial hints (#1206)
* Fill remaining missing hints with Any & disallow partial hints

* ModelFormatDict -> _ModelFormatDict

* Fixes

* Add __init__ return hints

* Add suppression
2022-10-31 14:33:59 +03:00
Marti Raudsepp
e3c131bc61 Add type hints to all test code (#1217)
* Add type hints to all test code

* Fixes

* Fix indentation

* Review fixes
2022-10-31 12:20:10 +03:00
github-actions[bot]
9b4162beb1 Auto-update pre-commit hooks (#1216)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-10-30 08:06:09 +00:00
Adam Johnson
7bce5c2081 BaseDeleteView now extends FormMixin (#1215)
* BaseDeleteView now extends FormMixin

Co-Authored-By: Simon Kohlmeyer <simon.kohlmeyer@gmail.com>

* With Generic

Co-authored-by: Simon Kohlmeyer <simon.kohlmeyer@gmail.com>
2022-10-28 23:36:38 +03:00
Guillaume Andreu Sabater
875acf76d7 Fixed F's asc and desc args (#1213)
* fixed F asc & desc signature

* improved BaseExpression asc & desc signature
2022-10-28 15:59:18 +03:00
Marti Raudsepp
36044c98b8 Add lots of missing argument & return type hints (#1204)
* Add lots of missing argument & return type hints

Discovered by setting mypy options disallow_untyped_defs, disallow_incomplete_defs.

* Sequence -> List

* Fixes from review

* Drop ordering_field

* Revert ModelBackend.with_perm

* typing_extensions.TypedDict instead

* bla

* Remove private method _get_lines_from_file

* A few additions

* Hints for BaseSpatialFeatures
2022-10-28 13:08:00 +03:00
Adam Johnson
e20d5307d1 Add BaseDatabaseSchemaEditor.table_sql() (#1212)
Co-Authored-By: Ryan Vinzent <ryan.vinzent@invitae.com>

Co-authored-by: Ryan Vinzent <ryan.vinzent@invitae.com>
2022-10-27 21:32:50 +03:00
Adam Johnson
ae5af12c9b Add BaseDetailView.object (#1211) 2022-10-27 21:32:08 +03:00
Adam Johnson
85ae4bb704 Add django.db.models.base.model_unpickle (#1209) 2022-10-27 21:30:44 +03:00
Adam Johnson
efebe22397 Add auto_now attrs to date and time model fields (#1210)
Co-Authored-By: Ben Nace <ben2701@verizon.net>

Co-authored-by: Ben Nace <ben2701@verizon.net>
2022-10-27 20:52:48 +03:00
dependabot[bot]
f9fbeb0f9b Bump pytest from 7.1.3 to 7.2.0 (#1203)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.1.3 to 7.2.0.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.1.3...7.2.0)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-27 11:37:05 +03:00
dependabot[bot]
73312caa24 Bump pytest-mypy-plugins from 1.10.0 to 1.10.1 (#1205)
Bumps [pytest-mypy-plugins](https://github.com/TypedDjango/pytest-mypy-plugins) from 1.10.0 to 1.10.1.
- [Release notes](https://github.com/TypedDjango/pytest-mypy-plugins/releases)
- [Changelog](https://github.com/typeddjango/pytest-mypy-plugins/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TypedDjango/pytest-mypy-plugins/compare/1.10.0...1.10.1)

---
updated-dependencies:
- dependency-name: pytest-mypy-plugins
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-27 09:00:41 +03:00
Petter Friberg
6aecafc64f Improve type of TestCase.captureOnCommitCallbacks (#1202)
Co-authored-by: Adam Johnson <me@adamj.eu>
2022-10-25 09:47:09 +01:00
Petter Friberg
adb26248db Allow assertQuerySetEqual to compare with a collection of values (#1201) 2022-10-25 00:50:08 +03:00
Thibaut Decombe
71b06f5bb3 Generic sitemap (#1198)
* Add test for both issue cases

* Use generic type and add new django 4.1 `get_latest_lastmod` method

* Add Sitemap to monkeypatch

* Update test case to use generic + add failing case

* Test GenericSitemap too
2022-10-22 20:58:59 +03:00
James Owen
fb9ad1c7fe Add hints for instance variables in console.EmailBackend (#1200) 2022-10-21 16:42:21 +01:00
Adam Johnson
36002a2087 Standardize all context manager __exit__ methods (#1194) 2022-10-19 10:31:38 +01:00
Adam Johnson
54e75fbe74 Update cache timeout parameters to floats (#1193) 2022-10-19 10:31:29 +01:00
Thibaut Decombe
14ff5ad7a8 Fix RelatedManager not callable (#1191)
* Add failing test

* Add call annotation
2022-10-19 11:14:51 +03:00
dependabot[bot]
a78c59226a Bump gitpython from 3.1.28 to 3.1.29 (#1187)
Bumps [gitpython](https://github.com/gitpython-developers/GitPython) from 3.1.28 to 3.1.29.
- [Release notes](https://github.com/gitpython-developers/GitPython/releases)
- [Changelog](https://github.com/gitpython-developers/GitPython/blob/main/CHANGES)
- [Commits](https://github.com/gitpython-developers/GitPython/compare/3.1.28...3.1.29)

---
updated-dependencies:
- dependency-name: gitpython
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-11 09:56:16 +03:00
github-actions[bot]
1c914abfa8 Auto-update pre-commit hooks (#1188)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-10-11 09:56:01 +03:00
dependabot[bot]
994312672e Bump black from 22.8.0 to 22.10.0 (#1184)
Bumps [black](https://github.com/psf/black) from 22.8.0 to 22.10.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/compare/22.8.0...22.10.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-07 09:37:11 +03:00
dependabot[bot]
4235bf7585 Bump gitpython from 3.1.27 to 3.1.28 (#1185)
Bumps [gitpython](https://github.com/gitpython-developers/GitPython) from 3.1.27 to 3.1.28.
- [Release notes](https://github.com/gitpython-developers/GitPython/releases)
- [Changelog](https://github.com/gitpython-developers/GitPython/blob/main/CHANGES)
- [Commits](https://github.com/gitpython-developers/GitPython/compare/3.1.27...3.1.28)

---
updated-dependencies:
- dependency-name: gitpython
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-07 09:37:03 +03:00
github-actions[bot]
1cc6ec39a6 Auto-update pre-commit hooks (#1186)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-10-07 09:36:53 +03:00
Anders Kaseorg
41deee4ec6 Update utils.log.log_response type for Django 4.1 (#1183)
90cf963264

Signed-off-by: Anders Kaseorg <andersk@mit.edu>

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-10-06 11:22:20 +03:00
PIG208
05dc579748 Add missing re-export for JSONObject. (#1182) 2022-10-06 08:43:05 +01:00
github-actions[bot]
3a2f806282 Auto-update pre-commit hooks (#1181)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-10-05 12:55:39 +03:00
dependabot[bot]
4bdf385602 Bump mypy from 0.981 to 0.982 (#1180)
Bumps [mypy](https://github.com/python/mypy) from 0.981 to 0.982.
- [Release notes](https://github.com/python/mypy/releases)
- [Commits](https://github.com/python/mypy/compare/v0.981...v0.982)

---
updated-dependencies:
- dependency-name: mypy
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-04 11:13:05 +03:00
Sigurd Ljødal
dde0f2f876 Reparametrize managers without explicit type parameters (#1169)
* Reparametrize managers without explicit type parameters

This extracts the reparametrization logic from #1030 in addition to
removing the codepath that copied methods from querysets to managers.
That code path seems to not be needed with this change.

* Use typevars from parent instead of base

* Use typevars from parent manager instead of base manager

This removes warnings when subclassing from something other than the
base manager class, where the typevar has been restricted.

* Remove unused imports

* Fix failed test

* Only reparametrize if generics are omitted

* Fix docstring

* Add test with disallow_any_generics=True

* Add an FAQ section and document disallow_any_generics behaviour
2022-10-03 20:36:45 +03:00
Marti Raudsepp
946274bed8 Add UUIDField lookup types (#1178) 2022-10-02 13:48:37 +03:00
Marti Raudsepp
db14454199 Fix type of <fieldname>_id when using ForeignKey(to_field=) (#1176)
* Fix type of <fieldname>_id when using ForeignKey(to_field=)

Previously mypy_django_plugin would always use the field type of target
model's primary key, but `to_field` can refer to a different field type.

* Fixes

* More fixes
2022-09-30 10:05:57 +03:00
Sigurd Ljødal
5c616863dc Add SETTINGS_MODULE to Settings and LazySettings (#1175)
Add SETTINGS_MODULE as an attriute to the Settings and LazySettings
classes. This makes mypy aware of this attribute.

Fixes #1174
2022-09-30 10:03:54 +03:00
Petter Friberg
54d5835f66 Implement support for <QuerySet>.as_manager() (#1025)
* Implement support for `<QuerySet>.as_manager()`

* fixup! Implement support for `<QuerySet>.as_manager()`

* fixup! fixup! Implement support for `<QuerySet>.as_manager()`
2022-09-29 15:05:25 +03:00
Sigurd Ljødal
1f2e406972 Don't allow promise to be passed to ArrayField.name (#1171)
This was incorrectly changed in #1168, so reverting that change.
2022-09-28 16:34:43 +03:00
Marti Raudsepp
56f74f1940 Disallow passing bytes for field verbose_name (#1170)
`verbose_name` is intended to be a human-readable string, not binary.
2022-09-27 19:56:25 +03:00
Sigurd Ljødal
199a7f2707 Allow Promise to be passed to ArrayField.verbose_name (#1168)
* Allow Promise to be passed to ArrayField.verbose_name

* Remove bytes and allow Promise for name as well
2022-09-27 17:53:28 +03:00
Nikita Sobolev
93fa1d2e19 Update mypy to 0.981 (#1167)
* Update mypy to 0.981

* Fix plugin API

* Fix scripts

* Fix scripts

* Fix plugin
2022-09-27 11:55:36 +03:00
github-actions[bot]
bba51ce67d Auto-update pre-commit hooks (#1165)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-09-26 09:17:41 +03:00
github-actions[bot]
f6a8c8dc8d Auto-update pre-commit hooks (#1164)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-09-25 08:51:38 +03:00
Anders Kaseorg
9bd8aed1e1 Disable fallback to runtime types for Django settings (#1163)
This fallback to value.__class__ seems to be doing more harm than
good; see #312 and #1162.  Replace it with a clear error message that
suggests a way to fix the problem rather than incompletely papering
over it.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-09-24 10:57:45 +03:00
Sigurd Ljødal
02999f3e86 Fix unresolved placeholder error during serialization (#1161)
This fixes an error that occured during state serialization. Completely
unsure how to reproduce this in a test but it resolves a long-standing
prolem in our project at work at least.
2022-09-23 21:35:23 +03:00
PIG208
3bc8278424 Fix paramters for ParallelTestSuite and RemoteTestRunner. (#1072)
* Fix paramters for ParallelTestSuite and RemoteTestRunner.

A new parameter `buffer` is added. `suites` is renamed to `subsuites`.

ParallelTestSuite:
2fac0a1808/django/test/runner.py (L468-L475)

RemoteTestRunner:
2fac0a1808/django/test/runner.py (L350)

`buffer` was added in f6713cda89,
`suites` was renamed in cb6c19749d.
Both of these changes were made in 4.1rc1.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Adjust types of attributes for runners.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-09-20 08:52:16 +03:00
Petter Friberg
6f9afd3cc9 Relax fields= arg for refresh_from_db to accept Sequence (#1156) 2022-09-19 23:14:08 +01:00
PIG208
d7326315b1 Improve stubs for runserver management command. (#1037)
This adds type annotation for `run`, `get_handler`, `inner_run` and
`server_cls`.

Source code:
03eec9ff6c/django/core/management/commands/runserver.py
2022-09-19 22:30:04 +03:00
PIG208
9a41aa63ba Broaden type annotation for verbose_name(_plural) to accept lazystr. (#1139)
* Broaden type annotation for verbose_name(_plural) to accept lazystr.

Fixes #1137.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Broaden type annotation for help_text to accept lazystr.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Broaden type annotation for ValidationError to accept lazystr.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Broaden type annotation for label to accept lazystr.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add StrPromise and StrOrPromise aliases to django_stubs_ext.

We make StrPromise and StrOrPromise available via django_stubs_ext so
that conditional imports with TYPE_CHECKING is not required.
These aliases fall back to Promise or Union[str, Promise]
when not TYPE_CHECKING.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-09-19 17:01:44 +03:00
Petter Friberg
a2a3543198 Adjust choices= type variance for model fields (#1154)
Avoid getting stuck in an invariance pit. I don't think it makes sense
to mix two tuple with named group elements in same choices sequence(?).

This also changes the outermost container type to `Sequence` as e.g.
both `tuple` and `list` are supported.
2022-09-19 13:17:17 +03:00
github-actions[bot]
88793ee3f7 Auto-update pre-commit hooks (#1153) 2022-09-16 08:32:46 +01:00
Petter Friberg
b34ebe7553 Serialize RelatedManager attributes in cache (#1152) 2022-09-15 23:54:10 +03:00
Adam Johnson
29e2b65c8b Improve Flake8 config (#1149) 2022-09-09 17:16:22 +03:00
Yannik Rödel
abd0609f80 Add type and parameter fields to MediaType (#1103) 2022-09-09 14:48:24 +01:00
Adam Johnson
3c942483d4 Correct EmailMultiAlternatives.body (#1146) 2022-09-08 14:13:54 +03:00
dependabot[bot]
354a892ecc Bump pytest from 7.1.2 to 7.1.3 (#1144)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.1.2 to 7.1.3.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.1.2...7.1.3)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-05 16:26:19 +03:00
Søren Howe Gersager
678a5a0302 Add django.db.models.functions.Collate (#1143) 2022-09-05 14:03:02 +01:00
PIG208
c0414c7b02 Reflect the deprecation of get_response being None. (#1086)
* Reflect the deprecation of get_response being None.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Type get_response with a callback protocol.

Otherwise, calling `self.get_response(request)` in a subclass of
`MiddlewareMixin` runs into `Invalid self argument` error.

This is a workaround for https://github.com/python/mypy/issues/5485.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-09-03 23:53:14 +03:00
Daniel Brown
12e8009600 fix type hint for GenericSitemap(info_dict) (#1111) 2022-09-02 12:48:19 +03:00
github-actions[bot]
2df1b6fecd Auto-update pre-commit hooks (#1142)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-09-01 11:52:06 +03:00
dependabot[bot]
f477317059 Bump black from 22.6.0 to 22.8.0 (#1141)
Bumps [black](https://github.com/psf/black) from 22.6.0 to 22.8.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/compare/22.6.0...22.8.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-01 11:43:22 +03:00
Sebastiaan Zeeff
a1d3aec3a2 Fix return type for django.shortcuts.render (#1140)
The return type for calling `shorcuts.render` without providing a value
for the `permanent` kwarg was `HttpResponsePermanentRedirect`, while it
should be `HttpResponseRedirect`.

The reason is that the first two overloads of the type stub overlap for
the case of using the default argument. While `mypy` does issue an error
for this, it was previously ignored with the `# type: ignore` comment.

As the first overload annotates the function as having the return type
`HttpResponsePermanentRedirect`, this would make mypy assume that the
return type is that instead of `HttpResponseRedirect`.

Since calling `django.shortcuts.redirect` without providing an argument
for `permanent` is the same as calling it with a `Literal[False]`, as
the default value is a `False`, we can improve the stub by only
specifying the option to use the default argument (`= ...`) in the
second overload. This also removes the overlap in stub definitions,
meaning that the `# type: ignore` can now be removed.

This commit fixes #1138.
2022-08-30 15:05:39 +03:00
Adam Johnson
74e31c7562 Add QuerySet.__aiter__() (#1136) 2022-08-28 15:15:28 +03:00
Adam Johnson
0635afa57c Fix Manager.contains and bulk_create (#1135) 2022-08-28 12:01:40 +03:00
Adam Johnson
3622a61442 Improve types for QuerySet.contains and bulk_create (#1134)
* Improve types for QuerySet.contains and bulk_create

* models.Model
2022-08-28 11:37:37 +03:00
Adam Johnson
bfad3b05c1 Improve database backend types (#1132)
* Improve database backend types

* fixes
2022-08-28 11:15:22 +03:00
Adam Johnson
11c587867d Add Q.__xor__ (#1133) 2022-08-28 11:14:03 +03:00
Joon Hwan 김준환
d0a9793917 Add async queryset for Django 4.1 (#1131)
* Add async queryset for Django 4.1

* dedup

* fix to async
2022-08-28 11:13:56 +03:00
PIG208
18a055124a Return Promise for lazy functions. (#689)
* Type the return value of lazy translation functions as Promise.

The return value of the lazy translation functions is a proxied
`Promise` object.
https://github.com/django/django/blob/3.2.6/django/utils/translation/__init__.py#L135-L221.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Mark unicode translation functions for deprecation.

https://docs.djangoproject.com/en/4.0/releases/4.0/#features-removed-in-4-0.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add proxied functions for Promise.

Although there is nothing defined in `Promise` itself, the only
instances of `Promise` are created by the `lazy` function, with magic
methods defined on it.

https://github.com/django/django/blob/3.2.6/django/utils/functional.py#L84-L191.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add _StrPromise as a special type for Promise objects for str.

This allows the user to access methods defined on lazy strings while
still letting mypy be aware of that they are not instances of `str`.

The definitions for some of the magic methods are pulled from typeshed. We need
those definitions in the stubs so that `_StrPromise` objects will work properly
with operators, as refining operator types is tricky with the mypy
plugins API.

The rest of the methods will be covered by an attribute hook.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Implement _StrPromise attribute hook.

This implements an attribute hook that provides type information for
methods that are available on `builtins.str` for `_StrPromise` except
the supported operators. This allows us to avoid copying stubs from the
builtins for all supported methods on `str`.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Allow message being a _StrPromise object for RegexValidator.

One intended usage of lazystr is to postpone the translation of the
error message of a validation error. It is possible that we pass a
Promise (specifically _StrPromise) and only evaluate it when a
ValidationError is raised.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Refactor _StrPromise attribtue hook with analyze_member_access.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-08-27 21:08:31 +03:00
PIG208
11ded9deaf Enhance stubs for csrf decorators. (#1130)
* Use inherited types from CsrfViewMiddleware.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Define decorators generated from middleware with TypeVars.

csrf_protect and etc. are created via the decorator_from_middleware
helper, which doesn't modify the original signature of the wrapped view
function. Using TypeVar helps preserve the original type of the
decorated callable.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-08-27 20:29:30 +03:00
Petter Friberg
8bd00ba25a Type samesite values as literals 'Lax', 'Strict' or 'None' (#1110)
* Type `samesite` values as literals 'Lax', 'Strict' or 'None'

- Adjusts supported `SESSION_COOKIE_SAMESITE` values
- Adjusts supported `CSRF_COOKIE_SAMESITE` values

* Update django-stubs/conf/global_settings.pyi

* Update response.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-08-27 02:02:47 +03:00
László Károlyi
6b39050d52 Updating deconstructible (#1116)
* Updating deconstructible

* Black

* Update deconstruct.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-08-27 01:43:32 +03:00
Adam Johnson
a01ab43cc6 Add HttpRequest current_app and LANGUAGE_CODE attrs (#1127)
* Add HttpRequest.current_app

* rearrange and add LANGUAGE_CODE
2022-08-26 17:23:50 +03:00
Adam Johnson
82695e8e1c Add db Field.flatchoices (#1128)
* Add db Field.flatchoices

* @property
2022-08-26 17:23:26 +03:00
Adam Johnson
0120fc531a Rewrite SessionBase properties to use @property (#1129) 2022-08-26 17:22:03 +03:00
Adam Johnson
de3e13ad92 Add database Field.non_db_attrs (#1125)
* Add database Field.non_db_attrs

* Update django-stubs/db/models/fields/__init__.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-08-26 14:56:56 +03:00
Nikita Sobolev
06359013c9 Run stubs self-check on all python versions (#1126) 2022-08-26 14:36:23 +03:00
Adam Johnson
63bee32d0d Add different signatures for form assertions from Django 4.1 (#1105) 2022-08-26 13:31:45 +03:00
Adam Johnson
1a310ef7f9 Add test client response.redirect_chain (#1124) 2022-08-26 13:31:17 +03:00
Adam Johnson
8b5509b2ab Improve type hints for test client response.context (#1100)
* Improve type hints for test client response.context

* fix test
2022-08-26 13:30:18 +03:00
Nikita Sobolev
0bb1182c42 Fix CI (#1108)
* Fix CI

* Fix CI

* Fix CI

* Fix CI

* APply black

* APply black

* Fix mypy

* Fix mypy errors in django-stubs

* Fix format

* Fix plugin

* Do not patch builtins by default

* Fix mypy

* Only run mypy on 3.10 for now

* Only run mypy on 3.10 for now

* WHAT THE HELL

* Enable strict mode in mypy

* Enable strict mode in mypy

* Fix tests

* Fix tests

* Debug

* Debug

* Fix tests

* Fix tests

* Add TYPE_CHECKING debug

* Caching maybe?

* Caching maybe?

* Try explicit `${{ matrix.python-version }}`

* Remove debug

* Fix typing

* Finally
2022-08-26 13:22:55 +03:00
Adam Johnson
d2bfd3710b Improve return type for BaseCommand.execute() (#1104) 2022-08-26 13:10:24 +03:00
Adam Johnson
cf16720f28 Improve types for DiscoverRunner (#1106)
* Improve types for DiscoverRunner

* add types for class-level attrs

* Add extra methods

* Add PDBDebugResult class

* black

* Update django-stubs/test/runner.pyi

* fix load_with_patterns return

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-08-26 13:09:41 +03:00
Adam Johnson
063a35f4d0 Expose HttpResponseBase in django.http (#1121)
* Expose HttpResponseBase in django.http

* isort
2022-08-26 12:45:22 +03:00
Adam Johnson
9ba4a55c93 Improve types for CheckMessage subclasses (#1107) 2022-08-26 12:44:18 +03:00
Adam Johnson
561140a584 Allow None to be passed to Paginator.get_page (#1101) 2022-08-26 12:40:53 +03:00
Adam Johnson
5b705d25da Add SimpleTestCase.assertURLEqual() (#1102) 2022-08-26 12:40:34 +03:00
Adam Johnson
f626448105 Add BaseDatabaseWrapper.operations (#1119) 2022-08-26 12:40:17 +03:00
Adam Johnson
63ea17744f Add HttpResponseBase.__contains__ (#1099) 2022-08-26 12:37:23 +03:00
Adam Johnson
f8fca3f94f Improve hints for BaseCache (#1117)
* Improve hints for BaseCache

* fix syntax error
2022-08-26 12:36:58 +03:00
Anders Kaseorg
041b66a6aa Prevent building an editable wheel with setuptools<64 (#1123)
This seems to be needed for passing CI now.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-08-26 11:55:41 +03:00
Alex Nathanail
3ac34f1108 Fix base_field type for SimpleArrayField (#1097)
* Fix base_field type for SimpleArrayField

* Add test which fails without this change
2022-08-10 16:16:54 +03:00
PIG208
a1445291fd Improve type annotation for RunSQL (#1090)
* Allow passing heterogeneous list or tuple to RunSQL.

The sqls to be executed do not necessarily need to be a homogeneous list
or tuple containing only lists or tuples or strs. It can be a mix of
everything.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Support passing dict as a sql param.

The 2-item tuple for `sql` can have a `dict` as the second item
for parameters. This behavior is the same as using
`cursor.execute` for backends except SQLite.

Relevant implementation:
5f76002500/django/db/migrations/operations/special.py (L119-L133)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add a test case for RunSQL.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-08-09 10:36:36 +03:00
PIG208
7b18e354f1 Add preset options list to makemessages command. (#1091)
These options can be found here:

0756c61f2a/django/core/management/commands/makemessages.py (L222-L225)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-08-09 00:31:34 +03:00
PIG208
db1edeeabf Fix a broken test case after the Django 4.1 update. (#1093)
This fixes the CI starting occur on #1086 and following PRs due to the release
of Django 4.1 (https://docs.djangoproject.com/en/4.1/releases/4.1/) which
shipped the change

    # Even if this relation is not to pk, we require still pk value.
    # The wish is that the instance has been already saved to DB,
    # although having a pk value isn't a guarantee of that.
    if self.instance.pk is None:
        raise ValueError(
            f"{instance.__class__.__name__!r} instance needs to have a primary "
            f"key value before this relationship can be used."
        )

in https://github.com/django/django/pull/15318.
2022-08-09 00:18:08 +03:00
Anders Kaseorg
589f315926 Remove trailing whitespace in README to fix CI failure (#1084)
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-08-02 11:07:21 +03:00
Tony Narlock
5334a80c9b docs(README): Fix indentation in list and examples (#1083)
Run examples through black for uniformity, link `HttpModel`
2022-08-02 02:39:14 +03:00
Thibaut Decombe
966472994b Allow float for min_value and max_value of FloatField (#1081)
Co-authored-by: Thibaut <thibaut.d@hellowatt.fr>
2022-08-01 14:17:50 +03:00
Anders Kaseorg
41804f0e8d Fix OutputWrapper.style_func type (#1080)
style_func has a setter that converts None to lambda x: x, so the
getter cannot return None.

https://github.com/django/django/blob/4.0.6/django/core/management/base.py#L141-L150

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-07-30 12:58:41 +03:00
PIG208
0e9ebf838b Support Lookup generics. (#1079)
Custom `Lookup` implementation will run into
'Missing type parameters for generic type "Lookup"' without having
`Lookup` monkey-patched with django-stubs-ext.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-28 21:08:56 +03:00
github-actions[bot]
196e6743ec Auto-update pre-commit hooks (#1076)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2022-07-27 10:06:55 +03:00
Adam Johnson
efc2d04ead Improve types for @require_http_methods (#1075) 2022-07-26 20:47:05 +03:00
PIG208
56f9300d0d Improve stubs for contrib.postgres.operations. (#1071)
* Improve stubs for contrib.postgres.operations.

This adds a bunch of missing operations in contrib.postgres.operations.

Documentation: https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/operations/#managing-collations-using-migrations
Source code: 2fac0a1808/django/contrib/postgres/operations.py

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add migration_name_fragment to Operation.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Remove redefinition of methods in subclasses.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-24 10:40:13 +03:00
Anders Kaseorg
20f0702f86 Tighten management.get_commands type (#1074)
get_commands has not actually returned BaseCommand items since Django
1.4.  See https://github.com/django/django/pull/15876.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-07-24 10:38:32 +03:00
PIG208
f3f80164a8 Fix type annotation of message_dict. (#1073)
When message_dict is accessed, it either raises an `AttributeError` or
returns a `dict`. There is no way for it to be `Optional`.

caad462fea/django/core/exceptions.py (L170-L176)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-23 16:55:58 +03:00
Anders Kaseorg
3d8d900487 Fix overloads and remove PathLike in finders (#1063)
* Fix overloads in finders

Signed-off-by: Anders Kaseorg <andersk@mit.edu>

* Remove PathLike from finders

Django really requires these paths to be str.  For example, in
FileSystemFinder, .find(path) calls .find_location(…, path, …) which
evaluates path.startswith(prefix) and path[len(prefix) :]; these don’t
work on arbitrary PathLike objects.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-07-22 10:35:24 +03:00
PIG208
563e947402 Improve type annotation of DiscoverRunner. (#1069)
The return type of DiscoverRunner.get_resultclass should
be Optional[Type[TextTestResult]] given that it may also return PDBDebugResult:
0dd2920909/django/test/runner.py (L958-L962)

`DicoverRunner.run_tests` accepts `None` for `extra_tests` because
that's already the default value for it:
0dd2920909/django/test/runner.py (L1030)
2022-07-22 10:34:26 +03:00
github-actions[bot]
62c09c064c Auto-update pre-commit hooks (#1070)
* Auto-update pre-commit hooks

* Update pre-commit-autoupdate.yml

Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-07-22 10:07:15 +03:00
Nikita Sobolev
89d0a10939 Create pre-commit-autoupdate.yml 2022-07-22 09:34:53 +03:00
Jordan Hayashi
0246f9fcf3 Use a more general type for django.core.mail.send_mass_mail's datatuple (#1062)
* Use a datatuple in django.core.mail.send_mass_mail

Even though the implementation works for both a List of tuples and a
tuple of tuples, the docs recommend using a tuple.

https://github.com/django/django/blob/main/django/core/mail/__init__.py#L112
https://docs.djangoproject.com/en/4.0/topics/email/#send-mass-mail

* Use a more general type for send_mass_mail's datatuple
2022-07-19 21:12:30 +03:00
Sigurd Ljødal
e7a89f73c4 Improve typing for unresolved managers (#1044)
* Improve typing for unresolved managers

This changes the logic when encountering an unresolvable manager class.
Instead of adding it as a `Manager` we create a subclass of `Manager`
that has `fallback_to_any=True` set. Similarly a `QuerySet` class is
created that also has fallbacks to `Any`. This allows calling custom
methods on the manager and querysets without getting type errors.

* Fix manager created and improve a test

* Fix row type of FallbackQuerySet

Because this inherits from _QuerySet, not QuerySet, it needs to have two
parameters
2022-07-18 09:13:46 +03:00
Sigurd Ljødal
830d74b493 Add support for inline from_queryset in model classes (#1045)
* Add support for inline from_queryset in model classes

This adds support for calling <Manager>.from_queryset(<QuerySet>)()
inline in models, for example like this:

    class MyModel(models.Model):
        objects = MyManager.from_queryset(MyQuerySet)()

This is done by inspecting the class body in the transform_class_hook

* Fix missing methods on copied manager

* Add test and other minor tweaks

* Always create manager at module level

When the manager is added at the class level, which happened when it was
created inline in the model body, it's not possible to retrieve the
manager again based on fullname. That lead to problems with inheritance
and the default manager.
2022-07-13 10:04:44 +03:00
David Smith
2e84c03632 Made BaseContext __setitem__ and __getitem__ consistant. (#1040)
* Made BaseContext __setitem__ and __getitem__ consistant.

* Standardised ContextKeys
2022-07-13 09:48:33 +03:00
PIG208
3648e10350 Use _AsSqlType for as_sql (#1052)
* Annotate the return type of as_sql for SpatialOperator.

Its subclasses inherits the type annotation from `SpatialOperator`, so
copying `as_sql` over is unnecessary.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Remove unnecessary as_sql definition.

`Query` inherits `as_sql` from `BaseExpression`, `GISLookup` inherits
`as_sql` from `Lookup`, and `BuiltinLookup` inherits `as_sql` from
`Lookup[_T]`.  None is required to be redefined.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Unify return types of as_sql and friends as _AsSqlType.

`Tuple[str, _ParamsT]`, `Tuple[str, List[Union[str, int]]]` and other
similar type annotations are all replaced with the `_AsSqlType`
alias. Any as_sql definition that annotate the return type as `Any` is also
updated to use `_AsSqlType`.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-13 09:47:01 +03:00
dependabot[bot]
29f0762540 Bump pre-commit from 2.19.0 to 2.20.0 (#1057)
Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 2.19.0 to 2.20.0.
- [Release notes](https://github.com/pre-commit/pre-commit/releases)
- [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md)
- [Commits](https://github.com/pre-commit/pre-commit/compare/v2.19.0...v2.20.0)

---
updated-dependencies:
- dependency-name: pre-commit
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-12 11:48:00 +03:00
Nick Pope
e8d52fe7da Monkeypatch some more generics. (#1050)
* Add generic monkeypatching for `FileProxyMixin`.

This fixes `TypeError: 'type' object is not subscriptable` for
`django.core.files.File` and `django.core.files.base.ContentFile`.

* Add generic monkeypatching for `ForeignKey`.

This matches the change coming in Django 4.1.

See https://github.com/django/django/pull/15571
2022-07-06 01:19:51 +03:00
PIG208
516deba2fa Improve stubs with minor fixes (#1038)
* Add a missing attribute to Jinja2.

https://github.com/django/django/blob/main/django/template/backends/jinja2.py#L35

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Make _QuerySet.extra's signature more generic.

This makes sure that we don't reject tuples, which is also valid
according to the implementation.

Relevant source code:
03eec9ff6c/django/db/models/sql/where.py (L271-L281)
03eec9ff6c/django/db/models/sql/query.py (L2307-L2308)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Fix user_passes_test to use AUTH_USER_MODEL.

According to the documentation, `test_func` is a callable that takes a
`User` (possibly anonymous).

Relevant documentation:
https://docs.djangoproject.com/en/4.0/topics/auth/default/#django.contrib.auth.decorators.user_passes_test

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* Add more accurate type annotations for dirs.

Though not documented, it's possible for `dirs` to contain
`pathlib.Path`.

`django.template.loaders.app_directories.Loader` is an example for this:
03eec9ff6c/django/template/loaders/app_directories.py
03eec9ff6c/django/template/utils.py (L97-L111)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>

* serve should return FileResponse.

There are several serve functions that should return a `FileResponse`.

Source code:
863aa7541d/django/views/static.py (L17-L53)
863aa7541d/django/contrib/staticfiles/views.py (L15-L39)
863aa7541d/django/contrib/staticfiles/handlers.py (L48-L50)
863aa7541d/django/test/testcases.py (L1680-L1687)

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-04 23:46:53 +03:00
Sigurd Ljødal
ae30525404 Fix type stubs for EmptyManager (#1039)
This should be parametrized based on the passed model. This also removes
the need for overriding the get_queryset method.
2022-07-04 12:43:58 +03:00
Petter Friberg
2a6f4647f0 Populate model argument for dynamically created managers (#1033)
* Populate model for dynamically created managers

* fixup! Populate model for dynamically created managers
2022-06-30 10:25:29 +03:00
Sigurd Ljødal
84eff75566 Resolve all queryset methods on managers as attributes (#1028)
* Add test case reproducing Sequence name not defined issue

* Resolve all manager methods as attribute

This changes to logic for resolving methods from the base QuerySet class
on managers from copying the methods to use the attribute approach
that's already used for methods from custom querysets. This resolves the
phantom type errors that stem from the copying.

* Disable cache in test case

Make sure the test will fail regardless of which mypy.ini file is being using.

Co-authored-by: Petter Friberg <petter@5monkeys.se>

* Update comments related to copying methods

* Use a predefined list of manager methods to update

The list of manager methods that returns a queryset, and thus need to
have it's return type changed, is small and well defined. Using a
predefined list of methods rather than trying to detect these at runtime
makes the code much more readable and probably faster as well.

Also add `extra()` to the methods tested in
from_queryset_includes_methods_returning_queryset, and sort the methods
alphabetically.

* Revert changes in .github/workflows/tests.yml

With cache_disable: true on the test case this is no longer needed to
reproduce the bug.

* Remove unsued imports and change type of constant

 - Remove unused imports left behind
 - Change MANAGER_METHODS_RETURNING_QUERYSET to Final[FrozenSet[str]]

* Import Final from typing_extensions

Was added in 3.8, we still support 3.7

* Sort imports properly

* Remove explicit typing of final frozenset

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>

* Add comment for test case

* Fix typo

* Rename variable

Co-authored-by: Petter Friberg <petter@5monkeys.se>
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-06-30 10:19:33 +03:00
David Smith
f8cc99ca3b Improved return type of render_to_string(). (#1036) 2022-06-30 10:16:07 +03:00
dependabot[bot]
c27b38d6b9 Bump requests from 2.28.0 to 2.28.1 (#1035)
Bumps [requests](https://github.com/psf/requests) from 2.28.0 to 2.28.1.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.28.0...v2.28.1)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-30 10:14:45 +03:00
Anders Kaseorg
214b0c7439 Support cursor.execute(psycopg2.sql.Composable) (#1029)
In addition to str, PostgreSQL cursors accept the
psycopg2.sql.Composable type, which is useful for guarding against SQL
injections when building raw queries that can’t be parameterized in
the normal way (e.g. interpolating identifiers).

In order to avoid reintroducing a dependency on psycopg2, we define a
Protocol that matches psycopg2.sql.Composable.

Documentation: https://www.psycopg.org/docs/sql.html
Related: https://github.com/python/typeshed/pull/7494

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2022-06-28 23:44:20 +03:00
Nikita Sobolev
33d4dc7dae Fix logger type in all modules (#1031)
* Fix `logger` type in all modules

* Fix CI
2022-06-28 23:25:50 +03:00
dependabot[bot]
fe2d2287a1 Bump black from 22.3.0 to 22.6.0 (#1027)
Bumps [black](https://github.com/psf/black) from 22.3.0 to 22.6.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/compare/22.3.0...22.6.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-28 09:42:09 +03:00
David Smith
926661ab4a Improved type of template.loader.get_template() (#1011)
* Improved type of template.loader.get_template()

* Removed Optional from return type.

* Edits.
2022-06-27 00:48:10 +03:00
Sigurd Ljødal
1a29ad4f97 Fix nullability of blank charfields in values and values_list (#1020)
Char fields with blank=True set should not be considered nullable in the
context of values() and values_list() querysets.

I'm also not a huge fan of the way these fields are made optional in the
constructur to the model classes, it feels like it would be better to
mark the arguments as having a default value, rather than allow sending
in None, but I'd rather keep this fix small and look at the overall
problem at a later point.
2022-06-25 14:37:25 +03:00
Jakub Hrabec
dd0fe02367 Add missing type for TestCase.captureOnCommitCallbacks (#1016)
* add missing type for TestCase.captureOnCommitCallbacks

* change default value
2022-06-25 13:41:29 +03:00
David Smith
44157a4b03 BaseContext.__copy__ (#1012)
* Improved BaseContext.__copy__()

* Update django-stubs/template/context.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>

* Updated __copy__ to use private name.

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-06-25 11:57:04 +03:00
Jakub Hrabec
c020349f2e Update RunSQL type to include parametrized sql (#1015)
* update RunSQL type to include parametrized sql

* fix Black formatting
2022-06-24 10:08:17 +03:00
w0rp
644052148a Set generic type of SimpleCookie (#1018)
Pyright complains about `response.cookies` because the generic type isn't known. `str` may or may not be the correct type to use here. Something should be set here.
2022-06-23 13:52:31 +03:00
sobolevn
f4407155a5 Do not generate release notes for django-stubs-ext 2022-06-17 18:14:44 +03:00
sobolevn
d6a9a4ef03 Fixing release pipeline 2022-06-17 18:09:00 +03:00
sobolevn
9a23ff864b Fixing release pipeline 2022-06-17 17:54:02 +03:00
sobolevn
4ea9b874f5 Add explicit test for .from_quertset Any fallback 2022-06-17 17:30:27 +03:00
Petter Friberg
023106fe45 Emit error and set fallback type for managers that can't be resolved (#999)
* Emit error and set fallback type for managers that can't be resolved

* fixup! Emit error and set fallback type for managers that can't be resolved
2022-06-17 17:19:42 +03:00
sobolevn
719cd3a6bc Fix release pipeline 2022-06-17 17:18:15 +03:00
sobolevn
4cf3b445bd Fix release pipeline 2022-06-17 17:15:28 +03:00
sobolevn
f4378112bb Release django-stubs and django-stubs-ext 2022-06-17 17:02:26 +03:00
Adam Birds
86c007d83f Add Feed to monkeypatch to fix generic issue. (#1002)
Fixes #1001
2022-06-17 16:39:11 +03:00
Nikita Sobolev
633030585d Update README.md 2022-06-17 16:33:12 +03:00
Petter Friberg
8d8b8cd1fc Set type of default django.core.cache.cache to BaseCache (#998)
* Set type of default `django.core.cache` to `BaseCache`

- The previous type `ConnectionProxy` is just a proxy class, thus
  revealing `Any` for _all_ cache methods

* fixup! Set type of default `django.core.cache` to `BaseCache`
2022-06-16 23:33:37 +03:00
Marti Raudsepp
e45ecd633e Improve hints in migration Operation class (#996) 2022-06-16 09:15:23 +03:00
Aleksander Vognild Burkow
9044a354cb Add fallback related manager in final iteration of AddRelatedManagers (#993)
If a django model has a Manager class that cannot be resolved statically
(if it is generated in a way where we cannot import it, like `objects =
my_manager_factory()`), we fallback to the default related manager, so
you at least get a base level of working type checking.
2022-06-15 18:50:53 +03:00
sterliakov
32e13c37a6 Fix manager types scope (#991)
* Fix manager types scope

* Restore incremental mode and mention in developer docs

* Separate dev mypy config and regular one

* Document config files usage
2022-06-14 20:30:13 +03:00
Adam Johnson
ae5b1a4edf Improve admin filter lookups() return type (#992) 2022-06-13 18:45:55 +03:00
dependabot[bot]
6e84c103af Bump actions/setup-python from 3 to 4 (#989)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 3 to 4.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-11 09:43:41 +03:00
dependabot[bot]
b6cd673e4c Bump requests from 2.27.1 to 2.28.0 (#990)
Bumps [requests](https://github.com/psf/requests) from 2.27.1 to 2.28.0.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.27.1...v2.28.0)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-11 09:43:33 +03:00
Terence Honles
1ce113d743 Enable GitHub auto generated release notes for GitHub releases (#988) 2022-06-11 09:43:24 +03:00
Zac Miller
f7ccf04082 Remove coreapi from requirements.txt (#987) 2022-06-09 00:04:16 +03:00
Terence Honles
a526ba75be remove unneeded submodule (removed in #485) (#982) 2022-06-07 23:07:15 +03:00
Adam Johnson
13c09921f8 Improve admin filter types (#984) 2022-06-07 12:29:44 +03:00
dependabot[bot]
195aaad1fe Bump mypy from 0.960 to 0.961 (#983)
Bumps [mypy](https://github.com/python/mypy) from 0.960 to 0.961.
- [Release notes](https://github.com/python/mypy/releases)
- [Commits](https://github.com/python/mypy/compare/v0.960...v0.961)

---
updated-dependencies:
- dependency-name: mypy
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-07 12:23:20 +03:00
Terence Honles
42321cabe6 Add GitHub release action to upload to PyPI & create GitHub release (#980)
* Add GitHub release action to upload to PyPI & create GitHub release

* Update .github/workflows/release.yml

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-06-07 12:23:03 +03:00
Anders Kaseorg
24a3b22c60 Move mypy version upper bound to a [compatible-mypy] extra (#979)
* Move mypy version upper bound to a [compatible-mypy] extra

Due to a bug in mypy 0.940 (#870), we made two changes in #871:

• pinned mypy==0.931 in requirements.txt (for running our tests);
• bounded mypy<0.940 in setup.py (for downstream users).

After the mypy bug was quickly fixed upstream in 0.941, our setup.py
bound has been repeatedly raised but not removed (#886, #939, #973).
The only changes in those commits have been to the precise wording of
error messages expected in our tests.  Those wording changes don’t
impact compatibility for downstream users, so it should be safe to go
back to allowing them to upgrade mypy independently.

Since mypy doesn’t yet guarantee backwards compatibility in the plugin
API (although in practice it has rarely been an issue), add a
django-stubs[compatible-mypy] extra for users who prefer a known-good
version of mypy even if it’s a little out of date.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>

* Update setup.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-06-05 00:08:00 +03:00
Daniel Hahler
43b082850c Fix BaseModelFormSet.save_m2m: accept self (#970)
* Fix BaseModelFormSet.save_m2m: accept `self`

Before it would result in the following when calling it:

> Attribute function "save_m2m" with type "Callable[[], None]" does not accept self argument  [misc]

* fixup! Fix BaseModelFormSet.save_m2m: accept `self`
2022-05-27 13:42:45 +03:00
Ceesjan Luiten
42d8e18bf8 Support content attribute for a Testing Response. (#968)
`content` is a documented attribute of a testing response which isn't part
of the parent HttpResponseBase:

https://docs.djangoproject.com/en/4.0/topics/testing/tools/#testing-responses
2022-05-26 13:17:22 +03:00
Alex Dutton
0a13d2c653 Fix AlterModelManagers managers annotation to be [(str, Manager), ...] (#966)
Django generates AlterModelManagers with Sequence[Tuple[str, Manager]]
arguments — not Sequence[Manager] — as shown by their tests[^1].

[^1]: https://github.com/django/django/blob/4.0.4/tests/migrations/test_operations.py#L3792-L3799

Closes #965.
2022-05-26 12:56:54 +03:00
Allex
fc6fae192e Fix false positive ModelAdmin.list_display_links=None (#964)
* Fix false positive ModelAdmin.list_display_links=None

list_display_links can be set to None to not generate any links in the list display.

https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display_links

* Update django-stubs/contrib/admin/options.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-05-26 01:27:11 +03:00
Damian Zaremba
2351051ef1 Upgrade mypy support to 0.960 (#973)
- Updates test_model_field_classes_from_existing_locations to account
  for the behaviour change in https://github.com/python/mypy/pull/12663
- Bumps the version of django-stubs for a new release
2022-05-26 01:20:44 +03:00
Maksim Kurnikov
4a90ad9edc bump version to 1.11.0 (#961) 2022-05-24 11:22:43 +02:00
Mattias Jakobsson
e221f0e053 Sync django.contrib.gis.gdal with upstream (#956) 2022-05-14 08:53:27 +03:00
henribru
8fe2bd4b9b Support passing extra classes to monkeypatch (#953)
* Support passing extra classes to monkeypatch

Closes https://github.com/typeddjango/django-stubs/issues/946#issuecomment-1122895190

* Move extra classes into separate test

* Avoid mutable default

* Fix protocol arguments
2022-05-12 20:14:59 +03:00
Sigurd Ljødal
ccef6779ad Fix type for related fields in values_list querysets (#955)
When fetching a related field in a values_list queryset Django will
return the object primary key, not model instances as was previously
what the mypy plugin assumed.
2022-05-12 09:14:17 +03:00
Sigurd Ljødal
724442b241 Fix type stubs for OuterRef (#952)
* Fix error when nesting OuterRef expressions

OuterRef(OuterRef("my_field")) is a valid expression in nested
subqueries. Mypy would complain that OuterRef was an incompatible type
because OuterRef is typed to only accept str.

* Only fix for OuterRef

* OuterRef is not guaranteed to be resolved to ResolvedOuterRef
2022-05-10 20:44:49 +03:00
Sigurd Ljødal
7d84e5473a Fix type of min_value and max_value on DecimalField (#951)
* Fix type of min_value and max_value on DecimalField

These should at the very least allow Decimals. Technically you can send
in anything that's comparable to a Decimal, but I'm not sure if it makes
sense to allow floats. Could allow both ints and Decimals I guess?

* Allow ints and floats as well

* Update django-stubs/forms/fields.pyi

* Update django-stubs/forms/fields.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-05-10 20:43:49 +03:00
Marti Raudsepp
1a36c6c379 Improve type hints of URL conf & include() (#949)
* Improve type hints of URL conf & include()

The type of `urlpatterns` list is `List[Union[URLPattern, URLResolver]]`.

* https://docs.djangoproject.com/en/dev/ref/urls/#django.urls.include
* https://docs.djangoproject.com/en/4.0/ref/urls/

* Alias _AnyURL = Union[URLPattern, URLResolver]

* Fix extract_views_from_urlpatterns
2022-05-06 09:00:21 +03:00
dependabot[bot]
4a5d330228 Bump pre-commit from 2.18.1 to 2.19.0 (#950)
Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 2.18.1 to 2.19.0.
- [Release notes](https://github.com/pre-commit/pre-commit/releases)
- [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md)
- [Commits](https://github.com/pre-commit/pre-commit/compare/v2.18.1...v2.19.0)

---
updated-dependencies:
- dependency-name: pre-commit
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-06 08:57:20 +03:00
sobolevn
69d5aa94b0 Move release.sh to scripts/ 2022-05-02 13:01:38 +03:00
Damian Zaremba
2ef7ff3309 Bump mypy 0.950 (#939)
* Bump mypy to 0.95x

* Remove the * for inferred types

There was an upstream change (https://github.com/python/mypy/pull/12459)
to remove * from inferred types in the reveal_type output.

As we are asserting the * to exist, all the test cases are now failing
on the 0.950 release. Removing the expected * to mirror the upstream
behaviour change should resolve the test failures.
2022-04-29 14:44:33 +03:00
Marti Raudsepp
0caee74490 Fix typecheck default Django version (#944)
Currently running `typecheck_tests.py` without arguments fails with "KeyError: '3.0'"
2022-04-29 10:21:20 +03:00
Marti Raudsepp
e0f45e4778 Update SimpleTestCase.assert method response types (#942)
Since PR 909, SimpleTestCase.client.get() etc methods return a class that no longer derives from `HttpResponse`, but instead `HttpResponseBase`, the `assert*` methods taking response should be updated as well.

Discovered while trying to update djangorestframework-stubs to django-stubs as of master.
2022-04-29 09:03:01 +03:00
Marti Raudsepp
f7b6a7beb4 Fix URLPattern, URLResolver pattern type (#941) 2022-04-29 09:02:19 +03:00
Marti Raudsepp
2b0bfdb46e Restore Python 3.7 compatibility (#945)
django-stubs still supports Python 3.7, but the `/` positional-only parameter syntax is supported only in Python 3.8+.

Not sure why this error wasn't caught in CI.
2022-04-29 08:51:56 +03:00
Marti Raudsepp
c836c3ac3a Fix ValidationError false positive on nested inputs (#943)
Reverts parts of PR 909.
2022-04-28 19:19:18 +03:00
sterliakov
6226381484 Recover after #909 (#925)
* Fix stubs related to `(Async)RequestFactory` and `(Async)Client`

* Revert incorrect removal.

* Allow set as `unique_together`, use shared type alias.

* Revert `Q.__init__` to use only `*args, **kwargs` to remove false-positive with `Q(**{...})`

* Add abstract methods to `HttpResponseBase` to create common interface.

* Remove monkey-patched attributes from `HttpResponseBase` subclasses.

* Add QueryDict mutability checks (+ plugin support)

* Fix lint

* Return back GenericForeignKey to `Options.get_fields`

* Minor fixup

* Make plugin code typecheck with `--warn-unreachable`, minor performance increase.

* Better types for `{unique, index}_together` and Options.

* Fix odd type of `URLResolver.urlconf_name` which isn't a str actually.

* Better types for field migration operations.

* Revert form.files to `MultiValueDict[str, UploadedFile]`

* Compatibility fix (#916)

* Do not assume that `Annotated` is always related to django-stubs (fixes #893)

* Restrict `FormView.get_form` return type to `_FormT` (class type argument). Now it is resolved to `form_class` argument if present, but also errors if it is not subclass of _FormT

* Fix CI (make test runnable on 3.8)

* Fix CI (make test runnable on 3.8 _again_)
2022-04-28 13:01:37 +03:00
Guillaume Andreu Sabater
16499a22ab added unique annotation on model Field (#936) 2022-04-27 22:57:58 +03:00
dependabot[bot]
268ec3bcd5 Bump pytest from 7.1.1 to 7.1.2 (#932)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.1.1 to 7.1.2.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.1.1...7.1.2)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-25 19:58:02 +03:00
Oleg Höfling
8e875b13f7 add fail_silently attribute for BaseEmailBackend instances (#931)
Signed-off-by: Oleg Hoefling <oleg.hoefling@ionos.com>
2022-04-21 19:45:51 +03:00
Chris Beaven
a1b647700b Fix incorrect instance arg for BaseInlineFormSet.__init__ (#928)
* Fix BaseInlineFormSet generic to retain parent model class info

* Add in test for generic formset improvements
2022-04-19 08:59:50 +03:00
rolandcrosby-check
30bf4dab6c Update media render return values to SafeString (#923) 2022-04-14 23:53:52 +03:00
Xavier Francisco
40bf7a562d Add missing type for setup_databases (#919)
* Add missing type for setup_databases

`django.test.utils` was seemingly missing the type for `setup_databases`. 

This change resolves my issue locally. The type was copied directly from `django.test.runner`.

* Fix typecheck_tests runner

Co-authored-by: Xavier Francisco <xavier.n.francisco@gmail.com>
2022-04-13 12:56:57 +03:00
Jim King
e468ee97da issue-914: ValidationError.error_dict type fix (#915) 2022-04-09 10:06:45 +03:00
Guillaume Andreu Sabater
d8b417456f added ExtractIsoWeekDay (#912)
https://docs.djangoproject.com/en/3.2/ref/models/database-functions/#django.db.models.functions.ExtractIsoWeekDay
2022-04-06 20:08:23 +03:00
Nikita Sobolev
2dad9228eb Switch to setuptools (#911) 2022-04-06 13:02:56 +03:00
dependabot[bot]
21bed1ccf3 Bump pre-commit from 2.17.0 to 2.18.1 (#910)
Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 2.17.0 to 2.18.1.
- [Release notes](https://github.com/pre-commit/pre-commit/releases)
- [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md)
- [Commits](https://github.com/pre-commit/pre-commit/compare/v2.17.0...v2.18.1)

---
updated-dependencies:
- dependency-name: pre-commit
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-04 14:18:28 +03:00
sterliakov
f69e0639c7 Large update (#909)
* Make module declaration precise.

* Make settings match real file.

* Replace `include` with import.

* Make types more specific.

* Replace `WSGIRequest` with `HttpRequest` where possible.

* Replace all `OrderedDict` occurrences with plain `Dict` (it is not used in Django 3.2 and later)

* Add fake datastructures for convenience: _PropertyDescriptor and _ListOrTuple now can live here. Added _IndexableCollection (often useful as alias for 'sequence or queryset')

* Actualize other datastructures.

* Rework MultiValueDict to reflect the fact that some methods can return empty list instead of value.

* Deprecate SafeText in favor of SafeString.

* Minor improvements to utils

* Disallow using str in TimeFormat and DateFormat, drop removed fmt `B`

* Do not let classproperty expect classmethod, make return value covariant.

* Sync with real file.

* Improve types for timezone.

* Sync deprecated, new and removed features in translation utils.

* Drop removed files, sync huge deprecations.

* Fix incompatible decorators (properties, contextmanagers)

* Rework pagination.

* Sync validators with real code. Add _ValidatorCallable for any external use (field validation etc.)

* Add shared type definitions (for fields of both forms and models). Actualize model fields. Mark keyword-only args explicitly in stubs (where code uses **kwargs). Disallow bytes for verbose_name.

* Make all checks return Sequence[CheckMessage] or subclass to be covariant.

* Add bidirectional references between backend.base and other files. Replace some Any's with specific types.

* Actualize db.migrations: remove removed methods, replace "None" annotations in wrong places, improve some wrong annotations.

* Actualize db.utils to match real file.

* Replace FileResponse and TemplateResponse with HttpResponse(Base) where needed: at least HttpResponseNotModified/HttpResponseRedirect can be returned instead of it, so annotation was wrong.

* Replace Any in forms where possible. Actualize class bases and method arguments.

* Improve typing of serializers.

* Actualize views, rename variable bound to Model to _M for consistency.

* Make types of file-related code consistent. Disallow using bytes as path, because many methods expect str-only paths. Make File inherit from IO[AnyStr] instead of IO[Any]: it makes impossible to instantiate file of union type, but allows precise types for some methods.

* Minor improvements: stop using None as annotation in wrong places, replace obvious Any's with precise types, actualize methods (missing/renamed/signature changed).

* Allow less specific containers, replace Any's with specific types.

* Improve types for requests and responses.

* Use AbstractBaseUser instead of User in auth.

* Use broader type for permission_required

* Use wider container types. Add 'type: ignore' to avoid issues with mypy.stubtest.

* Disallow using backend class as argument (it is passed to import_string).

* Add required methods to PasseordValidator.

* Allow using Path instance as argument.

* Actualize methods.

* Add 'type: ignore' to avoid issues with mypy.stubtest.

* Replace Any's with specific types and BaseForm with ModelForm.

* Actualize contrib.postgres

* Remove render_to_response, add 'get_absolute_url' to corresponding protocol.

* Actualize signers.

* Use precise types for handlers. Disallow str as stream type for LimitedStream.

* Exact types for ValidationError

* Replace wrong used Union with Sequence.

* Actualize static handlers.

* More specific types for admin. Fixes #874.

* Improve types and replace 'Tags' with str (it isn't Enum, so annotation was wrong).

* Replace Any with specific types, actualize signatures.

* Add async variants of handlers and clients. Use fake class to distinguish between request types in RequestFactory and AsyncRequestFactory.

* Fix signature, minor improvements.

* Actualize signatures and class names, replace Any with more specific types.

* Fix signature.

* Add some missing methods to Collector

* Combinable rarely returns Self type: almost always it's CombinedExpression.

* No Random in source anymore.

* Drop removed SimpleCol.

* Replace _OutputField with Field: nothing in docs about strings.

* Introduce reusable types, add missing methods. Remove strange types (probably created by stubgen). Remove RawQuery from Compiler: it obviously doesn't work with RawQuery.

* Use literal constants.

* Actualize base classes.

* Callable is not accepted by get_field.

* Add precise types.

* Use property and broader containers where possible. Add missing methods.

* Actualize indexes.

* More specific types for signals.

* Fix signatures, drop missing methods.

* Actualize window functions to match source.

* Actualize text functions, add missing methods, use type aliases for consistency.

* Add missing property decorators, methods and attributes. Use type aliases. Remove absent YearComparisonLookup and any SafeText references (they aren't related to lookups at all).

* Use bound TypeVar, mark all BuiltinLookup descendants as generic explicitly. Remove strange Union from Lookup.__init__

* Apply type alias, fix base class and argument name.

* Actualize BaseExpression methods.

* Fix imports.

* Add missing class and fix incompatible bases.

* Use same types in __init__ and attribute.

* OrderBy accepts F or Expression.

* Non-expressions are converted to Values.

* Add missing attributes.

* Add missing methods, fix 'None' argument type.

* Define properties where possible, remove 'None' argument annotations, remove inadequate type in make_immutable_fields_list.

* Remove absent QueryWrapper. Replace some Any with precise types.

* Fix wrong types and actualize signatures. Deny ManagerDescriptor.__get__ on model instances.

* Use more specific types.

* Arity can be None in subclasses.

* Reformat with black

* Make DeletionMixin generic.

* Fix wrong type variable in _RequestFactory.

* Fix variable name in signature.

* Disallow returning None from Form.clean()

* Allow again returning None from Form.clean

* Drop some unused imports.

* Add tests for MultiValueDict.

* Add tests for utils.timezone.

* Fix #834.

* Add more files to import_all test

* Allow None for `context_object_name`

* Fix CI

* Fix test to work on python 3.8
2022-04-04 00:41:41 +03:00
Sigurd Ljødal
dc4c0d9ee4 Emit error instead of raising on union custom QuerySet (#907)
* Add reproducer for failing case

* Emit warning instead of crashing when encountering enum

* Remove prints, slightly tweak error message

* Remove unused import

* Run black and isort

* Run isort on .pyi file

* Remove unrelated issue from test case
2022-04-01 22:07:55 +03:00
Petter Friberg
0e98cc9114 Don't rely on django.db.models.manager.Manager metadata for dynamically created manager (#904) 2022-03-31 23:37:37 +03:00
Sigurd Ljødal
76e3fdb479 Fix missing related managers on some models (#902)
* Fix missing related managers on some models

I was seeing an issue where some related managers were missing from some
models. Traced the issue down to this line, where it appears that if we
hit a relation with a non-default(?) reverse manager the iteration
stopped. I _think_ this is supposed to be a continue statement instead.
It appears to work in the project I'm working in at least.

* Add test case

* Add test case
2022-03-31 23:36:22 +03:00
Marti Raudsepp
49d855547b Improve MultiValueDict/QueryDict dict() return (#899)
According to Django documentation and code, the `MultiValueDict.dict()` method only returns singular values for each key, never a list.

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.dict

3de787a70b/django/utils/datastructures.py (L215-L217)
2022-03-31 11:47:45 +03:00
Marti Raudsepp
212ef40c3d Update Black dependency to fix CI lint (#900)
* Update Black dependency to fix CI lint

Closes #896.

Black 22.3.0 fixes incompatibility with Click 8.1.0:
https://github.com/psf/black/pull/2966

This currently causes the CI to fail, e.g. https://github.com/typeddjango/django-stubs/runs/5756075543

* Reformat with Black v22
2022-03-31 11:29:31 +03:00
Petter Friberg
92e5f202ac Cache dynamically created manager nodes (#840)
- Non plugin generated, "cross_ref"s points to dynamically
  created managers (e.g. `Model.objects`) and can make Mypy fail on
  cached runs
2022-03-31 10:21:21 +03:00
sobolevn
4e3f9d6f06 Version 0.10.1 release 2022-03-28 16:09:09 +03:00
Mark Gregson
2fad97af03 login_form is a class (#885) (#891) 2022-03-28 08:44:40 +03:00
henribru
a14fb28f33 Import Literal from typing_extensions for 3.7 compatibility (#889) 2022-03-27 20:28:52 +03:00
henribru
aa5f114575 Remove Python 3.6 trove classifier (#887) 2022-03-26 14:40:24 +03:00
Nikita Sobolev
3c58270a78 Version 1.10.0 release (#886)
* Version 1.10.0 release

* Fixes CI

* Fixes CI
2022-03-26 09:22:13 +03:00
Konstantin Alekseev
3f340c9df3 Fix mypy cache of WithAnnotation types (#725) 2022-03-25 01:13:20 +03:00
w0rp
1672b54c89 Set type parameters for Field in get_fields() (#882)
* Set type parameters for Field in get_fields()

This fixes an issue with Pyright strict type checking where Pyright complains that the type parameters aren't known.

* Fix type parameters in other methods
2022-03-25 00:14:16 +03:00
Sebastian Wagner
32a33c332d Don't serialize annotated types (#881)
Signed-off-by: Sebastian Wagner <sebastian@inter.link>

Co-authored-by: Sebastian Wagner <sebastian@inter.link>
2022-03-22 14:33:52 +03:00
Anderson Luiz de Souza
10e06947d7 Fix missing args on SlugField.__init__ (#879) 2022-03-20 19:40:55 +03:00
dependabot[bot]
f4d3895595 Bump pytest from 7.1.0 to 7.1.1 (#880)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.1.0 to 7.1.1.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.1.0...7.1.1)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-19 20:37:03 +03:00
Himanshu Balasamanta
5c75869dd3 Fixes #822 (#868)
Signed-off-by: Himanshu-Balasamanta <himanshubb.eee18@itbhu.ac.in>
2022-03-15 12:46:49 +03:00
dependabot[bot]
acfafaae14 Bump pytest from 7.0.1 to 7.1.0 (#869)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.0.1 to 7.1.0.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.0.1...7.1.0)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-14 21:27:12 +03:00
Himanshu Balasamanta
f9f6c827c1 Fixes #870 (#871)
* Fixes #870

Signed-off-by: Himanshu-Balasamanta <himanshubb.eee18@itbhu.ac.in>

* Updated mypy version in setup.py to == 0.931

* Update setup.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-03-14 21:17:53 +03:00
Adam Johnson
eb6991b008 Improve forms stubs (#862)
* `default_renderer` may be a renderer class, instance, or `None`: https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.default_renderer
* `field_order` should be a list/sequence of field names, or `None`: https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.field_order
* `cleaned_data` should be a dict/mapping of field names to values, as returned by `clean()`: https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.cleaned_data . I similarly updated `clean()` to allow arbitrary mappings, since it may be legitimate to use some special mapping class.
* `clean()` does not need to return a mapping - https://docs.djangoproject.com/en/4.0/ref/forms/validation/#validating-fields-with-clean : “If your form inherits another that doesn’t return a `cleaned_data` dictionary in its `clean()` method (doing so is optional)...”
* `is_multipart` returns a `bool`: https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.is_multipart
* `hidden_fields` and `visible_fields` aren't documented, but they return lists of `BoundField` instances: d8b437b1fb/django/forms/forms.py (L501-L513)
2022-03-02 18:02:54 +03:00
dependabot[bot]
078925a0fc Bump actions/checkout from 2 to 3 (#861)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-02 11:05:16 +03:00
dependabot[bot]
cf31c1de7b Bump actions/setup-python from 2 to 3 (#860)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 2 to 3.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-01 09:42:54 +03:00
Ethan Corey
104012b817 Added widget_type annotation to BoundField (#855)
* Add widget_type annotation to BoundField

See https://github.com/django/django/blob/main/django/forms/boundfield.py#L283

* Tweaked annotation to be `AnyStr`, not `str`

* Reverted to use `str` as return type
2022-02-22 22:47:43 +03:00
rolandcrosby-check
850df1655a Make formfield_from_dbfield return forms.Field instead of models.Field (#857) 2022-02-22 20:44:44 +03:00
dependabot[bot]
30bed85e0d Bump gitpython from 3.1.20 to 3.1.27 (#854)
Bumps [gitpython](https://github.com/gitpython-developers/GitPython) from 3.1.20 to 3.1.27.
- [Release notes](https://github.com/gitpython-developers/GitPython/releases)
- [Changelog](https://github.com/gitpython-developers/GitPython/blob/main/CHANGES)
- [Commits](https://github.com/gitpython-developers/GitPython/compare/3.1.20...3.1.27)

---
updated-dependencies:
- dependency-name: gitpython
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-21 09:47:17 +03:00
Joon Hwan 김준환
ab50fb9876 cache_page should be Optional[float] . (#851)
* cache_page can use None .

* Apply black
2022-02-14 15:14:28 +03:00
Joon Hwan 김준환
319ab7f9f7 get_cache_key can have multiple httprequest types. (#852)
* Update cache.pyi

* Apply black
2022-02-14 15:06:01 +03:00
dependabot[bot]
017ac1ce85 Bump pytest from 7.0.0 to 7.0.1 (#850)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.0.0 to 7.0.1.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/7.0.0...7.0.1)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-14 10:50:43 +03:00
Jacob Walls
bf84546b9e Fix return type of MigrationRecorder.applied_migrations() (#793)
Matches return type of MigrationLoader.applied_migrations, which reads from here.
2022-02-10 18:29:14 +03:00
Kevin Marsh
3eab36a5c4 DatabaseClient: add missing class methods and reflect Django 3.2 refactor (#846)
* DatabaseClient: add missing class method `settings_to_cmd_args_env` and add missing arg to `runshell`

The `DatabaseClient.runshell()` was refactored in Django 3.2 to be more standardized
across the different database backends.

* DatabaseClient: make `settings_dict` dict type better by specifying key/value types

* tests: add missing db backend client files to `import_all_modules`
2022-02-10 09:29:44 +03:00
dependabot[bot]
01a31d2fd5 Bump pytest from 6.2.5 to 7.0.0 (#845)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 6.2.5 to 7.0.0.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/6.2.5...7.0.0)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-07 09:12:33 +03:00
Rob Percival
74083c9f8a Correct return type of get_commands() (#838)
According to the docstring for this function, "the instantiated module can be placed in the dictionary in place of the application name".
2022-01-31 20:28:32 +03:00
dependabot[bot]
8843acde3e Bump black from 21.12b0 to 22.1.0 (#836)
Bumps [black](https://github.com/psf/black) from 21.12b0 to 22.1.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/commits/22.1.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-31 08:45:07 +03:00
Petter Friberg
8aae836a26 Model.__init__ supporting same typing as assigment (#835)
* `Model.__init__` supporting same typing as assigment

* Update mypy_django_plugin/django/context.py
2022-01-29 12:07:26 +03:00
Seth Yastrov
c556668d7a Attempt to fix 'INTERNAL ERROR using annotate'. (#753)
KeyError: "Failed qualified lookup: '_AnyAttrAllowed' (fullname =
'django._AnyAttrAllowed')."

https://github.com/typeddjango/django-stubs/issues/745
2022-01-28 21:43:03 +03:00
Cory Dolphin
28d6dc992c Export Datasource, Driver from gdal (#797) 2022-01-28 21:42:26 +03:00
emma-blossom
73290597f8 Make SomeModel._default_manager return a BaseManager[SomeModel] instead of BaseManager[Model] (#817)
* _default_manager has more specific type for TypeVars

* remove unnecessary # type: ignore

* add test for _base_manager

* add overloads for classproperty.__get__

* readd # type: ignore for WSGIRequestHandler.connection, fails in github's pipeline

* fix _base_manager test: mypy reveals an inferred type

Co-authored-by: Michael Pöhle <michael.poehle@polyteia.de>
2022-01-28 21:42:11 +03:00
Maarten ter Huurne
060dc3b41a Add object_list to BaseListView (#833)
While `object_list` isn't defined at construction, `BaseListView.get()`
sets it when handling a request, so in practice it is defined whenever
a list view is doing its work.

The Django documentation describes `object_list` as "the list of
objects (usually, but not necessarily a queryset)", so I picked
`Sequence` as the type.

Closes #790
2022-01-28 21:41:30 +03:00
rolandcrosby-check
5d3768e593 Allow *args to be Any for generic views (#831) 2022-01-26 10:00:26 +03:00
Petter Friberg
515e382d4a Fix .filter-kwargs lookup crash during cached runs (#828)
* Fix .filter-kwargs lookup crash during cached runs

* Update mypy_django_plugin/lib/helpers.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2022-01-24 13:24:09 +03:00
Petter Friberg
220f0e4cf0 Reuse reverse managers instead of recreating (#825) 2022-01-22 21:13:05 +03:00
Petter Friberg
edec5a1c99 Notify when Manager.from_queryset happens inside model class body (#824)
* Refactor to more easily support additional config options

* Notify when Manager.from_queryset happens inside model class body

- A warning will be emitted whenever `Manager.from_queryset` happens
  inside of a model class body

* Resolve generated default manager types before final iteration

A default manager on a model should always exist, eventually. Although,
we extend to look through dynamically generated managers on each
iteration instead of deferring until the final iteration.
2022-01-21 19:46:56 +03:00
dependabot[bot]
140bb38a79 Bump pre-commit from 2.16.0 to 2.17.0 (#823)
Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 2.16.0 to 2.17.0.
- [Release notes](https://github.com/pre-commit/pre-commit/releases)
- [Changelog](https://github.com/pre-commit/pre-commit/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pre-commit/pre-commit/compare/v2.16.0...v2.17.0)

---
updated-dependencies:
- dependency-name: pre-commit
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-19 09:58:07 +03:00
Nikita Sobolev
c04201c859 Delete FUNDING.yml 2022-01-17 15:04:29 +03:00
sobolevn
5bbe353e92 Add FUNDING.yml and drop python3.6 2022-01-17 15:00:27 +03:00
Aleksander Vognild Burkow
27e5908762 Update project to use mypy 931 (#819) 2022-01-17 14:58:16 +03:00
Petter Friberg
a9e41a8ba9 Fix suggested changes from #820 (#821) 2022-01-16 21:13:47 +03:00
Petter Friberg
99f28387fb Set custom queryset methods as manager attrs instead of method copies (#820)
Instead of copying methods over from a QuerySet passed to a basemanager
when invoking '<BaseManager>.from_queryset', any QuerySet methods are
declared as attributes on the manager.

This allows us to properly lookup any QuerySet method types via a
'get_attribute_hook' and will thus remove disorienting phantom errors
occuring from mypy trying to resolve types only existing in the module
where the _original_ (and real) queryset method was declared.
2022-01-16 12:14:33 +03:00
rolandcrosby-check
1da693ebff Fix extra_context argument type in admin views (#816)
The `extra_context` argument to `ModelAdmin.changeform_view`,
`add_view`, `change_view`, `changelist_view`, `delete_view`, and
`history_view` is used to pass extra context variables to a template, so
all of these arguments should have type `Optional[Dict[str, Any]]`.
Instead, these are currently typed as `Optional[Dict[str, bool]]`,
`Optional[Dict[str, str]]`, or `None`.
2022-01-13 23:03:03 +03:00
rolandcrosby-check
3c1e9e3884 Allow Iterable[Iterable[Any]] as args_generator argument to format_html_join (#722)
* Allow List[Tuple[Any]] as args_generator argument to format_html_join

format_html_join's args_generator argument can be anything that contains
tuples of things that can be coerced to strings or that have a
`__html__` method.

Fixes #721.

* Use `Iterable[Iterable[Any]]` as `args_generator` type

* Run linter
2022-01-12 09:44:14 +03:00
dependabot[bot]
4cdf8a8d39 Bump pytest-mypy-plugins from 1.9.2 to 1.9.3 (#815)
Bumps [pytest-mypy-plugins](https://github.com/TypedDjango/pytest-mypy-plugins) from 1.9.2 to 1.9.3.
- [Release notes](https://github.com/TypedDjango/pytest-mypy-plugins/releases)
- [Changelog](https://github.com/typeddjango/pytest-mypy-plugins/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TypedDjango/pytest-mypy-plugins/compare/1.9.2...1.9.3)

---
updated-dependencies:
- dependency-name: pytest-mypy-plugins
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-12 09:42:53 +03:00
rolandcrosby-check
7701957e4f Fix annotation of ModelAdmin.get_object (#812)
* Fix annotation of ModelAdmin.get_object

The type annotation in django-stubs indicated that the type of the
`from_field` argument to `ModelAdmin.get_object` should be `None`. In
fact, `None` is the default value of that argument. If the argument is
not `None`, [it is passed to a model's `_meta.get_field` method][impl], which
takes an argument of type `Union[Callable[..., Any], str`.

[impl]: ac5cc6cf01/django/contrib/admin/options.py (L767)

* Fix formatting
2022-01-08 10:48:29 +03:00
dependabot[bot]
fafb200e90 Bump requests from 2.27.0 to 2.27.1 (#807)
Bumps [requests](https://github.com/psf/requests) from 2.27.0 to 2.27.1.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.27.0...v2.27.1)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-06 12:39:00 +03:00
Tom Carrick
118f50307c Allow expressions in UniqueConstraint (#806)
* Allow expressions in UniqueConstraint

* Use ellipsis

* And for fields
2022-01-06 12:07:24 +03:00
Abhyudai
3761c16c51 Change return type of queryset.bulk_update to int (#683)
- the change was made in the commit cd124295d8.
2022-01-05 18:42:47 +03:00
Gergely Kalmár
c65e2c48db Add typing to mypy plugin (#804) 2022-01-05 16:21:14 +03:00
Nikita Sobolev
ed68fbc99f Update typecheck_tests.py 2022-01-04 20:32:50 +03:00
Nikita Sobolev
9cad4fbfeb Delete misspel.yml 2022-01-04 20:32:18 +03:00
dependabot[bot]
3a27d8bb91 Bump requests from 2.26.0 to 2.27.0 (#803)
Bumps [requests](https://github.com/psf/requests) from 2.26.0 to 2.27.0.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.26.0...v2.27.0)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-04 11:19:24 +03:00
Carl Johan Hambro
49bed6c28d Fix type for templatetag (#801) 2021-12-31 11:56:10 +03:00
Gabriel Augendre
3b02222beb Update syndication Feed class (#800)
* Update syndication Feed class

* Fix typing
2021-12-30 16:33:29 +03:00
Cory Dolphin
9483865284 Make geos.GEOSGeometryBase.equals_exact accept float (#796) 2021-12-29 11:16:16 +03:00
Gabriel Augendre
1834242e46 Fix Feed.get_object signature (#798)
get_object's default implementation returns None but subclasses
are allowed to override this method and make it return anything.

The returned object would then be passed to other methods
to publish different data for different URL parameters.

https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/
2021-12-29 11:07:43 +03:00
sobolevn
3b303480b3 Rename requirements.txt file for dependabot to work 2021-12-25 11:11:15 +03:00
Nikita Sobolev
b883e192e4 Adds better id and pk handling (#791) 2021-12-18 13:09:22 +03:00
w0rp
4a0dd04611 Set types for on_delete functions (#772)
Set types for on_delete functions so they can be provided as values to
the on_delete attribute of ForeignKey in Pyright's strict mode.
2021-12-17 22:20:01 +03:00
Nikita Sobolev
feb0bfa4a6 Updates deps (#788)
* Updates deps

* Updates deps
2021-12-16 22:39:12 +03:00
Nikita Sobolev
02a39f722d Replace toml with tomli (#787)
* Replace `toml` with `tomli`

* Replace `toml` with `tomli`
2021-12-16 22:19:34 +03:00
Nikita Sobolev
b50a9077f8 Adds django@4.0 support (#786)
* Adds django@4.0 support

* Fixes CI

* Fixes CI

* Ignore new error for django4.0

* Fixes
2021-12-16 21:51:46 +03:00
sobolevn
e9b328a935 Updates deps, adds mypy@0.920 compat, adds dependabot 2021-12-16 13:11:06 +03:00
Nikita Sobolev
eb80b949af Refs #774 (#777)
* Refs #774

* Update test_create.yml
2021-12-15 15:53:24 +03:00
Chris Beaven
1219d62b6a Add Model._base_manager (#776) 2021-12-15 09:08:45 +03:00
Chris Beaven
daf6c659f0 Update autoreload to Django 3.2 (#775)
* Update autoreload stub to Django 3.2

* Fix some subclass return types

* types for watchmanreloader attributes

* Don't reference an redundant attribute in WatchmanReloader
2021-12-15 09:06:32 +03:00
w0rp
059471101c Fix the get_field type for Pyright (#773)
This PR fixes the type of get_field so it won't report errors in
Pyright's strictest type checking mode.
2021-12-13 20:05:23 +03:00
Vadim Safonov
ccbbf86d0e Update signature for Django 3.1 Paginator (#770) 2021-12-09 22:35:32 +03:00
Chris Beaven
69d4b1a86d More accurate template.Parser parse_until type (#769) 2021-12-09 11:26:26 +03:00
Marti Raudsepp
6436a10d5a Add more precise RunSQL, RunPython migration hints (#768) 2021-12-08 15:11:35 +03:00
Marti Raudsepp
79d34d6f46 Add ValidationError type hints (#767) 2021-12-08 15:09:20 +03:00
Kevin Marsh
e5361f1e04 Fix QuerySet.create and Manager.create annotation since it doesn't accept *args (only **kwargs) (#762) 2021-11-30 18:37:54 +03:00
Stanislav Mikhailov
593d04d6e9 Fixed the types in ManyToManyField according to their definition in Django. (#758) 2021-11-24 01:13:45 +03:00
Sigurd Ljødal
a57ae4fc76 Fix BaseConnectionWrapper.execute_wrapper (#752)
This is a context manager, not an iterator.

Currently mypy will complain if it's used as documented.
2021-11-15 18:14:42 +03:00
David Cain
331042d1c7 Add signature for Django 3.2 TimestampSigner (#751)
Django 3.2 introduced two new methods: `sign_object` and
`unsign_object` which can sign/unsign "complex data structures" such as
lists, tuples, dictionaries:

https://docs.djangoproject.com/en/3.2/topics/signing/#django.core.signing.TimestampSigner

Because the methods take an arbitrary serializer (a JSON serializer by
default, but not guaranteed), we cannot be sure of the type of `obj`.
2021-11-13 22:56:27 +03:00
Avery Fischer (biggerfisch)
b5c20100ff Update MigrationExecutor stubs to use Sequence (#749)
There is no need for a specific List type here, using a higher type
works fine and allows more working code to pass type-checking.
2021-11-12 20:10:24 +03:00
Petter Friberg
48aaf3d2ac Implement stubs for views.decorators.common.no_append_slash (#743) 2021-11-01 18:04:58 +03:00
Chris Beaven
640553dcd7 Fix boundfield method parameters (#741) 2021-10-26 14:34:08 +03:00
Yukio Mizuta
95060b54c2 Update send_mail recipient_list type from List[str] to Sequence[str] (#740) 2021-10-22 21:51:57 +03:00
Simon Charette
09c3dc894b Adjust django.core.signing.dumps and loads key type. (#739)
An optional key can be provided to these functions.
2021-10-22 21:02:01 +03:00
9482f2f81c fix django.contrib.auth.models.Group.natural_key no return type (#724) 2021-10-19 15:03:53 +03:00
Brian Helba
676750e090 Add a definition for Storage.get_alternative_name (#732)
See: f5802a21c4/django/core/files/storage.py (L65)
2021-10-19 14:53:22 +03:00
Brian Helba
7c87c720ad Correct the type of FileField.storage (#731)
* Correct the type of FileField.storage

This instance property can't be a callable. Although the FileField constructor
allows a callable, it is immediately resolved to an instance of Storage.
See: f5802a21c4/django/db/models/fields/files.py (L231-L235)

* Correct the type of FieldFile.storage

This instance property is copied directly from `FileField.storage` and should be
the same type.
See: f5802a21c4/django/db/models/fields/files.py (L21)
2021-10-19 14:40:17 +03:00
Rob Percival
9938378e94 Make AddRelatedManagers look for "objects" on parent model (#730)
* Add failing test for relation to model inheriting `objects`

Fails with:
```
pytest_mypy_plugins.utils.TypecheckAssertionError: Invalid output:
Expected:
  main:2: note: Revealed type is "myapp.models.MyUser*"
  main:3: note: Revealed type is "myapp.models.MyUser*"
  <45 (diff)
  <45 (diff)
Actual:
  main:2: note: Revealed type is "myapp.models.MyUser*"
  main:3: note: Revealed type is "myapp.models.MyUser*"
  main:6: error: "MyUser" has no attribute "book_set" (diff)
  main:6: note: Revealed type is "Any"          (diff)
  main:7: error: "MyUser" has no attribute "article_set" (diff)
  main:7: note: Revealed type is "Any"          (diff)
```

* Make AddRelatedManagers look for "objects" on parent model

Previously, AddRelatedManagers would fail if a related model had inherited
its `objects` field from a parent class. This would result in missing
relation attributes. This is fixed by using `get()` instead of `names`;
the former searches the MRO for the symbol, whereas the latter only looks
for symbols declared directly on the class.
2021-10-19 14:31:14 +03:00
Nikita Sobolev
7ac33f3a28 Fixes CI (#734)
* Fixes CI

* Fixes CI

* Fixes CI
2021-10-19 14:10:25 +03:00
Terence Honles
fb12560981 update all path related operations to have more accurate types (#713) 2021-09-11 22:41:16 +03:00
Terence Honles
799b41fe47 fix typing on HttpResponse and StreamingHttpResponse (#712)
While the documentation for `HttpResponse` and `StreamingHttpResponse`
*says* `content` and `streaming_content` should be bytestrings [1] or an
iterable of bytestrings respectively [2], this is not what the API
supports [3] [4] and there are tests which make sure the API supports
more than bytestrings [5] [6] [etc]. Before assigning `content` or
`streaming_content` the code paths will call  `self.make_bytes` to
coerce the value to bytes.

[1]: ecf87ad513/django/http/response.py (L324-L327)
[2]: 0a28b42b15/django/http/response.py (L395-L399)
[3]: ecf87ad513/django/http/response.py (L342-L362)
[4]: 0a28b42b15/django/http/response.py (L415-L427)
[5]: 0a28b42b15/tests/cache/tests.py (L2250)
[6]: 0a28b42b15/tests/i18n/urls.py (L8)
2021-09-10 23:18:20 +03:00
Terence Honles
fb4d20475b add HashedFilesMixin.url argument force (#714) 2021-09-10 10:02:48 +03:00
Craig
a1f3712c43 Add SmallAutoField (#710)
* Add SmallAutoField

* Test SmallAutoField presents as int
2021-09-09 15:58:03 +03:00
sobolevn
372b1340a0 Version django-stubs-ext@0.3.1 release 2021-09-07 22:08:49 +03:00
Eero Ruohola
6424e33a74 Fix BaseModelForm not working with generic type parameter (#705)
Resolves: https://github.com/typeddjango/django-stubs/issues/703
2021-09-07 22:07:22 +03:00
Eero Ruohola
b6d3373c34 Add typing-extension as a direct dependency of django-stubs-ext (#707)
Needed, because `django-stubs-ext` generally has to specified as a
production dependency (to use the monkey patching). `django-stubs` does
have `typing-extensions` as a dependency, but it is often used only as a
dev dependency as it has not runtime functionality.

Resolves: https://github.com/typeddjango/django-stubs/issues/702
2021-09-07 12:01:21 +03:00
Nikita Sobolev
f98330356c Update bug.md 2021-09-04 20:10:23 +03:00
sobolevn
a33d8a9e59 Version 1.9.0 release 2021-09-04 11:54:02 +03:00
sobolevn
d6ccecdd73 Version 1.9.0 release 2021-09-04 11:33:39 +03:00
sobolevn
321284ac62 Version 1.9.0 release 2021-09-04 11:31:11 +03:00
sobolevn
a0f893ea3d Version django-stubs-ext@0.3.0 release 2021-09-04 11:30:30 +03:00
PIG208
0d8dd85442 Minor fixes to improve django-stubs (#695)
* Use `Sequence` instead of `Iterable` for `send_messages`.

According to the documentation
(https://docs.djangoproject.com/en/3.2/topics/email/#email-backends),
`email_messages` is a list. Using `Iterable` will make it hard for
subclasses to implement this method utilizing functions like `__len__`.
While this still allows subclasses to accept `Iterable`.

* Fix function signature of `authenticate` of `BaseBackend`.

1. BaseBackend no longer requires the username and password argument.

They were removed 3 years ago in the commit below when `BaseBackend` is added:
75337a6050

2. `request` is optional for `authenticate` method.

According to django documentation, the authenticate method does not
necessarily require the request object.

https://docs.djangoproject.com/en/3.2/topics/auth/default/#authenticating-users

* Tighten the type of `streaming_content` to `Iterator[bytes]`.

It is an iterator of a bytestring according to the documentation:
https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.StreamingHttpResponse.streaming_content

* Fix function signature of `django.contrib.staticfiles.serve`.

Since this `serve` function uses `django.views.static.serve` that
accepts `HttpRequest` as its first argument, it is more reasonable
to type it with `HttpRequest` instead of `WSGIRequest`.

Related:
https://github.com/django/django/blob/main/django/contrib/staticfiles/views.py#L39
2021-08-16 10:59:04 +03:00
PIG208
a6a81797d3 Add py.typed to package distribution of django_stubs_ext. (#694) 2021-08-15 17:52:44 +03:00
PIG208
8674c48c59 Fixes a broken link in CONTRIBUTING.md (#690) 2021-08-12 19:50:29 +03:00
Tim Nyborg
44f7c25a4e extend ProtectedError and RestrictedError stubs (#682)
types for their properties
2021-08-03 11:13:15 +03:00
Abhyudai
696f39b58c Remove assertions for mypy builtins (#685) 2021-08-01 11:14:13 +03:00
Abhyudai
01eecf901f Add tests for some queryset methods (#684) 2021-08-01 11:12:06 +03:00
Abhyudai
695a7d71a7 Update type of BinaryField to include memoryview as well (#686) 2021-08-01 11:10:15 +03:00
Seth Yastrov
8da8ab4862 Fix/673/from queryset then custom qs method (#680)
* Fix `MyModel.objects.filter(...).my_method()`

* Fix regression: `MyModel.objects.filter(...).my_method()` no longer worked when using from_queryset

This also fixes the self-type of the copied-over methods of the manager generated by from_queryset.
Previously it was not parameterized by the model class, but used Any.

The handling of unbound types is not tested here as I have not been able to
find a way to create a test case for it. It has been manually tested
against an internal codebase.

* Remove unneeded defer.
2021-07-30 01:01:39 +03:00
Richard Xia
08a662ecb1 Change PasswordResetForm.get_users() to return Iterable, not Iterator. (#678)
This matches the actual implementation in Django, where it only attempts
to use the result of get_users() in a for loop, which allows for any
Iterable, and it provides a more flexible and idiomatic API for users
who subclass PasswordResetForm.
2021-07-29 12:35:28 +03:00
Richard Xia
0d7c32f38e Change PasswordResetForm.save() to accept HttpRequest, not WSGIRequest. (#679) 2021-07-29 12:26:06 +03:00
Michael Williamson
51183231e0 Add @display to django.contrib.admin (#677)
The `display` decorator is defined in `django.contrib.admin.decorators`, but
isn't included in `django.contrib.admin`, which is how the Django docs describe
its usage.
2021-07-27 16:31:41 +03:00
snmishra
d29dacd64b Add accepts method stub in HttpRequest (#676)
* Add accepts method to HttpRequest stubs

The accepts method (and dependencies) was missing in the stub for HttpRequest

* Change accepted_types to return correct type

* Fix Black formatting

* Add annotation for MediaType __init__ args
2021-07-25 18:53:37 +03:00
snmishra
ee51aa4bf8 Add datetime to DateTimeField (#675)
* Add datetime to set_type of DateTimeField

`DateTimeField` was missing `datetime` as a valid set type. But Django clearly accepts `datetime`.

* Fix test for DateTimeField type change

datetime is now a valid set type for DateTimeField
2021-07-25 13:06:22 +03:00
github-actions[bot]
ee9c0d4a32 Fixes by misspell-fixer (#674)
Co-authored-by: sobolevn <sobolevn@users.noreply.github.com>
2021-07-24 10:48:48 +03:00
Seth Yastrov
cfd69c0acc QuerySet.annotate improvements (#398)
* QuerySet.annotate returns self-type. Attribute access falls back to Any.

- QuerySets that have an annotated model do not report errors during .filter() when called with invalid fields.
- QuerySets that have an annotated model return ordinary dict rather than TypedDict for .values()
- QuerySets that have an annotated model return Any rather than typed Tuple for .values_list()

* Fix .annotate so it reuses existing annotated types. Fixes error in typechecking Django testsuite.

* Fix self-typecheck error

* Fix flake8

* Fix case of .values/.values_list before .annotate.

* Extra ignores for Django 2.2 tests (false positives due to tests assuming QuerySet.first() won't return None)

Fix mypy self-check.

* More tests + more precise typing in case annotate called before values_list.

Cleanup tests.

* Test and fix annotate in combination with values/values_list with no params.

* Remove line that does nothing :)

* Formatting fixes

* Address code review

* Fix quoting in tests after mypy changed things

* Use Final

* Use typing_extensions.Final

* Fixes after ValuesQuerySet -> _ValuesQuerySet refactor. Still not passing tests yet.

* Fix inheritance of _ValuesQuerySet and remove unneeded type ignores.

This allows the test
"annotate_values_or_values_list_before_or_after_annotate_broadens_type"
to pass.

* Make it possible to annotate user code with "annotated models", using PEP 583 Annotated type.

* Add docs

* Make QuerySet[_T] an external alias to _QuerySet[_T, _T].

This currently has the drawback that error messages display the internal type _QuerySet, with both type arguments.

See also discussion on #661 and #608.

Fixes #635: QuerySet methods on Managers (like .all()) now return QuerySets rather than Managers.

Address code review by @sobolevn.

* Support passing TypedDicts to WithAnnotations

* Add an example of an error to README regarding WithAnnotations + TypedDict.

* Fix runtime behavior of ValuesQuerySet alias (you can't extend Any, for example).

Fix some edge case with from_queryset after QuerySet changed to be an
alias to _QuerySet. Can't make a minimal test case as this only occurred
on a large internal codebase.

* Fix issue when using from_queryset in some cases when having an argument with a type annotation on the QuerySet.

The mypy docstring on anal_type says not to call defer() after it.
2021-07-23 16:15:15 +03:00
Tim Nyborg
c69e720dd8 Replace accepts expression as string (#671)
Fixes #503
2021-07-18 15:04:27 +03:00
Tim Nyborg
2a9410f3b1 widen type of make_password and get_hasher parameters (#670)
* widen type of make_password's hasher

make_password will accept a subclass of BasePasswordHasher as a hasher

* widen get_hasher's algorithm type

get_hasher will accept (and immediately return) a BasePasswordHasher
2021-07-18 15:01:36 +03:00
Petter Friberg
cc5d363cfa Add end-of-file-fixer hook to pre-commit (#668) 2021-07-12 00:48:36 +03:00
Abhishek Chaudhary
446589e133 fix(BaseCache): corrected return type of get_many func (#666)
* fix(BaseCache): corrected return type of get_many func

* fix(basecache): made required changes
2021-07-05 14:44:04 +03:00
Nikita Sobolev
d5e45db79b Better linting config (#664)
* Better linting config

* Applies isort on django-stubs, only style changes

* Fixes black and isort compat
2021-07-04 16:16:43 +03:00
Nikita Sobolev
552f2ffc0c Adds more rules to mypy config, related #662 (#663)
* Adds more rules to mypy config, related #662

* Removes plugin.ini for mypy settings

* Fixes build
2021-07-04 15:41:51 +03:00
horpto
d9c63f5e71 fix CursorWrapper iter method (#628) 2021-07-04 15:11:21 +03:00
Michael Aquilina
008dcdbcb6 chore: remove excess # type: ignore comments in _ValuesQuerySet (#662) 2021-07-04 14:53:28 +03:00
Michael Aquilina
5c3ce171b2 Add more method signatures for _ValuesQuerySet (#661) 2021-07-03 20:12:05 +03:00
Michael Aquilina
13c620f572 chore: remove unused class stubs from query.pyi (#660) 2021-07-03 16:14:16 +03:00
Michael Aquilina
ded66f6937 Add distinct, order_by and all method signatures for _ValuesQuerySet (#657) 2021-07-03 16:00:58 +03:00
David Szotten
739b1711a9 Use Sequence instead of List for path param (#659)
Unlike `List`, which is invariant, `Sequence` is covariant, which lets
`path` accept lists of subsets of the `Union` as well.

I believe this is safe, as django doesn't mutate this input. I found
[this
comment](https://github.com/python/mypy/issues/3351#issuecomment-300447832)
helpful
2021-07-03 13:46:29 +03:00
darius-blink
cf6952c9df Fix type of MigrationLoader.applied_migrations (#656)
Co-authored-by: Darius Marian <marian.darius98@gmail.com>
2021-06-30 12:23:48 +03:00
Seth Yastrov
0c3252fb97 Check whether reported issues actually fails currently (#653) 2021-06-28 13:23:20 +03:00
Seth Yastrov
f9317c7679 Rename ValuesQuerySet -> _ValuesQuerySet and remove _BaseQuerySet. Ma… (#654)
* Rename ValuesQuerySet -> _ValuesQuerySet and remove _BaseQuerySet. Make a public alias called ValuesQuerySet in django_stubs_ext.

* Update tests
2021-06-28 13:23:00 +03:00
Seth Yastrov
29e971ed9d Allow setting AutoFields to None (#634) 2021-06-28 03:23:54 +03:00
Daniel Hahler
a00563cfa4 [WIP/RFC] Revisit patching of mypy builtins (reveal_{type,locals}) (#615)
* Revisit patching of mypy builtins (reveal_{type,locals})

Fixes https://github.com/typeddjango/django-stubs/issues/609
Reverts ee58b18f15

* Create test_patching.yml

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-06-25 16:56:21 +03:00
sobolevn
159a0e4790 Adds docs for how Field access works 2021-06-23 13:44:06 +03:00
Nikita Sobolev
eb702384a8 Improves edit.py and its forms (#648)
* Improves edit.py and its forms

* Adds tests
2021-06-16 11:25:57 +03:00
Chris Beaven
acfe0ce820 Patch detail and list generic view base classes (#642)
Similar to the already patched `FormMixin`, the detail and list generic view classes are also missing __class_getitem__ and choke when you try to use their generics.
2021-06-16 10:32:47 +03:00
Patrick Gingras
f182b39c91 Copy decorated queryset methods to manager too (#646)
* copy decorated queryset methods to manager too

* added test for from_manager with decorated queryset methods
2021-06-16 10:15:32 +03:00
Anton Agestam
96ae17f4a7 Add missing queryset annotations (#644) 2021-06-15 11:51:13 +03:00
Cesar Canassa
397e3f3dac Adds support for pyproject.toml files (#639)
* Adds support for pyproject.toml files

Since mypy 0.900 the pyproject.toml files are supported.

This PR adds a support for it. It searchs for a `tool.django-stubs` section. This is an example configuration:

```
[tool.django-stubs]
django_settings_module = "config.settings.local"
```

Fixes #638

* Added TOML tests

* Use textwrap.dedent instead of trying to manually replace spaces
2021-06-15 01:50:31 +03:00
Maarten ter Huurne
8c387e85fe Allow Collection for 'fields' and 'exclude' of form model helpers (#637) (#640)
* Allow Collection for 'fields' and 'exclude' of form model helpers (#637)

There are several functions and classes in `django.forms.models` that
take a `fields` or `exclude` argument. Previously, `Sequence` was used
to annotate these, but the code of Django (I checked version 3.2.4)
doesn't require `__getitem__()` to be implemented, so requiring
`Collection` instead is sufficient.

The practical advantage of requiring `Collection` is that a set, such
as the key set of a dictionary, can be passed without first having to
convert it to a list or tuple.

* Pin mypy to below version 0.900

* Remove Callable for 'fields' and 'exclude' of form model helpers

I cannot find any support for callables for these two arguments in
the code or in the documentation.

* Update setup.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-06-12 01:21:42 +03:00
Cesar Canassa
77f9926ce1 fix tests for mypy 0.900 (#641) 2021-06-12 01:05:46 +03:00
Nikita Sobolev
47f1700a8b Update test.yml 2021-06-05 23:46:55 +03:00
Seth Yastrov
48c0bf0713 get_language can sometimes return None (#633)
https://docs.djangoproject.com/en/3.2/ref/utils/#django.utils.translation.get_language
> Returns the currently selected language code. Returns None if translations are temporarily deactivated (by deactivate_all() or when None is passed to override()).
2021-06-04 16:02:08 +03:00
jonfoster
893ad6bb02 #629: Add HTTP response "streaming" attribute (#632)
Add the missing attribute django.http.response.StreamingHttpResponse.streaming .

This is actually done by moving the attribute from HttpResponse to the base class HttpResponseBase.

The real Django source code declares this attribute on HttpResponse and StreamingHttpResponse, however that's only because Django doesn't have type hints.  The right place for the type hint is on the base class HttpResponseBase, since all instances of that base class are actually instances of HttpResponse or StreamingHttpResponse or a subclass of those two classes.  So it's guaranteed that every HttpResponseBase instance has the attribute.

Fixes bug #629.
2021-06-03 21:25:25 +03:00
Abhishek Chaudhary
becb0c9605 fix(ResolverMatch): Added _func_path (#631)
* fix(ResolverMatch): Added _func_path

ResolverMatch class in Django contains _func_path variable and it will get initialized in init method whatever the condition, so it should be added in type stubs as well. https://github.com/django/django/blob/main/django/urls/resolvers.py#L48

* Update resolvers.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-06-03 13:57:16 +03:00
Paweł Markowski
9a95b98398 add concrete attr to field (#623) 2021-05-25 18:22:48 +03:00
Nikita Sobolev
e12a2d9aef Update README.md 2021-05-24 11:56:08 +03:00
Y. Kiuchi
2f84d2e904 Add db_collation parameter to CharField and TextField (#621)
* Add db_collation parameter to CharField

* Add db_collation parameter to TextField
2021-05-24 11:22:07 +03:00
Nikita Sobolev
353b790209 Create py.typed 2021-05-21 11:00:24 +03:00
Bob Whitelock
66d5045ed9 Document limitation with django_stubs_ext.monkeypatch() (#619)
This monkey patching will only work when using Python 3.7+, which
introduced the `__class_getitem__` magic method. This tripped me up for
a while as I was on Python 3.6 and wondered why the monkey patching was
not working, therefore documenting this to point this out to future
readers.
2021-05-20 19:24:33 +03:00
Anton Agestam
3bd9fe530e Add stub for QuerySet.alias() (#618) 2021-05-19 16:23:59 +03:00
Anton Agestam
6dd8384381 Add stub for OpClass (#617) 2021-05-19 11:09:31 +03:00
Anton Agestam
248f1cccee Adjust Postgres indexes for Django 3.2 (#616) 2021-05-19 09:49:01 +03:00
Nikita Sobolev
c0203c9a60 Removes useless import 2021-05-17 22:06:32 +03:00
Marti Raudsepp
45f6dc0362 Improve hints for database connections (DatabaseWrapper) (#612)
* `django.db.{connection, connections, router}` are now hinted -- including `ConnectionHandler` and `ConnectionRouter` classes.
* Several improvements to `BaseDatabaseWrapper` attribute hints.
* In many places, database connections were hinted as `Any`, which I changed to `BaseDatabaseWrapper`.
* In a few places I added additional `SQLCompiler` hints.
* Minor tweaks to nearby code.
2021-05-13 20:22:35 +03:00
Marti Raudsepp
d1dd95181a Add a few missing Storage-related hints (#611) 2021-05-13 13:44:19 +03:00
Marti Raudsepp
e8d03a0e22 Use BaseDatabaseWrapper class instead of sqlite3's wrapper (#610)
Code dealing with DatabaseWrapper instances should be capable of dealing
with any database, not just sqlite3.
2021-05-13 13:38:08 +03:00
LanDinh
9251520f66 Allow Views to return the more generic HttpResponseBase instead of HttpResponse, to allow returning StreamingHttpResponse (#607)
* Add type hints for the postgres CursorDebugWrapper, expand the BaseCursorDebugWrapper.

* Fix how Optinal gets applied.

* Fix optional handling further.

* Adjust postgres debugcursorwrapper to look more like the implementation.

* Apply review feedback.

* Use the more generic HttpResponseBase when appriopriate.

* Fix failing test and add new test.

* Remove the other test again, it was the wrong location. Add new tests in the correct location.

Co-authored-by: LanDinh <coding+sourcetree@khaleesi.ninja>
2021-05-02 00:33:05 +03:00
Thomas Krapp
2a1c86744c Update decorators.pyi to match Django 3.1 (#576)
* Update decorators.pyi to match Django 3.1

This commit resembles the state of the file in Django 3.1. Unfortunately, this is not even compatible with Django 3.0 which misses the sync* and async* decorators.

* Update decorators.pyi

* Fixes lint

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-05-01 13:42:29 +03:00
Brian Helba
619823d497 Ensure that all registered checks return a list of CheckMessage (#508)
* Ensure that all registered checks return a list of CheckMessage

This changes missing and Any return types on registered checks to always
return "List[CheckMessage]".

In many cases, check functions were already annotated to return in a more
specific type than CheckMessage (e.g. Error). In these cases, it's assumed
that the existing annotation is correct, and the more specific type is kept.

* Update model_checks.pyi

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-05-01 13:34:38 +03:00
Sondre Lillebø Gundersen
e4de8453cf Replace models.Model annotations with type variables (#603)
* Replace models.Model annotations with type variables

* Adds generic type args to generic views

* Adds more tests

* Revert "Adds generic type args to generic views"

This reverts commit 6522f30cdb9027483f46d77167394c84eb7b7f4b.

* Adds Generic support for DetailView and ListView

Co-authored-by: sobolevn <mail@sobolevn.me>
2021-05-01 13:21:19 +03:00
Nikita Sobolev
5c3898d3b0 Revert "correct the type signature of AbstractBaseUser.set_password (#493)" (#537)
This reverts commit 8729a74f81.
2021-05-01 13:10:11 +03:00
Fabian Henze
e5ff9808cf Correct type of core.management.commands.runserver.Command.default_port (#604)
Strangely this variable is actually a string:
8bcb00858e/django/core/management/commands/runserver.py (L33)
2021-04-30 20:23:33 +03:00
Maxim Masiutin
c633f3215f Added a few definitions to resolve incompatibily with Pyre/Pysa (#601) 2021-04-24 08:24:49 +03:00
Abhyudai
9e8e4363b1 Update BaseCommand.requires_system_checks for django >=3.2 (#600)
- the documentation for this specific change in django can be seen at https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/#django.core.management.BaseCommand.requires_system_checks
2021-04-22 19:11:22 +03:00
Simon Charette
d4c1ed2ce0 Handle GenericForeignKey class typeinfo lookup failure. (#597)
This addresses an obscure crash we're getting when defining a GenericForeignKey
subclass on a model.

Not sure how this slipped through type checking since
`helpers.lookup_class_typeinfo -> Optional[TypeInfo]` while
`.get_private_descriptor_type(type_info: TypeInfo)` so this should be a clear
type violation.
2021-04-21 09:44:41 +03:00
LanDinh
3931432b34 Add type hints for the postgres CursorDebugWrapper and add missing method to the BaseCursorDebugWrapper (#585)
* Add type hints for the postgres CursorDebugWrapper, expand the BaseCursorDebugWrapper.

* Fix how Optinal gets applied.

* Fix optional handling further.

* Adjust postgres debugcursorwrapper to look more like the implementation.

* Apply review feedback.

Co-authored-by: LanDinh <coding+sourcetree@khaleesi.ninja>
2021-04-18 13:50:25 +03:00
Stevan Milic
4c90b5098f Add no_key parameter to select_for_update queryset method (#594) (#595)
Co-authored-by: Stevan Milic <stevan.milic@tradecore.com>
2021-04-16 19:42:02 +03:00
sobolevn
488d17b65c django-stubs-ext@0.2.0 2021-04-14 12:59:57 +03:00
Daniel Hahler
ee58b18f15 WIP: django_stubs_ext: monkeypatch reveal_{type,locals} into builtins (#591)
* WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

Fixes https://github.com/typeddjango/django-stubs/issues/590

* fixup! WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

* fixup! fixup! WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

* Update patch.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-04-14 12:33:45 +03:00
Daniel Hahler
3c6f438cc9 build(deps-dev): remove/unpin mypy/typing-extensions (#593)
* build(deps-dev): remove/unpin mypy/typing-extensions

Closes https://github.com/typeddjango/django-stubs/issues/592.

* Update test_options.yml

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-04-14 12:27:15 +03:00
Hannes Ljungberg
a14f49c4b2 [3.2] Adjust contrib.admin (#589) 2021-04-13 21:36:24 +03:00
Hannes Ljungberg
f003968177 [3.2] Add missing exceptions (#588) 2021-04-13 13:18:42 +03:00
Hannes Ljungberg
e8a97e301c [3.2] Adjust model indexes (#587) 2021-04-13 13:18:13 +03:00
Hannes Ljungberg
e72cbb6eb5 [3.2] Add durable argument to atomic (#586)
* [3.2] Add durable argument to atomic

* Adjust compatibility table for 3.2

* Update README.md

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-04-13 13:17:30 +03:00
sobolevn
3cca71a58f Version 1.8.0 release 2021-04-12 13:12:19 +03:00
LanDinh
ceb08f1804 Add URLPattern options to django.url.conf since they were missing. (#583)
* Add URLPattern options to django.url.conf since they were missing.

* Fix some wording in the contribution guide & fix a reference to Django version 3.0, which has since been replaced by 3.1 as new stable version.

* My bad - I was misreading the type hints a bit here. Fix tests.

* We need to specify the List[Union[URLResolver, URLPattern]] upfront, since those don't accept List[URLResolver] as argument.

* Add test to ensure that path() accepts a mix of URLPatterns & URLResolvers.

Co-authored-by: LanDinh <coding+sourcetree@khaleesi.ninja>
2021-04-10 18:01:40 +03:00
Konstantin Alekseev
9beb5327de Create related managers from generated managers (#580) 2021-04-07 11:37:28 +03:00
Daniel Sears
cd9ef6cdd4 compatibility matrix doc change for new django-stubs version (#581) 2021-04-03 11:29:16 +03:00
Edwin Grubbs
8f97bf880d MIMEBase parameter for EmailMessage.attach() (#577)
* MIMEBase parameter for EmailMessage.attach()

* Added test_mail.yml

Co-authored-by: Edwin Grubbs <edwin.grubbs@motiva.com>
2021-04-02 00:21:21 +03:00
Anton Agestam
124d90794c Fix Field arguments variance (#573)
* Fix Field arguments variance

* fixup! Fix Field arguments variance

Test field can be used as bsse type
2021-03-07 13:32:56 +03:00
James Owen
6a6fd47f28 Tweak the constructor signature for ManyToManyField (#571)
Prior to this change, ManyToManyField was declared as being generic in
_ST and _GT, but also used the _T Typevar in its __init__ signature.
This caused mypy to add _T to the variables it was generic in when used
as an alias.

The symptom of this problem was that mypy would show an error with the
message "Type application has too few types (3 expected)" where a
ManyToManyField alias was declared, but adding an extra argument would
fail because the type only takes two arguments.

This change brings the signature of ManyToManyField in line with
ForeignKey and OneToOneField.
2021-03-04 12:23:13 +03:00
melvyn-oviavo
54e5ecc16a feat(add-get-lines): Add get_inlines method (#570)
Document ModelAdmin.get_inlines(). Available since Django 3.0.
2021-02-22 11:54:35 +03:00
Seth Yastrov
418437b00c Mention issue about as_manager along with a workaround (#569)
* Mention issue about as_manager along with a workaround

* Update README.md

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
2021-02-18 09:56:09 +03:00
Daniel
eb195b61e9 Correct order for FileField __init__ args (#568) 2021-02-15 13:38:04 +03:00
Thomas Krapp
993dd816a4 Update static.pyi (#566)
* Update static.pyi

Parameters document_root and show_indexes should be marked as Optional since they have a default value.

* Update static.pyi

Correct signature of serve function.
2021-02-13 00:27:12 +03:00
Chas Nelson
e6dcfe4fc6 fix: add headers to http.HttpResponseBase constructor (#564)
* fix: add headers to http.HttpResponseBase constructor

fixes #563

* fix: correct Dict() with Dict[]

* feat: add ResponseHeaders typing

* fix: correct HttpResponseBase.headers type

* fix: add missing ...s

* fix: add CaseInsensitiveMapping import

* fix: make Dict -> Dict[str, str]
2021-02-09 22:07:35 +03:00
Simon Charette
8f9e77ce39 Allow ModelAdmin.actions to be set to None. (#560)
`None` is an allowed value to disable all actions for a particular `ModelAdmin`.
2021-01-31 10:24:32 +03:00
Tim Martin
a1334a70b9 Stricter return type annotations for template.Library (#541)
* Stricter return type annotations for template.Library

* Add some unit tests for the template library decorators
2021-01-20 23:11:02 +03:00
Nicolas Delaby
a8d8561d0e Add deferrable argument to unique constraint (#472) 2021-01-20 11:04:38 +03:00
Yuta Okamoto
bdc7db1154 Add algorithm parameter (Django 3.1) (#489)
* add algorithm parameter

* add algorithm field

* reformat
2021-01-20 11:03:51 +03:00
Maksim Kurnikov
49ed9c957f Merge pull request #536 from wkschwartz/patch-1
Fix incorrect and add missing annotations for loaddata command
2021-01-20 02:31:04 +03:00
Maksim Kurnikov
4829ce2200 Merge pull request #510 from jpulec/patch-1
Add resolve_callables to db.models.utils (Django 3.1)
2021-01-20 02:20:35 +03:00
Maksim Kurnikov
9fe1a76779 Merge pull request #559 from mkurnikov/value-to-string
add value_to_string method to Field
2021-01-20 02:18:20 +03:00
Maksim Kurnikov
153613eddb run black 2021-01-20 02:11:37 +03:00
Maksim Kurnikov
b6cb50e729 Merge pull request #538 from bullfest/av/ModelMultipleChoiceField
Make queryset parameter to ModelMultipleChoiceField.__init__ Optional
2021-01-20 02:02:01 +03:00
Maksim Kurnikov
344dea06b5 value_to_string obj param is Model 2021-01-20 01:58:29 +03:00
Maksim Kurnikov
01a9ad12e1 Merge pull request #533 from woochica/master
Add support for PositiveBigIntegerField (Django 3.1)
2021-01-20 00:19:13 +03:00
Maksim Kurnikov
0a0e1985d7 add value_to_string method to Field 2021-01-20 00:14:15 +03:00
Maksim Kurnikov
f07477260f Merge pull request #558 from mkurnikov/jsonfield
Missing Django 3.1 items
2021-01-20 00:10:24 +03:00
Maksim Kurnikov
11c3f8cd11 add django 3.1 classproperty 2021-01-19 22:16:12 +03:00
Maksim Kurnikov
159f8b95ba add django 3.1 jsonfield 2021-01-19 22:13:36 +03:00
Anas
58c087f7f5 Added cache in github actions to speed up CI (#549) 2020-12-22 23:37:41 +03:00
markedwards
2e9adce5eb Add Field to django_stubs_ext.django_stubs_ext.patch._need_generic (#547) 2020-12-22 10:09:29 +03:00
markedwards
47bd07758b Update django_stubs_ext documentation to reference settings (#548) 2020-12-19 11:50:46 +03:00
Marti Raudsepp
36d1778e2a Django admin additions (#543) 2020-12-17 13:23:51 +03:00
proxi
caaa23ab8f convince mypy that user.is_staff (and friends) are booleans (#542)
closes #512

Co-authored-by: proxi <51172302+3n-k1@users.noreply.github.com>
2020-12-16 23:28:01 +03:00
Marcin Wieczorek
cfd9379b58 Change patch_response_headers argument to Optional[int] (Fixes #337) (#338) 2020-12-13 16:21:58 +03:00
Alexander Viklund
362342d998 Make queryset parameter to ModelMultipleChoiceField Optional 2020-12-09 17:12:54 +01:00
William Schwartz
d3ff5415db Finish loaddata.pyi
This incorporates all type information I could glean from loaddata at
django/django@adb40d217e.

- Remove `help` per review comment:
  https://github.com/typeddjango/django-stubs/pull/536#discussion_r533179013
- Add `exclude_models` and `exclude_apps` based on the return type of
  `..utils.parse_apps_and_model_labels`.
- Change `loaddata`'s `fixture_labels` to `Sequence` of `str` instead of
  `Iterable` because in practice it's a tuple, but at a type level, the
  important thing is that `loaddata` iterates over `fixture_labels` more than
  once. General iterables (which include iterators) need not support iteration
  more than once.
- Correct the return type of `parse_name` to account for the possibility that
  the data and compression formats are `None`.
- Correct the return type of `find_fixtures` to be a list of the same type that
  `parse_name` returns.
- Add a type annotation for `SingleZipReader.read`. Django implements the method
  in a way that actually conflicts with `zipfile.ZipFile.read`'s type. This
  necessitates a `type: ignore[override]` to keep the tests passing. Mypy is
  correct that there is an override error, but Django's code is what it is.
  (And that method's signature was introduced way back in Django version 1.1,
  commit django/django@089ab18c025917f38a2e3731ae4024d4810df1ec.)
2020-12-01 11:32:59 -06:00
William Schwartz
eecf13a2fe Fix loaddata.pyi
- Added some of the instance attributes from command arguments: ignore, using, app_label, verbosity, format.
- Added class attribute: help.
- Fixed return type of find_fixtures.
2020-12-01 00:42:56 -06:00
Lysandros Nikolaou
d9c851abce Do not force django.contrib.* dependencies (#535)
* Do not force django.contrib.* dependencies

Fixes #428.
Fixes #534.

* Add one more test with contenttypes installed, but auth not
2020-11-24 14:38:03 +03:00
Torok Gabor
896cbe4752 Add support for PositiveBigIntegerField (Django 3.1) 2020-11-20 08:28:13 +01:00
Alisue
f3e0872d6e Fix signature of RemoteUserBackend.configure_user (#532)
* Fix signature of RemoteUserBackend.configure_user

The function signature has changed from 2.1 on 2.2 but django-stubs did not follow that.

https://github.com/django/django/blob/2.1.15/django/contrib/auth/backends.py#L163
https://github.com/django/django/blob/2.2/django/contrib/auth/backends.py#L177

* Use HttpRequest on request to make it more explicit
2020-11-19 18:38:59 +03:00
javulticat
4cb13a6ac5 AttributeError exception in copy_method_to_another_class (#531)
* Fix for method_node having no arguments

* Trim whitespace
2020-11-17 10:24:59 +03:00
Nikita Sobolev
19d695b1da Update misspel.yml 2020-11-17 10:15:18 +03:00
sobolevn
16326e999c Fixes CI 2020-11-14 21:18:09 +03:00
sobolevn
517ae648e5 Adds more types to patch 2020-11-14 20:46:32 +03:00
sobolevn
3e0f144148 Fixes README 2020-11-14 20:05:36 +03:00
Nikita Sobolev
8a68111ce5 Closes #529 (#530)
* Closes #529

* Fixing CI

* Fixing CI

* new monorepo setup
2020-11-14 20:03:50 +03:00
sobolevn
9f966a8056 django_stubs_ext release 0.1.0 2020-11-14 19:17:38 +03:00
proxy
0c41d0c6e9 create monkeypatching function for adding get_item dunder (#526)
* run black

* create monkeypatching function for adding get_item dunder

* whoops i forgot the test

* change the name in INSTALLED_APPS to make test pass

* turn the whole thing into a proper package

* move django_stubs_ext to requirements.txt

* also install requirements.txt

* attempt to fix pre-commit

* numerous small code review fixes

* fix dependency issues

* small dependency fixes

* configure proper license file location

* add the rest of the monkeypatching

* use strict mypy

* update contributing with a note monkeypatching generics

* copy release script from parent package
2020-11-11 10:04:13 +03:00
Tim Martin
e798b496c0 Add stubs for remaining commands in django.core.management.commands (#525)
* Add stubs for remaining commands in django.core.management.commands

* Tighten up stub definitions in django.core.management.commands

* Apply some missing declarations in django.core.management.commands
2020-11-11 01:56:41 +03:00
Francesc
01af2ff588 Annotate get_asgi_application (#527) 2020-11-09 20:27:17 +03:00
proxy
aab8acf2ea change get_user to use a protocol requiring a session (#522)
* change get_user to use a protocol requiring a session
define a "_HasSession" protocol, and update contrib.auth.get_user to use it
get_user only requires a session field, and idiomatic django testing frequently calls get_user with a TestClient

* run black

* use union for get_user instead of a protocol

* create tests for get_user typechecking

* properly import test client
2020-11-07 11:38:45 +03:00
Clarity
1c4a7d25c7 Add Point and Polygon to contrib.gis.geos (#524) 2020-11-07 01:34:47 +03:00
Robert Huselius
a0d61c0de3 Change InlineModelAdmin.formset to Type[BaseInlineFormSet] (#521)
* Change InlineModelAdmin.formset to Type[BaseInlineFormSet]

* More exact annotations + add NaturalTimeFormatter

* Correction: cls type is Type[...]

* Complete annotations for PasswordResetTokenGenerator

* fix *gettext*_lazy annotations
2020-11-06 11:04:34 +03:00
Ceesjan Luiten
e837dac26a Fix ResourceWarning (#520) 2020-11-05 16:47:41 +03:00
Yanky Hoffman
bbdf15a6ec Add is_active field to django.contrib.auth.AbstractBaseUser model (#517)
* Add `is_active` field to `django.contrib.auth.AbstractBaseUser` model

* Favor defining type than setting concrete value

* Update type to reflect sub-class implementation
2020-11-03 18:07:45 +03:00
proxy
f08b428027 make FormMixin generic to allow proper typing for LoginView (#515)
closes #514
2020-10-31 21:53:45 +03:00
Na'aman Hirschfeld
44151c485d updated package setup (#485)
* updated package setup

* updated to use python 3.9

* fixed test runner

* fixed typecheck tests

* fixed discrepencies

* added override to runner

* updated travis

* updated pre-commit hooks

* updated dep
2020-10-29 11:59:48 +03:00
Brian Helba
a3624dec36 Provide a more specific signature for django.core.checks.register (#509)
This also corrects the fact that "run_checks" only returns a concatenated list
of all registered check results, which may only contain CheckMessage:
302caa40e4/django/core/checks/registry.py (L60)
2020-10-29 10:31:26 +03:00
James Pulec
9a9a0123c7 Fix Generator Type 2020-10-28 21:33:43 -07:00
James Pulec
d3d854dac8 Add resolve_callables to db.models.utils 2020-10-28 20:27:46 -07:00
Brian Helba
6dc2c32382 Ensure that all registered checks take the same parameters (#499)
The Django API requires that registered checks take an "app_configs"
argument, which is a list of AppConfig. This is practically also passed by
keyword, so all parameters should be specified with a "= ..." to indicate
that they are keywords.

Django always passed "app_configs" as a list, but checks can accept and
use a more general more Sequence.

The Django API also requires that registered checks take "**kwargs".

This results in the canonical parameters of:
"app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any"
2020-10-29 02:21:32 +03:00
Brian Helba
695cdb16ca Add django.forms.widgets.FILE_INPUT_CONTRADICTION symbol (#506)
302caa40e4/django/forms/widgets.py (L399)
2020-10-29 02:20:40 +03:00
sobolevn
cb1fa08a82 Version 1.7.0 released 2020-10-28 11:41:15 +03:00
proxy
e2f6abe579 add additional failing test for ModelAdmin generic (#505)
this will ensure that the generic constraint holds
2020-10-28 10:28:04 +03:00
proxy
ffb6551eb4 make BaseModelAdmin generic to properly type methods dealing with models (#504)
* make BaseModelAdmin generic to properly type the `obj` argument of ModelAdmin.delete_model
closes #482

* turn BaseModelAdmin into bound generic, run black

* add test for generic ModelAdmin
2020-10-28 01:02:43 +03:00
Nikita Sobolev
40c8bfa510 Update migration.pyi (#501)
* Update migration.pyi

* Fixes tests

* Fixes tests

* Fixes tests
2020-10-26 11:43:47 +03:00
Nikita Sobolev
402b7d563f Update http.pyi (#502) 2020-10-26 00:01:36 +03:00
Daniel Hillier
92eb068a04 Fix #224 add paths in mypy's mypy_path option or MYPYPATH env var for import discovery (#498) 2020-10-23 01:06:49 +03:00
Brian Helba
9d4d06f8b3 Allow overridable checks to be CheckMessage (#497)
* Allow overridable checks to be CheckMessage

The checks framework expects return types to be "List[CheckMessage]". This
allows all overridable checks-returning methods to return the more general
"CheckMessage", instead of the "Error" subclass.

* Ignore an incorrect usage of the checks API in Django 2.2
2020-10-22 15:12:36 +03:00
giladsheffer
d746e3f5e4 user parameter for login accepts None (#496)
Co-authored-by: Gilad Sheffer <gilad@orca.security>
2020-10-19 18:15:44 +03:00
proxy
8729a74f81 correct the type signature of AbstractBaseUser.set_password (#493) 2020-10-18 11:54:10 +03:00
Mark Story
56361b353e Fix typoand grammar in readme (#491) 2020-10-15 12:47:15 +03:00
Noam
b71c9ad282 Changed model exceptions to use more specific base classes. (#490) 2020-10-14 18:41:23 +03:00
Na'aman Hirschfeld
ce370ea79f Missing stubs (#467)
* adding missing db.backends typings and updated test

* added missing stubs

* reformatted files

* removed contrib.postgres.forms

* fixed test
2020-10-11 12:14:08 +03:00
Mariam Maarouf
2a732fd257 renderer = BaseRenderer instead of EngineMixin in Widget.render() (#481) 2020-10-07 20:19:12 +03:00
sobolevn
645ee97e78 Release 1.6.0 2020-10-01 10:57:05 +03:00
William Schwartz
5bc3759ea2 Template Loader.get_template_sources yield Origins (#476)
django.template.loaders.base.Loader.get_template_sources should yield Origins:
https://docs.djangoproject.com/en/3.1/ref/templates/api/#django.template.loaders.base.Loader.get_template_sources

Currently it's returning none. Objects that yield should be marked as iterables.
https://mypy.readthedocs.io/en/stable/kinds_of_types.html#generators
2020-09-30 01:21:38 +03:00
henribru
534a028ea2 Use AbstractBaseUser where possible (#475)
Fixes #431
2020-09-29 22:04:20 +03:00
Nicolas Delaby
87856754ea psycopg2-binary is faster to install (#473) 2020-09-29 12:50:11 +03:00
Szymon Pyżalski
2f7fac2eaf Allowed to use decimal in combinables (#454)
Co-authored-by: Szymon Pyżalski <spyzalski@egnyte.com>
2020-09-21 15:00:32 +03:00
Marti Raudsepp
5ff99fd047 Check arguments to django.urls.{path,re_path} functions (#464)
These functions were added in Django 2.0, but the stubs have been
incomplete since commit 9a68263257

The implementation is almost identical to `url()` from
`conf/urls/__init__.pyi`
2020-09-17 18:08:26 +03:00
Marti Raudsepp
f77ebcd22c Add db.models.constants stub module (#462) 2020-09-17 18:07:03 +03:00
Alexander Viklund
34b126e3da Fix wrong type for parse_until in template parser (#460) 2020-09-12 01:58:09 +03:00
Jonathan Moss
6e5f5f2cdb Allows FileField storage to be a Callable (#453)
* Allows FileField storage to be a Callable

The `storage` parameter of `FileField` (and by extension `ImageField`)
is not limited to just taking an instance of `Storage`. It can also take
a no-args callable that returns an instance of `Storage`.

* correcting linting issue in forms.pyi
2020-08-28 10:14:57 +03:00
James Perretta
95252cde60 Add "one_to_many", "one_to_one", "many_to_many," and "many_to_one" attributes to Field base class (#449)
* Add "_to_many" and "_to_one" bool attributes to Field base class.

* Remove unused import from test case.
2020-08-24 23:09:15 +03:00
Zach Waggoner
6ef2cf0331 Add force_color parameter to django.core.management.color.color_style (#448) 2020-08-21 12:41:51 +03:00
Alexander Viklund
9f3b95841b return type for translation.get_language should not be Optional (#446) 2020-08-18 12:41:52 +03:00
Federico Bond
e764b1cf4c Add route argument to ResolverMatch constructor (#442) 2020-08-12 15:36:01 +03:00
Šarūnas Nejus
8a64d87917 Output a more clear configuration error (#421)
* Output a more clear configuration error

* Performance related improvements in config read handling

* Check python 3.6 with travis

* Revert the .travis.yml py36 inclusion

* Added tests for input error handling

* Thanks isort, isorted it out

* Make exit() function a bit more aesthetic

* Single quote -> double quote docstrings

* Whitespace removed
2020-08-09 11:27:21 +03:00
Daniel Hillier
60f3f9dd9f Change select_for_update's 'of' type to Sequence[str] (#440) 2020-08-08 20:21:55 +03:00
Mantas Zimnickas
ca10ee9242 Fix staff_member_required annotations (#436)
* Fix staff_member_required annotations

`redirect_field_name` can be `None`.

* Reformat code with black
2020-07-31 10:35:35 +03:00
Sigurd Ljødal
f651f27ddf Fix type of update_fields parameter to Model.save (#437)
Sending in a single string leads to unexpected behavior and the method
accepts any iterable, not just sequences, of strings.

Technically sending in a single string is still allowed because a string
is an iterable of strings, but this way the intention of that argument
is clearer.
2020-07-31 10:14:35 +03:00
Kacper
3915aa0639 AttributeError exception in build_unannotated_method_args (#429)
* AttributeError exception in build_unannotated_method_args

* assigning [] to arguments if AttributeError

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-07-21 15:31:19 +03:00
Nate Clark
97ec2ee43b Allow Field.widget to be a class or instance (#426)
According to source below, a Field's widget is allowed to be a class or instance of Widget.

156a2138db/django/forms/fields.py (L63-L66)
2020-07-16 00:51:29 +03:00
Daniel Hillier
19c73a106d admin: Allow ModelAdmin.actions to contain str (#425)
Strings are allowed in ModelAdmin.actions when they refer to a method on
the ModelAdmin subclass.
2020-07-14 10:43:50 +03:00
Kacper
92ef5d9d95 additional defer() to offset the effect of using the type before decl… (#424)
* additional defer() to offset the effect of using the type before declaring

* linter fix

* linter fix

* linter fix

* test case

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-07-13 16:31:13 +03:00
Daniel Hillier
f16d1b8cb6 Improve *HttpResponse.getvalue() types (#422)
* Change returned type of StreamingHttpResponse.getvalue() to bytes

* Add HttpResponse.getvalue() definition
2020-07-11 15:57:35 +03:00
Alexander Viklund
c3cdc1c2d5 Allow more types for args to Paginator.get_page (#418) 2020-07-08 22:53:38 +03:00
Alexander Viklund
3704d0ab98 Don't change type of HttpRequest.user if type has been changed by subclassing (#415)
* Don't change type of HttpRequest.user if type has been changed by subclassing

* Asserts for typing

* Add tests

* Add description of HttpRequest subclassing to README

* Dummy to rebuild travis
2020-07-07 12:52:21 +03:00
Kacper
b1d619edb2 Bumped required Mypy version to newest in requirements (#414)
* pytest-mypy-plugins package newer version

* Revert "pytest-mypy-plugins package newer version"

This reverts commit 871347a86577a5dad867bc751689bbc06d2bcae0.

* update tests ignores for django

* Revert "update tests ignores for django"

This reverts commit 93fc66e311af62cf8cf5b79a72ab723bf3cf060a.

* changed required mypy version to the newest

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-07-06 10:34:17 +03:00
Akseli Nelander
e680326c72 Fix partition signature (#413) 2020-07-01 15:35:35 +03:00
Étienne
574a87e68c explicitly mark value and label types on choices enum (#406)
In addition to the meta properties added
to the Choices enums, value and label are
set for each choice.
This commit explicitly types those instead of the
tuple value and non-extant label types
2020-06-22 11:08:09 +03:00
coiax
82ae1751ed 🐑 Update update_session_auth_hash() stub (#401)
The update_session_auth_hash() stub doesn't match the documented and
actual type that the function expects.

---

Resolves #400.
2020-06-16 19:19:11 +03:00
Ceesjan Luiten
69042783b1 Allow form.save() in CreateView / UpdateView (#374) 2020-06-12 21:12:56 +03:00
Kacper
391bbc59d5 WIP Fix ci/cd (#396)
* pytest-mypy-plugins package newer version

* Revert "pytest-mypy-plugins package newer version"

This reverts commit 871347a86577a5dad867bc751689bbc06d2bcae0.

* update tests ignores for django

* Revert "update tests ignores for django"

This reverts commit 93fc66e311af62cf8cf5b79a72ab723bf3cf060a.

* lets see what happen :)

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-11 23:05:59 +03:00
Michael
28c76df3b2 Fix compatibility table in readme (#395) 2020-06-10 16:03:00 +03:00
Nikita Sobolev
3d2534ea8d Closes #392 2020-06-08 10:55:30 +03:00
Kacper
54f5f63e71 Issue 379 (#391)
* pytest-mypy-plugins package newer version

* Revert "pytest-mypy-plugins package newer version"

This reverts commit 871347a86577a5dad867bc751689bbc06d2bcae0.

* update tests ignores for django

* Revert "update tests ignores for django"

This reverts commit 93fc66e311af62cf8cf5b79a72ab723bf3cf060a.

* tests for python 3.8 WIP - initial commit

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-06 14:28:28 +03:00
Kacper
4c5723d368 WIP Issue 388 (#390)
* updated mypy dependency

* update readme

* readme update v2

* pytest-mypy-plugins newer version

* updated pytest_mypy_plugins name

* update ignored errors for typechecking django test suite

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-06 11:35:51 +03:00
Alexander Viklund
7e0e43135d BaseForm.prefix may be None (#389) 2020-06-04 21:24:42 +03:00
Kacper
e05b84e32d Issue 378 (#387)
* proper redirect return type annotations made with Literal

* Mapping instead of Dict type annotation for context in render() with test

* removed Union and Context

* typo

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>

Add __init__ to OrderedSet (#381)

Issue 382 (#384)

* WIP fix, pushed for testing

* added _ prefix for internal types

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>

Fix parameter types for assertJSONEqual/NotEqual (#385)

Add get_supported_language_variant (#386)

Issue 309 (#383)

* added tags for user models

* type test for HttpRequest.user

* test for User and AnonymousUser tags

* httrequest test fix

* checking python version fix for readibility

* Rewrite version check for readability

* Annotate is_authenticated/is_anonymous with Literal-type

* Add auth in INSTALLED_APPS in test

* Fix wrong type assertion in test

* Fix misconception of how branch-testing works

* Remove user from WSGIRequest

* Change HttpRequest-transformer to set user-type to include AnonymousUser

* Add check for anonymous_user_info=None to appease mypy

* Isort transformers/request

* Remove trailing whitespace

* Remove unused import

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>

* fix formatting and unused import

* reformatted again

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-03 23:46:30 +03:00
Alexander Viklund
71751d3795 Issue 309 (#383)
* added tags for user models

* type test for HttpRequest.user

* test for User and AnonymousUser tags

* httrequest test fix

* checking python version fix for readibility

* Rewrite version check for readability

* Annotate is_authenticated/is_anonymous with Literal-type

* Add auth in INSTALLED_APPS in test

* Fix wrong type assertion in test

* Fix misconception of how branch-testing works

* Remove user from WSGIRequest

* Change HttpRequest-transformer to set user-type to include AnonymousUser

* Add check for anonymous_user_info=None to appease mypy

* Isort transformers/request

* Remove trailing whitespace

* Remove unused import

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-03 20:29:19 +03:00
Alexander Viklund
25f92e8e56 Add get_supported_language_variant (#386) 2020-06-03 20:04:19 +03:00
Alexander Viklund
28d47c7e93 Fix parameter types for assertJSONEqual/NotEqual (#385) 2020-06-03 20:03:59 +03:00
Kacper
197cb4058e Issue 382 (#384)
* WIP fix, pushed for testing

* added _ prefix for internal types

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-03 12:58:03 +03:00
Alexander Viklund
dac2b31fb2 Add __init__ to OrderedSet (#381) 2020-06-02 13:56:11 +03:00
Kacper
8d2600136a Issue 355 (#376)
* Mapping instead of Dict type annotation for context in render() with test

* removed Union and Context

* typo

Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-06-01 19:41:57 +03:00
Pavel Savchenko
570772f973 Revert "Allow template render to string helper functions to accept Context (#372)" (#377)
This reverts commit 64cbb0f70e.
2020-06-01 14:34:21 +03:00
Anton Agestam
d5c1bfb12a Increase accuracy of ModelAdmin types (#375)
* Increase accuracy of ModelAdmin types

* Add comment for regression test
2020-05-30 00:24:47 +03:00
Pavel Savchenko
64cbb0f70e Allow template render to string helper functions to accept Context (#372)
* Add failing test case for render_to_string

* Allow Context objects in template render functions
2020-05-23 13:47:39 +03:00
Ville Skyttä
6f5a39625e Add release notes project URL (#365)
Background info at https://github.com/pypa/warehouse/pull/7882
2020-05-05 18:38:11 +03:00
Anthony Ricaud
bf604a0398 Add BaseForm._html_output (#364) 2020-04-30 14:36:55 +03:00
Ashish Bansal (mrphantom)
92c8dfc93f Fix wrong BaseCache typings (#363)
django.core.cache.backends.base.BaseCache were invalid. This commit
fixes them in accordance with [0].

[0] 447980e72a/django/core/cache/backends/base.py (L108)
2020-04-24 12:44:55 +03:00
Jorgen Phillips
c10c55052c Add add_to_class method to Model (#361)
* Add add_to_class method to Model

* Fix @classmethod decorator
2020-04-24 01:11:16 +03:00
Sergey Tikhonov
96914e466b Annotate AdminForm.__init__ (#359) 2020-04-16 18:22:21 +03:00
Onyeka Aghanenu
90ed7f332d Fix Modelform auto_id to accept Boolean type. (#356) 2020-04-13 19:04:18 +03:00
Kacper
a801501151 stub for _build_app_dict (#351)
Co-authored-by: Kacper Szmigiel <szmigielkacper@gmai.com>
2020-04-04 20:38:42 +03:00
Sid Mitra
8ea59985df Add RESTRICT and RestrictedError to django.db.models.deletion (#345)
* Add RESTRICT and RestrictedError to django.db.models.deletion

* Add black fomatting changes
2020-04-03 17:02:34 +03:00
Ceesjan Luiten
2964ed53d7 Improve type of BaseForms.files (#350)
This is valid Django, which failed to pass with the old type-defintion:

    class MyForm(Form):
      myparam = MultiFileField(...)

      self.clean(self, *args, **kwargs):
        self.files.getlist('myparam', [])
2020-03-31 10:16:02 +03:00
Stevan Milic
1b9176f994 Add state attribute to Model (#347) (#348)
Add from_db method to Model

Co-authored-by: Stevan Milic <stevan.milic@tradecore.com>
2020-03-30 10:35:40 +03:00
Nikita Sobolev
54d0d018c6 Minor type improvements after linting (#343) 2020-03-19 18:04:51 +03:00
Maxim Kurnikov
1af3a12f2c bump to 1.5.0 2020-03-15 00:59:58 +03:00
Marti Raudsepp
7af89ee6a6 Update to mypy 0.770 (#341) 2020-03-13 16:45:45 +03:00
Marti Raudsepp
afa16bfb74 Make decorator functions transparent to Mypy (#306)
By declaring return type as -> Callable[[_C], _C], Mypy can infer that
the decorated function has also the same arguments and return type as
the original.

View functions are constrained to return HttpResponseBase (or any
subclass of it).

Also added typecheck test coverage to most of the cases.
2020-03-12 00:32:30 +03:00
Marti Raudsepp
f77073157b Fix CI build errors (#339)
* Updated gitpython dependency to fix error:
  ModuleNotFoundError: No module named 'gitdb.utils.compat'
* Updated Django repository git refs because old 3.0.x commit hash gave error:
  stderr: 'fatal: reference is not a tree: 6cb30414bc0f83b49afc4cae76d4af5656effe9a'
* Newer Django version also needs new ignores.
2020-03-12 00:19:51 +03:00
Kevin Marsh
fe3b95c611 Fix input types of humanize functions (#335) 2020-02-27 10:10:53 +03:00
Daniel Hillier
d0f9730c53 Add db.models.fields.Field method stubs for custom Fields (#331)
Add stubs for: pre_save, get_db_prep_value, get_db_prep_save
2020-02-17 10:08:39 +03:00
Leo Shklovskii
0fdd678d65 fix typo in README.md (#328) 2020-02-15 08:28:47 +03:00
Semyon Pupkov
2397065fa6 signing.loads allows use timedelta for max_age (#325)
* signing.loads allows use timedelta

https://github.com/django/django/blob/stable/2.2.x/django/core/signing.py#L191

* fix black
2020-02-14 14:12:58 +03:00
Semyon Pupkov
04023a9f31 Fix readme (#326) 2020-02-13 23:20:58 +03:00
Marti Raudsepp
95e6c94319 Improve test client type stubs (#322)
* Added missing `follow: bool` argument to Client request methods.
* Annotated return types as `HttpResponse` instead of `Any`.
* Made `Client` class inherit from `RequestFactory`, as it does in Django.
* Changed `json()` return type to Any, as it can also be a list.

Wrt (2), these return types were reverted from `HttpResponse` to `Any`
in commit 287c64d6fb. But I suspect that
was simply to silence mypy warnings about "incompatible with supertype
RequestFactory", not because there were any issues with the annotation.

Note that `Client.request()` monkey-patches the `HttpResponse` object
with some additional attributes. Those attributes were already annotated
before, I reordered and added additional comments to make it clear where
they come from.
2020-02-12 18:44:17 +03:00
Brian Helba
d96aee7a8b Fix the type of form.Field.widget (#321)
The `widget` class attribute of `form.Field` expects a `Widget` class, not an instance of `Widget`.

See: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#widget
Also usages at: 3259983f56/django/forms/fields.py (L46)
2020-02-07 12:42:02 +03:00
Nikita Sobolev
2489bb9b04 Adds CONTRIBUTING.md (#319)
* Adds CONTRIBUTING.md

Closes #206 
Refs #274

* Update CONTRIBUTING.md
2020-02-06 15:01:56 +03:00
Nikita Sobolev
3a8f278c88 Update README.md 2020-02-06 11:09:16 +03:00
Nikita Sobolev
85b65b4578 Update README.md 2020-02-06 11:07:23 +03:00
Nikita Sobolev
150e8e862a Update README.md (#317)
* Update README.md

* Update README.md

* Update README.md
2020-02-06 11:03:38 +03:00
Vince Salvino
5b3088a17a Fix cache arg type for django.utils.cache.learn_cache_key() (#316) 2020-02-01 22:03:46 +03:00
Konstantin Alekseev
f89a0fbbaa Cleanup checks framework (#310) 2020-01-30 14:38:23 +03:00
Tatsh
438f8b5829 Add OutputWrapper write() signature (#301)
* Add OutputWrapper write() signature

* Add #type: ignore[override] to OutputWrapper write() signature
2020-01-28 01:34:13 +03:00
Joseph Kahn
836d5acd8f Allow error handlers to be strings (#307)
Based on the docs on this page: https://docs.djangoproject.com/en/3.0/ref/urls/
2020-01-28 01:33:49 +03:00
Cesar Canassa
bfae51e64c Added manager _db (#296) 2020-01-14 17:05:29 +03:00
Daniel Hillier
e3801918e3 Fix incorrect type for django.core.files.File.file (#293) (#294) 2020-01-11 14:27:46 +03:00
Marti Raudsepp
6f296b0a91 Implement @cached_property attribute inference (#292) 2020-01-10 13:57:09 +03:00
679 changed files with 21198 additions and 8630 deletions

View File

@@ -33,3 +33,4 @@ That is EXTREMELY helpful!
- `django` version:
- `mypy` version:
- `django-stubs` version:
- `django-stubs-ext` version:

15
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
version: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily
time: "02:00"
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
time: "02:00"
open-pull-requests-limit: 10

107
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,107 @@
name: test
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9']
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./requirements.txt
- name: Run pre-commit
run: pre-commit install && pre-commit run --all-files
mypy-self-check:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.7', '3.8', '3.9', '3.10']
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./requirements.txt
- name: Run mypy on plugin code
run: mypy --strict mypy_django_plugin
- name: Run mypy on ext code
run: mypy --strict django_stubs_ext
- name: Run mypy on scripts and utils
run: mypy --strict scripts
- name: Run mypy on stubs
run: mypy --cache-dir=/dev/null --no-incremental django-stubs
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9']
steps:
- uses: actions/checkout@v3
- name: Setup system dependencies
run: sudo apt-get install binutils libproj-dev gdal-bin
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./requirements.txt
- name: Run tests
run: PYTHONPATH='.' pytest
typecheck:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10']
django-version: ['3.2', '4.0']
include:
- python-version: '3.7'
django-version: '2.2'
steps:
- uses: actions/checkout@v3
- name: Setup system dependencies
run: sudo apt-get install binutils libproj-dev gdal-bin
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./requirements.txt
- name: Run tests
run: python ./scripts/typecheck_tests.py --django_version="${{ matrix.django-version }}"

18
.gitignore vendored
View File

@@ -1,14 +1,12 @@
*.egg-info
__pycache__/
out/
/test_sqlite.py
/django
.DS_Store
.idea/
.mypy_cache/
build/
dist/
pip-wheel-metadata/
.pytest_cache/
/.envrc
/.direnv
django-sources/
.venv/
__pycache__/
django-source/
out/
pip-wheel-metadata/
stubgen/
build/

43
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,43 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.9
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: check-yaml
- id: trailing-whitespace
- id: check-executables-have-shebangs
- id: debug-statements
- id: check-merge-conflict
- id: end-of-file-fixer
- repo: https://github.com/asottile/pyupgrade
rev: v3.2.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
name: isort (python)
- id: isort
name: isort (pyi)
types: [pyi]
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
ci:
autofix_commit_msg: '[pre-commit.ci] auto fixes from pre-commit.com hooks'
autofix_prs: true
autoupdate_commit_msg: '[pre-commit.ci] pre-commit autoupdate'
autoupdate_schedule: weekly
skip: [flake8]
submodules: false

View File

@@ -1,52 +0,0 @@
language: python
cache: pip
dist: xenial
sudo: required
jobs:
include:
- name: Run plugin test suite with python 3.7
python: 3.7
script: 'pytest'
- name: Typecheck Django 3.0 test suite with python 3.7
python: 3.7
script: |
python ./scripts/typecheck_tests.py --django_version=3.0
- name: Typecheck Django 3.0 test suite with python 3.6
python: 3.6
script: |
python ./scripts/typecheck_tests.py --django_version=3.0
- name: Typecheck Django 2.2 test suite with python 3.7
python: 3.7
script: |
python ./scripts/typecheck_tests.py --django_version=2.2
- name: Mypy for plugin code
python: 3.7
script: 'mypy ./mypy_django_plugin'
- name: Lint with black
python: 3.7
script: 'black --check django-stubs/'
- name: Lint plugin code with flake8
python: 3.7
script: 'flake8'
- name: Lint stubs with flake8-pyi and check for unused imports
python: 3.7
script: 'flake8 --config flake8-pyi.ini'
- name: Lint plugin code with isort
python: 3.7
script: 'isort --check --diff'
before_install: |
sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable -y
sudo apt-get update
sudo apt-get install -y binutils libproj-dev gdal-bin
pip install -U pip setuptools wheel
install: |
pip install -r ./dev-requirements.txt

118
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,118 @@
# Contribution Guide
This project is open source and community driven. As such we encourage code contributions of all kinds. Some areas you can contribute in:
1. Improve the stubs
2. Sync stubs with the latest version of Django
3. Improve plugin code and extend its capabilities
4. Write tests
5. Update dependencies
## Tutorials
If you want to start working on this project, you will need to get familiar with python typings.
The Mypy documentation offers an excellent resource for this, as well as the python official documentation:
- [Mypy typing documentation](https://mypy.readthedocs.io/en/stable/#overview-type-system-reference)
- [Python official typing documentation](https://docs.python.org/3/library/typing.html)
- [Typing in Python](https://inventwithpython.com/blog/2019/11/24/type-hints-for-busy-python-programmers/) article
Additionally, the following resources might be useful:
- [How to write custom mypy plugins](https://mypy.readthedocs.io/en/stable/extending_mypy.html)
- [Typechecking Django and DRF](https://sobolevn.me/2019/08/typechecking-django-and-drf) guide
- [Testing mypy stubs, plugins, and types](https://sobolevn.me/2019/08/testing-mypy-types) guide
- [Awesome Python Typing](https://github.com/typeddjango/awesome-python-typing) list
## Dev setup
### Repository Setup
As a first step you will need to fork this repository and clone your fork locally.
In order to be able to continously sync your fork with the origin repository's master branch, you will need to set up an upstream master. To do so follow this [official github guide](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/syncing-a-fork).
### Dependency Setup
After your repository is setup you will then need to create and activate a git ignored virtual env, e.g.:
```bash
python3 -m venv .venv
source .venv/bin/activate
```
Then install the dev requirements:
```bash
pip install -r ./requirements.txt
```
Finally, install the pre-commit hooks:
```bash
pre-commit install
```
### Testing and Linting
We use `mypy`, `pytest`, `flake8`, and `black` for quality control. All tools except pytest are executed using pre-commit when you make a commit.
To ensure there are not formatting or typing issues in the entire repository you can run:
```bash
pre-commit run --all-files
```
NOTE: This command will not only lint but also modify files - so make sure to commit whatever changes you've made before hand.
You can also run pre-commit per file or for a specific path, simply replace "--all-files" with a target (see [this guide](https://codeburst.io/tool-your-django-project-pre-commit-hooks-e1799d84551f) for more info).
To execute the unit tests, simply run:
```bash
pytest
```
If you get some unexpected results or want to be sure that tests run is not affected by previous one, remove `mypy` cache:
```bash
rm -r .mypy_cache
```
We also test the stubs against Django's own test suite. This is done in CI but you can also do this locally.
To execute the script run:
```bash
python ./scripts/typecheck_tests.py --django_version 3.1
```
### Generating Stubs using Stubgen
The stubs are based on auto-generated code created by Mypy's stubgen tool (see: [the stubgen docs](https://mypy.readthedocs.io/en/stable/stubgen.html)).
To make life easier we have a helper script that auto generates these stubs. To use it you can run:
```bash
python ./scripts/stubgen-django.py --django_version 3.1
```
You can also pass an optional commit hash as a second kwarg to checkout a specific commit, e.g.
```bash
python ./scripts/stubgen-django.py --django_version 3.1 --commit_sha <commit_sha>
```
The output for this is a gitignored folder called "stubgen" in the repo's root.
## Submission Guidelines
The workflow for contributions is fairly simple:
1. fork and setup the repository as in the previous step.
2. create a local branch.
3. make whatever changes you want to contribute.
4. ensure your contribution does not introduce linting issues or breaks the tests by linting and testing the code.
5. make a pull request with an adequate description.
## A Note About Generics
As Django uses a lot of the more dynamic features of Python (i.e. metaobjects), statically typing it requires heavy use of generics. Unfortunately, the syntax for generics is also valid python syntax. For instance, the statement `class SomeClass(SuperType[int])` implicitly translates to `class SomeClass(SuperType.__class_getitem__(int))`. If `SuperType` doesn't define the `__class_getitem__` method, this causes a runtime error, even if the code typechecks.
When adding a new generic class, or changing an existing class to use generics, run a quick test to see if it causes a runtime error. If it does, please add the new generic class to the `_need_generic` list in the [django_stubs_ext monkeypatch function](https://github.com/typeddjango/django-stubs/blob/master/django_stubs_ext/django_stubs_ext/patch.py)

290
README.md
View File

@@ -1,85 +1,297 @@
<img src="http://mypy-lang.org/static/mypy_light.svg" alt="mypy logo" width="300px"/>
# pep484 stubs for Django framework
# pep484 stubs for Django
[![Build Status](https://travis-ci.com/typeddjango/django-stubs.svg?branch=master)](https://travis-ci.com/typeddjango/django-stubs)
[![Build status](https://github.com/typeddjango/django-stubs/workflows/test/badge.svg?branch=master&event=push)](https://github.com/typeddjango/django-stubs/actions?query=workflow%3Atest)
[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)
[![Gitter](https://badges.gitter.im/mypy-django/Lobby.svg)](https://gitter.im/mypy-django/Lobby)
[![StackOverflow](https://img.shields.io/stackexchange/stackoverflow/t/django-stubs)](https://stackoverflow.com/questions/tagged/django-stubs)
This package contains type stubs and mypy plugin to provide more precise static types and type inference for Django framework. Django uses some Python "magic" that makes having precise types for some code patterns problematic. This is why we need to accompany the stubs with mypy plugins. The final goal is to be able to get precise types for most common patterns.
Could be run on earlier versions of Django, but expect some missing imports warnings.
This package contains [type stubs](https://www.python.org/dev/peps/pep-0561/) and a custom mypy plugin to provide more precise static types and type inference for Django framework. Django uses some Python "magic" that makes having precise types for some code patterns problematic. This is why we need this project. The final goal is to be able to get precise types for most common patterns.
## Installation
```bash
pip install django-stubs
pip install django-stubs[compatible-mypy]
```
## Mypy compatibility
| django-stubs | mypy version | django version | python version
| ------------ | ---- | ---- | ---- |
| 1.3.0 | 0.750 | 2.2.x | ^3.6
| 1.2.0 | 0.730 | 2.2.x | ^3.6
| 1.1.0 | 0.720 | 2.2.x | ^3.6
| 0.12.x | old semantic analyzer (<0.711), dmypy support | 2.1.x | ^3.6
## Configuration
To make mypy aware of the plugin, you need to add
```ini
[mypy]
plugins =
mypy_django_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = "myproject.settings"
```
in your `mypy.ini` or `setup.cfg` [file](https://mypy.readthedocs.io/en/latest/config_file.html).
Plugin also requires Django settings module (what you put into `DJANGO_SETTINGS_MODULE` variable) to be specified.
[pyproject.toml](https://mypy.readthedocs.io/en/stable/config_file.html#using-a-pyproject-toml-file) configurations are also supported:
```ini
[mypy]
strict_optional = True
```toml
[tool.mypy]
plugins = ["mypy_django_plugin.main"]
# This one is new:
[mypy.plugins.django-stubs]
django_settings_module = mysettings
[tool.django-stubs]
django_settings_module = "myproject.settings"
```
Where `mysettings` is a value of `DJANGO_SETTINGS_MODULE` (with or without quotes)
Two things happening here:
Current implementation uses Django runtime to extract models information, so it will crash, if your installed apps `models.py` is not correct. For this same reason, you cannot use `reveal_type` inside global scope of any Python file that will be executed for `django.setup()`.
In other words, if your `manage.py runserver` crashes, mypy will crash too.
1. We need to explicitly list our plugin to be loaded by `mypy`
2. Our plugin also requires `django` settings module (what you put into `DJANGO_SETTINGS_MODULE` variable) to be specified
This fully working [typed boilerplate](https://github.com/wemake-services/wemake-django-template) can serve you as an example.
## Version compatibility
## Notes
We rely on different `django` and `mypy` versions:
Type implementation monkey-patches Django to add `__class_getitem__` to the `Manager` class.
If you would use Python3.7 and do that too in your code, you can make things like
| django-stubs | mypy version | django version | python version
|--------------| ---- | ---- | ---- |
| 1.13.0 | 0.980+ | 3.2.x or 4.0.x or 4.1.x | ^3.7
| 1.12.0 | 0.931+ | 3.2.x or 4.0.x | ^3.7
| 1.11.0 | 0.931+ | 3.2.x | ^3.7
| 1.10.0 | 0.931+ | 3.2.x | ^3.7
| 1.9.0 | 0.910 | 3.2.x | ^3.6
| 1.8.0 | 0.812 | 3.1.x | ^3.6
| 1.7.0 | 0.790 | 2.2.x \|\| 3.x | ^3.6
| 1.6.0 | 0.780 | 2.2.x \|\| 3.x | ^3.6
| 1.5.0 | 0.770 | 2.2.x \|\| 3.x | ^3.6
| 1.4.0 | 0.760 | 2.2.x \|\| 3.x | ^3.6
| 1.3.0 | 0.750 | 2.2.x \|\| 3.x | ^3.6
| 1.2.0 | 0.730 | 2.2.x | ^3.6
| 1.1.0 | 0.720 | 2.2.x | ^3.6
| 0.12.x | old semantic analyzer (<0.711), dmypy support | 2.1.x | ^3.6
## FAQ
### Is this an official Django project?
No, it is not. We are independent from Django at the moment.
There's a [proposal](https://github.com/django/deps/pull/65) to merge our project into the Django itself.
You can show your support by liking the PR.
### Is it safe to use this in production?
Yes, it is! This project does not affect your runtime at all.
It only affects `mypy` type checking process.
But, it does not make any sense to use this project without `mypy`.
### mypy crashes when I run it with this plugin installed
The current implementation uses Django's runtime to extract information about models, so it might crash if your installed apps or `models.py` are broken.
In other words, if your `manage.py runserver` crashes, mypy will crash too.
You can also run `mypy` with [`--tb`](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-show-traceback)
option to get extra information about the error.
### I cannot use QuerySet or Manager with type annotations
You can get a `TypeError: 'type' object is not subscriptable`
when you will try to use `QuerySet[MyModel]`, `Manager[MyModel]` or some other Django-based Generic types.
This happens because these Django classes do not support [`__class_getitem__`](https://www.python.org/dev/peps/pep-0560/#class-getitem) magic method in runtime.
1. You can go with our [`django_stubs_ext`](https://github.com/typeddjango/django-stubs/tree/master/django_stubs_ext) helper, that patches all the types we use as Generic in django.
Install it:
```bash
pip install django-stubs-ext # as a production dependency
```
And then place in your top-level settings:
```python
import django_stubs_ext
django_stubs_ext.monkeypatch()
```
Note: This monkey patching approach will only work when using Python 3.7 and higher, when the `__class_getitem__` magic method was introduced.
You can add extra types to patch with `django_stubs_ext.monkeypatch(extra_classes=[YourDesiredType])`
2. You can use strings instead: `'QuerySet[MyModel]'` and `'Manager[MyModel]'`, this way it will work as a type for `mypy` and as a regular `str` in runtime.
### How can I create a HttpRequest that's guaranteed to have an authenticated user?
Django's built in [`HttpRequest`](https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest) has the attribute `user` that resolves to the type
```python
class MyUserManager(models.Manager['MyUser']):
pass
Union[User, AnonymousUser]
```
where `User` is the user model specified by the `AUTH_USER_MODEL` setting.
class MyUser(models.Model):
objects = MyUserManager()
If you want a `HttpRequest` that you can type-annotate with where you know that the user is authenticated you can subclass the normal `HttpRequest` class like so:
```python
from django.http import HttpRequest
from my_user_app.models import MyUser
class AuthenticatedHttpRequest(HttpRequest):
user: MyUser
```
work, which should make a error messages a bit better.
And then use `AuthenticatedHttpRequest` instead of the standard `HttpRequest` for when you know that the user is authenticated. For example in views using the `@login_required` decorator.
### My QuerySet methods are returning Any rather than my Model
If you are using `MyQuerySet.as_manager()`:
Example:
```python
from django.db import models
class MyModelQuerySet(models.QuerySet):
pass
class MyModel(models.Model):
bar = models.IntegerField()
objects = MyModelQuerySet.as_manager()
def use_my_model() -> int:
foo = MyModel.objects.get(id=1) # Should now be `MyModel`
return foo.xyz # Gives an error
```
Or if you're using `Manager.from_queryset`:
Example:
```python
from django.db import models
class MyModelQuerySet(models.QuerySet):
pass
MyModelManager = models.Manager.from_queryset(MyModelQuerySet)
class MyModel(models.Model):
bar = models.IntegerField()
objects = MyModelManager()
def use_my_model() -> int:
foo = MyModel.objects.get(id=1) # Should now be `MyModel`
return foo.xyz # Gives an error
```
### Why am I getting incompatible return type errors on my custom managers?
If you declare your custom managers without generics and override built-in
methods you might see an error message about incompatible error messages,
something like this:
```python
from django.db import models
class MyManager(model.Manager):
def create(self, **kwargs) -> "MyModel":
pass
```
will cause this error message:
```
error: Return type "MyModel" of "create" incompatible with return type "_T" in supertype "BaseManager"
```
This is happening because the `Manager` class is generic, but without
specifying generics the built-in manager methods are expected to return the
generic type of the base manager, which is any model. To fix this issue you
should declare your manager with your model as the type variable:
```python
class MyManager(models.Manager["MyModel"]):
...
```
### How do I annotate cases where I called QuerySet.annotate?
Django-stubs provides a special type, `django_stubs_ext.WithAnnotations[Model]`, which indicates that the `Model` has
been annotated, meaning it allows getting/setting extra attributes on the model instance.
Optionally, you can provide a `TypedDict` of these attributes,
e.g. `WithAnnotations[MyModel, MyTypedDict]`, to specify which annotated attributes are present.
Currently, the mypy plugin can recognize that specific names were passed to `QuerySet.annotate` and
include them in the type, but does not record the types of these attributes.
The knowledge of the specific annotated fields is not yet used in creating more specific types for `QuerySet`'s
`values`, `values_list`, or `filter` methods, however knowledge that the model was annotated _is_ used to create a
broader type result type for `values`/`values_list`, and to allow `filter`ing on any field.
```python
from typing import TypedDict
from django_stubs_ext import WithAnnotations
from django.db import models
from django.db.models.expressions import Value
class MyModel(models.Model):
username = models.CharField(max_length=100)
def func(m: WithAnnotations[MyModel]) -> str:
return m.asdf # OK, since the model is annotated as allowing any attribute
func(MyModel.objects.annotate(foo=Value("")).get(id=1)) # OK
func(
MyModel.objects.get(id=1)
) # Error, since this model will not allow access to any attribute
class MyTypedDict(TypedDict):
foo: str
def func2(m: WithAnnotations[MyModel, MyTypedDict]) -> str:
print(m.bar) # Error, since field "bar" is not in MyModel or MyTypedDict.
return m.foo # OK, since we said field "foo" was allowed
func(MyModel.objects.annotate(foo=Value("")).get(id=1)) # OK
func(MyModel.objects.annotate(bar=Value("")).get(id=1)) # Error
```
## Related projects
- [`awesome-python-typing`](https://github.com/typeddjango/awesome-python-typing) - Awesome list of all typing-related things in Python.
- [`djangorestframework-stubs`](https://github.com/typeddjango/djangorestframework-stubs) - Stubs for Django REST Framework.
- [`pytest-mypy-plugins`](https://github.com/typeddjango/pytest-mypy-plugins) - `pytest` plugin that we use for testing `mypy` stubs and plugins.
- [`wemake-django-template`](https://github.com/wemake-services/wemake-django-template) - Create new typed Django projects in seconds.
Otherwise, custom type will be created in mypy, named `MyUser__MyUserManager`, which will rewrite base manager as `models.Manager[User]` to make methods like `get_queryset()` and others return properly typed `QuerySet`.
## To get help
We have Gitter here: <https://gitter.im/mypy-django/Lobby>
If you think you have more generic typing issue, please refer to <https://github.com/python/mypy> and their Gitter.
If you think you have more generic typing issue, please refer to https://github.com/python/mypy and their Gitter.
## Contributing
This project is open source and community driven. As such we encourage contributions big and small. You can contribute by doing any of the following:
1. Contribute code (e.g. improve stubs, add plugin capabilities, write tests etc) - to do so please follow the [contribution guide](./CONTRIBUTING.md).
2. Assist in code reviews and discussions in issues.
3. Identify bugs and issues and report these
4. Ask and answer questions on [StackOverflow](https://stackoverflow.com/questions/tagged/django-stubs)
You can always also reach out in gitter to discuss your contributions!

View File

@@ -1,8 +0,0 @@
black
pytest-mypy-plugins==1.2.0
psycopg2
flake8==3.7.9
flake8-pyi==19.3.0
isort==4.3.21
gitpython==3.0.5
-e .

View File

@@ -1,12 +1,8 @@
from typing import Any, NamedTuple
from typing import Any
from .utils.version import get_version as get_version
VERSION: Any
__version__: str
def setup(set_prefix: bool = ...) -> None: ...
# Used by mypy_django_plugin when returning a QuerySet row that is a NamedTuple where the field names are unknown
class _NamedTupleAnyAttr(NamedTuple):
def __getattr__(self, item: str) -> Any: ...
def __setattr__(self, item: str, value: Any) -> None: ...

View File

@@ -1,3 +1,2 @@
from .config import AppConfig as AppConfig
from .registry import apps as apps

View File

@@ -1,20 +1,22 @@
from typing import Any, Iterator, Type, Optional, Dict
import types
from typing import Dict, Iterator, Optional, Type
from django.apps.registry import Apps
from django.db.models.base import Model
from django.utils.functional import _StrOrPromise
MODELS_MODULE_NAME: str
class AppConfig:
name: str = ...
module: Optional[Any] = ...
module: Optional[types.ModuleType] = ...
apps: Optional[Apps] = ...
label: str = ...
verbose_name: str = ...
verbose_name: _StrOrPromise = ...
path: str = ...
models_module: Optional[str] = ...
models: Dict[str, Type[Model]] = ...
def __init__(self, app_name: str, app_module: Optional[Any]) -> None: ...
def __init__(self, app_name: str, app_module: Optional[types.ModuleType]) -> None: ...
@classmethod
def create(cls, entry: str) -> AppConfig: ...
def get_model(self, model_name: str, require_ready: bool = ...) -> Type[Model]: ...

View File

@@ -1,4 +1,4 @@
from typing import Any
from typing import Any, Optional
from django.utils.functional import LazyObject
@@ -6,24 +6,34 @@ from django.utils.functional import LazyObject
from . import global_settings
ENVIRONMENT_VARIABLE: str = ...
DEFAULT_CONTENT_TYPE_DEPRECATED_MSG: str = ...
FILE_CHARSET_DEPRECATED_MSG: str = ...
PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG: str = ...
DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG: str = ...
# required for plugin to be able to distinguish this specific instance of LazySettings from others
class _DjangoConfLazyObject(LazyObject):
def __getattr__(self, item: Any) -> Any: ...
class LazySettings(_DjangoConfLazyObject):
configured: bool
def configure(self, default_settings: Any = ..., **options: Any) -> Any: ...
SETTINGS_MODULE: str
@property
def configured(self) -> bool: ...
def configure(self, default_settings: Any = ..., **options: Any) -> None: ...
settings: LazySettings = ...
class Settings:
def __init__(self, settings_module: str): ...
SETTINGS_MODULE: str
def __init__(self, settings_module: str) -> None: ...
def is_overridden(self, setting: str) -> bool: ...
class UserSettingsHolder: ...
class UserSettingsHolder:
SETTINGS_MODULE: None = ...
def __init__(self, default_settings: Any) -> None: ...
def __getattr__(self, name: str) -> Any: ...
def __setattr__(self, name: str, value: Any) -> None: ...
def __delattr__(self, name: str) -> None: ...
def is_overridden(self, setting: str) -> bool: ...
class SettingsReference(str):
def __new__(self, value: Any, setting_name: str) -> SettingsReference: ...
def __init__(self, value: str, setting_name: str) -> None: ...

View File

@@ -7,6 +7,8 @@ by the DJANGO_SETTINGS_MODULE environment variable.
# django.utils.translation -- that module depends on the settings.
from typing import Any, Dict, List, Optional, Pattern, Protocol, Sequence, Tuple, Union
from typing_extensions import Literal
####################
# CORE #
####################
@@ -68,15 +70,11 @@ USE_L10N: bool = ...
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# Default charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE: str = ...
DEFAULT_CHARSET: str = ...
# Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET: str = ...
# Email address that error messages come from.
SERVER_EMAIL: str = ...
@@ -85,7 +83,7 @@ DATABASES: Dict[str, Dict[str, Any]] = ...
# Classes used to implement DB routing behavior.
class Router(Protocol):
def allow_migrate(self, db, app_label, **hints): ...
def allow_migrate(self, db: str, app_label: str, **hints: Any) -> Optional[bool]: ...
DATABASE_ROUTERS: List[Union[str, Router]] = ...
@@ -136,7 +134,7 @@ APPEND_SLASH: bool = ...
PREPEND_WWW: bool = ...
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
FORCE_SCRIPT_NAME: Optional[str] = ...
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
@@ -148,7 +146,7 @@ FORCE_SCRIPT_NAME = None
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search'),
# ]
DISALLOWED_USER_AGENTS: List[Pattern] = ...
DISALLOWED_USER_AGENTS: List[Pattern[str]] = ...
ABSOLUTE_URL_OVERRIDES: Dict[str, Any] = ...
@@ -162,7 +160,7 @@ ABSOLUTE_URL_OVERRIDES: Dict[str, Any] = ...
# re.compile(r'^/phpmyadmin/'),
# re.compile(r'\.(cgi|php|pl)$'),
# ]
IGNORABLE_404_URLS: List[Pattern] = ...
IGNORABLE_404_URLS: List[Pattern[str]] = ...
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
@@ -210,12 +208,12 @@ FILE_UPLOAD_TEMP_DIR: Optional[str] = ...
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_PERMISSIONS: int = ...
# The numeric mode to assign to newly-created directories, when uploading files.
# The value should be a mode as you'd pass to os.chmod;
# see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
FILE_UPLOAD_DIRECTORY_PERMISSIONS: Optional[int] = ...
# Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
@@ -330,33 +328,33 @@ MIDDLEWARE: List[str] = ...
############
# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = "default"
SESSION_CACHE_ALIAS: str = ...
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = "sessionid"
SESSION_COOKIE_NAME: str = ...
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
SESSION_COOKIE_AGE: int = ...
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN: Optional[str] = ...
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_SECURE: bool = ...
# The path of the session cookie.
SESSION_COOKIE_PATH = "/"
SESSION_COOKIE_PATH: str = ...
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_HTTPONLY: bool = ...
# Whether to set the flag restricting cookie leaks on cross-site requests.
# This can be 'Lax', 'Strict', or None to disable the flag.
SESSION_COOKIE_SAMESITE: Optional[str] = ...
# This can be 'Lax', 'Strict', 'None', or False to disable the flag.
SESSION_COOKIE_SAMESITE: Literal["Lax", "Strict", "None", False] = ...
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
SESSION_SAVE_EVERY_REQUEST: bool = ...
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_EXPIRE_AT_BROWSER_CLOSE: bool = ...
# The module to store session data
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_ENGINE: str = ...
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH: Optional[str] = ...
# class to serialize session data
SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
SESSION_SERIALIZER: str = ...
#########
# CACHE #
@@ -364,9 +362,9 @@ SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
# The cache backends to use.
CACHES: Dict[str, Dict[str, Any]] = ...
CACHE_MIDDLEWARE_KEY_PREFIX = ""
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = "default"
CACHE_MIDDLEWARE_KEY_PREFIX: str = ...
CACHE_MIDDLEWARE_SECONDS: int = ...
CACHE_MIDDLEWARE_ALIAS: str = ...
##################
# AUTHENTICATION #
@@ -376,14 +374,14 @@ AUTH_USER_MODEL: str = ...
AUTHENTICATION_BACKENDS: Sequence[str] = ...
LOGIN_URL = "/accounts/login/"
LOGIN_URL: str = ...
LOGIN_REDIRECT_URL: str = ...
LOGOUT_REDIRECT_URL: Optional[str] = ...
# The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3
PASSWORD_RESET_TIMEOUT_DAYS: int = ...
# the first hasher in this list is the preferred algorithm. any
# password using different algorithms will be converted automatically
@@ -396,7 +394,7 @@ AUTH_PASSWORD_VALIDATORS: List[Dict[str, str]] = ...
# SIGNING #
###########
SIGNING_BACKEND = "django.core.signing.TimestampSigner"
SIGNING_BACKEND: str = ...
########
# CSRF #
@@ -404,26 +402,26 @@ SIGNING_BACKEND = "django.core.signing.TimestampSigner"
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure"
CSRF_FAILURE_VIEW: str = ...
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = "csrftoken"
CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = "/"
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE: Optional[str] = ...
CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN"
CSRF_COOKIE_NAME: str = ...
CSRF_COOKIE_AGE: int = ...
CSRF_COOKIE_DOMAIN: Optional[str] = ...
CSRF_COOKIE_PATH: str = ...
CSRF_COOKIE_SECURE: bool = ...
CSRF_COOKIE_HTTPONLY: bool = ...
CSRF_COOKIE_SAMESITE: Literal["Lax", "Strict", "None", False] = ...
CSRF_HEADER_NAME: str = ...
CSRF_TRUSTED_ORIGINS: List[str] = ...
CSRF_USE_SESSIONS = False
CSRF_USE_SESSIONS: bool = ...
############
# MESSAGES #
############
# Class to use as messages backend
MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage"
MESSAGE_STORAGE: str = ...
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
@@ -433,21 +431,21 @@ MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage"
###########
# The callable to use to configure logging
LOGGING_CONFIG = "logging.config.dictConfig"
LOGGING_CONFIG: str = ...
# Custom logging configuration.
LOGGING: Dict[str, Any] = ...
# Default exception reporter filter class used in case none has been
# specifically assigned to the HttpRequest instance.
DEFAULT_EXCEPTION_REPORTER_FILTER = "django.views.debug.SafeExceptionReporterFilter"
DEFAULT_EXCEPTION_REPORTER_FILTER: str = ...
###########
# TESTING #
###########
# The name of the class to use to run the test suite
TEST_RUNNER = "django.test.runner.DiscoverRunner"
TEST_RUNNER: str = ...
# Apps that don't need to be serialized at test database creation time
# (only apps with migrations are to start with)
@@ -494,11 +492,11 @@ SILENCED_SYSTEM_CHECKS: List[str] = ...
#######################
# SECURITY MIDDLEWARE #
#######################
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_BROWSER_XSS_FILTER: bool = ...
SECURE_CONTENT_TYPE_NOSNIFF: bool = ...
SECURE_HSTS_INCLUDE_SUBDOMAINS: bool = ...
SECURE_HSTS_PRELOAD: bool = ...
SECURE_HSTS_SECONDS: int = ...
SECURE_REDIRECT_EXEMPT: List[str] = ...
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
SECURE_SSL_HOST: Optional[str] = ...
SECURE_SSL_REDIRECT: bool = ...

View File

@@ -1,3 +1,3 @@
from typing import Dict, Any
from typing import Any, Dict
LANG_INFO: Dict[str, Any] = ...

View File

@@ -1,25 +1,30 @@
# Stubs for django.conf.urls (Python 3.5)
from typing import Any, Callable, Dict, List, Optional, overload, Tuple, Union
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union, overload
from django.http.response import HttpResponse, HttpResponseBase
from django.urls import URLPattern, URLResolver
from django.urls import include as include
from django.urls import URLResolver, URLPattern
handler400: Union[str, Callable[..., HttpResponse]] = ...
handler403: Union[str, Callable[..., HttpResponse]] = ...
handler404: Union[str, Callable[..., HttpResponse]] = ...
handler500: Union[str, Callable[..., HttpResponse]] = ...
handler400: Callable[..., HttpResponse] = ...
handler403: Callable[..., HttpResponse] = ...
handler404: Callable[..., HttpResponse] = ...
handler500: Callable[..., HttpResponse] = ...
IncludedURLConf = Tuple[Sequence[Union[URLResolver, URLPattern]], Optional[str], Optional[str]]
IncludedURLConf = Tuple[List[URLResolver], Optional[str], Optional[str]]
def include(arg: Any, namespace: str = ..., app_name: str = ...) -> IncludedURLConf: ...
# Deprecated
@overload
def url(
regex: str, view: Callable[..., HttpResponseBase], kwargs: Dict[str, Any] = ..., name: str = ...
regex: str, view: Callable[..., HttpResponseBase], kwargs: Optional[Dict[str, Any]] = ..., name: Optional[str] = ...
) -> URLPattern: ...
@overload
def url(regex: str, view: IncludedURLConf, kwargs: Dict[str, Any] = ..., name: str = ...) -> URLResolver: ...
def url(
regex: str, view: IncludedURLConf, kwargs: Optional[Dict[str, Any]] = ..., name: Optional[str] = ...
) -> URLResolver: ...
@overload
def url(
regex: str, view: List[Union[URLResolver, str]], kwargs: Dict[str, Any] = ..., name: str = ...
regex: str,
view: Sequence[Union[URLResolver, str]],
kwargs: Optional[Dict[str, Any]] = ...,
name: Optional[str] = ...,
) -> URLResolver: ...

View File

@@ -1,8 +1,8 @@
from typing import Any, List, Tuple, Callable
from typing import List, Tuple
from django.urls.resolvers import URLPattern
from django.urls import _AnyURL
def i18n_patterns(*urls: Any, prefix_default_language: bool = ...) -> List[List[URLPattern]]: ...
def i18n_patterns(*urls: _AnyURL, prefix_default_language: bool = ...) -> List[_AnyURL]: ...
def is_language_prefix_patterns_used(urlconf: str) -> Tuple[bool, bool]: ...
urlpatterns: List[Callable]
urlpatterns: List[_AnyURL]

View File

@@ -1,24 +1,23 @@
from .decorators import register as register
from .filters import (
AllValuesFieldListFilter as AllValuesFieldListFilter,
BooleanFieldListFilter as BooleanFieldListFilter,
ChoicesFieldListFilter as ChoicesFieldListFilter,
DateFieldListFilter as DateFieldListFilter,
FieldListFilter as FieldListFilter,
ListFilter as ListFilter,
RelatedFieldListFilter as RelatedFieldListFilter,
RelatedOnlyFieldListFilter as RelatedOnlyFieldListFilter,
SimpleListFilter as SimpleListFilter,
)
from .helpers import ACTION_CHECKBOX_NAME as ACTION_CHECKBOX_NAME
from .options import (
HORIZONTAL as HORIZONTAL,
VERTICAL as VERTICAL,
ModelAdmin as ModelAdmin,
StackedInline as StackedInline,
TabularInline as TabularInline,
)
from .sites import AdminSite as AdminSite, site as site
from . import checks as checks
from .decorators import action as action
from .decorators import display as display
from .decorators import register as register
from .filters import AllValuesFieldListFilter as AllValuesFieldListFilter
from .filters import BooleanFieldListFilter as BooleanFieldListFilter
from .filters import ChoicesFieldListFilter as ChoicesFieldListFilter
from .filters import DateFieldListFilter as DateFieldListFilter
from .filters import EmptyFieldListFilter as EmptyFieldListFilter
from .filters import FieldListFilter as FieldListFilter
from .filters import ListFilter as ListFilter
from .filters import RelatedFieldListFilter as RelatedFieldListFilter
from .filters import RelatedOnlyFieldListFilter as RelatedOnlyFieldListFilter
from .filters import SimpleListFilter as SimpleListFilter
from .options import HORIZONTAL as HORIZONTAL
from .options import VERTICAL as VERTICAL
from .options import ModelAdmin as ModelAdmin
from .options import StackedInline as StackedInline
from .options import TabularInline as TabularInline
from .sites import AdminSite as AdminSite
from .sites import site as site
def autodiscover() -> None: ...

View File

@@ -1,8 +1,8 @@
from typing import Optional
from django.contrib.admin.options import ModelAdmin
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.query import QuerySet
from django.http.request import HttpRequest
from django.template.response import TemplateResponse
def delete_selected(modeladmin: ModelAdmin, request: WSGIRequest, queryset: QuerySet) -> Optional[TemplateResponse]: ...
def delete_selected(modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet) -> Optional[TemplateResponse]: ...

View File

@@ -1,21 +1,21 @@
from typing import Any, List, Union, Iterable, Optional
from django.contrib.admin.options import BaseModelAdmin
from django.core.checks.messages import Error
from typing import Any, List, Optional, Sequence
from django.apps.config import AppConfig
from django.contrib.admin.options import BaseModelAdmin
from django.core.checks.messages import CheckMessage, Error
_CheckError = Union[str, Error]
def check_admin_app(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[_CheckError]: ...
def check_dependencies(**kwargs: Any) -> List[_CheckError]: ...
def check_admin_app(app_configs: Optional[Sequence[AppConfig]], **kwargs: Any) -> List[CheckMessage]: ...
def check_dependencies(**kwargs: Any) -> List[CheckMessage]: ...
class BaseModelAdminChecks:
def check(self, admin_obj: BaseModelAdmin, **kwargs: Any) -> List[_CheckError]: ...
def check(self, admin_obj: BaseModelAdmin, **kwargs: Any) -> List[CheckMessage]: ...
class ModelAdminChecks(BaseModelAdminChecks): ...
class InlineModelAdminChecks(BaseModelAdminChecks): ...
class ModelAdminChecks(BaseModelAdminChecks):
def check(self, admin_obj: BaseModelAdmin, **kwargs: Any) -> List[CheckMessage]: ...
def must_be(type: Any, option: Any, obj: Any, id: Any): ...
def must_inherit_from(parent: Any, option: Any, obj: Any, id: Any): ...
def refer_to_missing_field(field: Any, option: Any, model: Any, obj: Any, id: Any): ...
class InlineModelAdminChecks(BaseModelAdminChecks):
def check(self, inline_obj: BaseModelAdmin, **kwargs: Any) -> List[CheckMessage]: ... # type: ignore
def must_be(type: Any, option: Any, obj: Any, id: Any) -> List[CheckMessage]: ...
def must_inherit_from(parent: Any, option: Any, obj: Any, id: Any) -> List[CheckMessage]: ...
def refer_to_missing_field(field: Any, option: Any, obj: Any, id: Any) -> List[CheckMessage]: ...

View File

@@ -1,5 +1,26 @@
from typing import Any, Callable, Optional, Type
from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union
from django.contrib.admin import ModelAdmin
from django.contrib.admin.sites import AdminSite
from django.db.models import Combinable, QuerySet
from django.db.models.base import Model
from django.db.models.expressions import BaseExpression
from django.http import HttpRequest
def register(*models: Type[Model], site: Optional[Any] = ...) -> Callable: ...
_ModelT = TypeVar("_ModelT", bound=Model)
def action(
function: Optional[Callable[[ModelAdmin, HttpRequest, QuerySet], None]] = ...,
*,
permissions: Optional[Sequence[str]] = ...,
description: Optional[str] = ...,
) -> Callable: ...
def display(
function: Optional[Callable[[_ModelT], Any]] = ...,
*,
boolean: Optional[bool] = ...,
ordering: Optional[Union[str, Combinable, BaseExpression]] = ...,
description: Optional[str] = ...,
empty_value: Optional[str] = ...,
) -> Callable: ...
def register(*models: Type[Model], site: Optional[AdminSite] = ...) -> Callable: ...

View File

@@ -0,0 +1,4 @@
from django.core.exceptions import SuspiciousOperation as SuspiciousOperation
class DisallowedModelAdminLookup(SuspiciousOperation): ...
class DisallowedModelAdminToField(SuspiciousOperation): ...

View File

@@ -1,39 +1,39 @@
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Iterator
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Type
from django.contrib.admin.options import ModelAdmin
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.db.models.fields import Field
from django.db.models.fields.related import RelatedField
from django.db.models.query import QuerySet
from django.db.models.fields import Field
from django.http.request import HttpRequest
class ListFilter:
title: Any = ...
title: str = ...
template: str = ...
used_parameters: Any = ...
def __init__(
self, request: WSGIRequest, params: Dict[str, str], model: Type[Model], model_admin: ModelAdmin
self, request: HttpRequest, params: Dict[str, str], model: Type[Model], model_admin: ModelAdmin
) -> None: ...
def has_output(self) -> bool: ...
def choices(self, changelist: Any) -> Optional[Iterator[Dict[str, Any]]]: ...
def queryset(self, request: Any, queryset: QuerySet) -> Optional[QuerySet]: ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
def queryset(self, request: HttpRequest, queryset: QuerySet) -> Optional[QuerySet]: ...
def expected_parameters(self) -> Optional[List[str]]: ...
class SimpleListFilter(ListFilter):
parameter_name: Any = ...
parameter_name: str = ...
lookup_choices: Any = ...
def value(self) -> Optional[str]: ...
def lookups(self, request: Any, model_admin: Any) -> List[Tuple[Any, str]]: ...
def lookups(self, request: HttpRequest, model_admin: ModelAdmin) -> Optional[Iterable[Tuple[Any, str]]]: ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class FieldListFilter(ListFilter):
field: Field = ...
field_path: Any = ...
title: Any = ...
field_path: str = ...
title: str = ...
def __init__(
self,
field: Field,
request: WSGIRequest,
request: HttpRequest,
params: Dict[str, str],
model: Type[Model],
model_admin: ModelAdmin,
@@ -45,7 +45,7 @@ class FieldListFilter(ListFilter):
def create(
cls,
field: Field,
request: WSGIRequest,
request: HttpRequest,
params: Dict[str, str],
model: Type[Model],
model_admin: ModelAdmin,
@@ -56,32 +56,34 @@ class RelatedFieldListFilter(FieldListFilter):
used_parameters: Dict[Any, Any]
lookup_kwarg: str = ...
lookup_kwarg_isnull: str = ...
lookup_val: None = ...
lookup_val_isnull: None = ...
lookup_val: Any = ...
lookup_val_isnull: Any = ...
lookup_choices: Any = ...
lookup_title: Any = ...
lookup_title: str = ...
title: str = ...
empty_value_display: Any = ...
@property
def include_empty_choice(self) -> bool: ...
def field_choices(
self, field: RelatedField, request: WSGIRequest, model_admin: ModelAdmin
self, field: RelatedField, request: HttpRequest, model_admin: ModelAdmin
) -> List[Tuple[str, str]]: ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class BooleanFieldListFilter(FieldListFilter):
lookup_kwarg: Any = ...
lookup_kwarg2: Any = ...
lookup_kwarg: str = ...
lookup_kwarg2: str = ...
lookup_val: Any = ...
lookup_val2: Any = ...
def choices(self, changelist: Any) -> None: ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class ChoicesFieldListFilter(FieldListFilter):
title: str
used_parameters: Dict[Any, Any]
lookup_kwarg: str = ...
lookup_kwarg_isnull: str = ...
lookup_val: None = ...
lookup_val_isnull: None = ...
lookup_val: Any = ...
lookup_val_isnull: Any = ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class DateFieldListFilter(FieldListFilter):
field_generic: Any = ...
@@ -90,21 +92,28 @@ class DateFieldListFilter(FieldListFilter):
lookup_kwarg_until: Any = ...
links: Any = ...
lookup_kwarg_isnull: Any = ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class AllValuesFieldListFilter(FieldListFilter):
title: str
used_parameters: Dict[Any, Any]
lookup_kwarg: str = ...
lookup_kwarg_isnull: str = ...
lookup_val: None = ...
lookup_val_isnull: None = ...
lookup_val: Any = ...
lookup_val_isnull: Any = ...
empty_value_display: str = ...
lookup_choices: QuerySet = ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...
class RelatedOnlyFieldListFilter(RelatedFieldListFilter):
lookup_kwarg: str
lookup_kwarg_isnull: str
lookup_val: None
lookup_val_isnull: None
lookup_val: Any
lookup_val_isnull: Any
title: str
used_parameters: Dict[Any, Any]
class EmptyFieldListFilter(FieldListFilter):
lookup_kwarg: str = ...
lookup_val: Any = ...
def choices(self, changelist: Any) -> Iterator[Dict[str, Any]]: ...

View File

@@ -1,13 +1,16 @@
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union, Iterable
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.forms.boundfield import BoundField
from django.forms.utils import ErrorDict
from django.forms.widgets import Media, Widget
from django.utils.safestring import SafeText
from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
from django import forms
from django.contrib.admin.options import ModelAdmin
from django.db.models import Model
from django.db.models.fields import AutoField
from django.forms import BaseForm
from django.forms.boundfield import BoundField
from django.forms.models import ModelForm
from django.forms.utils import ErrorDict, ErrorList
from django.forms.widgets import Media, Widget
from django.utils.safestring import SafeString
from typing_extensions import TypedDict
ACTION_CHECKBOX_NAME: str
@@ -17,99 +20,121 @@ class ActionForm(forms.Form):
checkbox: Any
class _PrepopulatedDict(TypedDict):
field: BoundField
dependencies: List[BoundField]
class AdminForm:
prepopulated_fields: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
prepopulated_fields: List[_PrepopulatedDict]
model_admin: Optional[ModelAdmin] = ...
readonly_fields: Sequence[str] = ...
form: ModelForm
fieldsets: List[Tuple[Any, Dict[str, List[str]]]]
def __init__(
self,
form: AdminPasswordChangeForm,
fieldsets: List[Tuple[None, Dict[str, List[str]]]],
prepopulated_fields: Dict[Any, Any],
readonly_fields: Optional[Iterable[Any]] = ...,
model_admin: Any = ...,
form: ModelForm,
fieldsets: List[Tuple[Any, Dict[str, List[str]]]],
prepopulated_fields: Mapping[str, Iterable[str]],
readonly_fields: Optional[Sequence[str]] = ...,
model_admin: Optional[ModelAdmin] = ...,
) -> None: ...
def __iter__(self) -> Iterator[Fieldset]: ...
@property
def errors(self) -> ErrorDict: ...
@property
def non_field_errors(self) -> Callable: ...
def non_field_errors(self) -> Callable[[], ErrorList]: ...
@property
def media(self) -> Media: ...
class Fieldset:
form: Any = ...
classes: Any = ...
description: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
form: ModelForm = ...
classes: str = ...
description: Optional[str] = ...
model_admin: Optional[ModelAdmin] = ...
readonly_fields: Sequence[str] = ...
def __init__(
self,
form: Any,
form: ModelForm,
name: Optional[Any] = ...,
readonly_fields: Optional[Iterable[Any]] = ...,
fields: Any = ...,
classes: Any = ...,
description: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
readonly_fields: Sequence[str] = ...,
fields: Sequence[str] = ...,
classes: Iterable[str] = ...,
description: Optional[str] = ...,
model_admin: Optional[ModelAdmin] = ...,
) -> None: ...
@property
def media(self) -> Media: ...
def __iter__(self) -> Iterator[Fieldline]: ...
class Fieldline:
form: Any = ...
fields: Any = ...
has_visible_field: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
form: ModelForm = ...
fields: Sequence[str] = ...
has_visible_field: bool = ...
model_admin: Optional[ModelAdmin] = ...
readonly_fields: Sequence[str] = ...
def __init__(
self, form: Any, field: Any, readonly_fields: Optional[Iterable[Any]] = ..., model_admin: Optional[Any] = ...
self,
form: ModelForm,
field: Union[str, Sequence[str]],
readonly_fields: Optional[Sequence[str]] = ...,
model_admin: Optional[ModelAdmin] = ...,
) -> None: ...
def __iter__(self) -> Iterator[Union[AdminField, AdminReadonlyField]]: ...
def errors(self) -> SafeText: ...
def errors(self) -> SafeString: ...
class AdminField:
field: BoundField = ...
is_first: bool = ...
is_checkbox: bool = ...
is_readonly: bool = ...
def __init__(self, form: Any, field: Any, is_first: Any) -> None: ...
def label_tag(self) -> SafeText: ...
def errors(self) -> SafeText: ...
def __init__(self, form: ModelForm, field: str, is_first: bool) -> None: ...
def label_tag(self) -> SafeString: ...
def errors(self) -> SafeString: ...
class _FieldDictT(TypedDict):
name: str
label: str
help_text: str
field: Union[Callable[[Model], Any], str]
class AdminReadonlyField:
field: Any = ...
form: Any = ...
model_admin: Any = ...
is_first: Any = ...
field: _FieldDictT = ...
form: ModelForm = ...
model_admin: Optional[ModelAdmin] = ...
is_first: bool = ...
is_checkbox: bool = ...
is_readonly: bool = ...
empty_value_display: Any = ...
def __init__(self, form: Any, field: Any, is_first: Any, model_admin: Optional[Any] = ...) -> None: ...
def label_tag(self) -> SafeText: ...
def contents(self) -> SafeText: ...
def __init__(
self,
form: ModelForm,
field: Union[Callable[[Model], Any], str],
is_first: bool,
model_admin: Optional[ModelAdmin] = ...,
) -> None: ...
def label_tag(self) -> SafeString: ...
def contents(self) -> SafeString: ...
class InlineAdminFormSet:
opts: Any = ...
formset: Any = ...
fieldsets: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
prepopulated_fields: Any = ...
classes: Any = ...
has_add_permission: Any = ...
has_change_permission: Any = ...
has_delete_permission: Any = ...
has_view_permission: Any = ...
model_admin: Optional[ModelAdmin] = ...
readonly_fields: Sequence[str] = ...
prepopulated_fields: Dict[str, Any] = ...
classes: str = ...
has_add_permission: bool = ...
has_change_permission: bool = ...
has_delete_permission: bool = ...
has_view_permission: bool = ...
def __init__(
self,
inline: Any,
formset: Any,
fieldsets: Any,
prepopulated_fields: Optional[Any] = ...,
readonly_fields: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
prepopulated_fields: Optional[Dict[str, Any]] = ...,
readonly_fields: Optional[Sequence[str]] = ...,
model_admin: Optional[ModelAdmin] = ...,
has_add_permission: bool = ...,
has_change_permission: bool = ...,
has_delete_permission: bool = ...,
@@ -119,37 +144,38 @@ class InlineAdminFormSet:
def fields(self) -> Iterator[Dict[str, Union[Dict[str, bool], bool, Widget, str]]]: ...
def inline_formset_data(self) -> str: ...
@property
def forms(self): ...
def forms(self) -> List[BaseForm]: ...
@property
def non_form_errors(self) -> Callable: ...
def non_form_errors(self) -> Callable[[], ErrorList]: ...
@property
def media(self) -> Media: ...
class InlineAdminForm(AdminForm):
formset: Any = ...
original: Any = ...
show_url: Any = ...
absolute_url: Any = ...
original: Optional[bool] = ...
show_url: bool = ...
absolute_url: Optional[str] = ...
def __init__(
self,
formset: Any,
form: Any,
form: ModelForm,
fieldsets: Any,
prepopulated_fields: Any,
original: Any,
readonly_fields: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
view_on_site_url: Optional[Any] = ...,
original: Optional[bool],
readonly_fields: Optional[Sequence[str]] = ...,
model_admin: Optional[ModelAdmin] = ...,
view_on_site_url: Optional[str] = ...,
) -> None: ...
def __iter__(self) -> Iterator[InlineFieldset]: ...
def needs_explicit_pk_field(self) -> Union[bool, AutoField]: ...
def pk_field(self) -> AdminField: ...
def fk_field(self) -> AdminField: ...
def deletion_field(self) -> AdminField: ...
def ordering_field(self): ...
class InlineFieldset(Fieldset):
formset: Any = ...
def __init__(self, formset: Any, *args: Any, **kwargs: Any) -> None: ...
def __iter__(self) -> Iterator[Fieldline]: ...
class AdminErrorList(forms.utils.ErrorList):
def __init__(self, form: Any, inline_formsets: Any) -> None: ...
def __init__(self, form: ModelForm, inline_formsets: Any) -> None: ...

View File

@@ -2,9 +2,8 @@ from typing import Any, Optional, Union
from uuid import UUID
from django.contrib.contenttypes.models import ContentType
from django.db.models.base import Model
from django.db import models
from django.db.models.base import Model
ADDITION: int
CHANGE: int

View File

@@ -1,33 +1,62 @@
from collections import OrderedDict
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, Union
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
from django.contrib.admin.filters import ListFilter
from django import forms
from django.contrib.admin.filters import FieldListFilter, ListFilter
from django.contrib.admin.models import LogEntry
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.contrib.contenttypes.models import ContentType
from django.core.checks.messages import Error
from django.core.checks.messages import CheckMessage
from django.core.paginator import Paginator
from django.db.models.base import Model
from django.db.models.fields import Field
from django.db.models.fields.related import ForeignKey, ManyToManyField, RelatedField
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.fields import Field as FormField
from django.forms.fields import TypedChoiceField
from django.forms.models import ModelChoiceField, ModelMultipleChoiceField
from django.forms.forms import BaseForm
from django.forms.formsets import BaseFormSet
from django.forms.models import (
BaseInlineFormSet,
BaseModelFormSet,
ModelChoiceField,
ModelForm,
ModelMultipleChoiceField,
)
from django.forms.widgets import Media
from django.http.request import HttpRequest
from django.http.response import HttpResponse, HttpResponseBase, HttpResponseRedirect, JsonResponse
from django.template.response import TemplateResponse
from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template.response import _TemplateForResponseT
from django.urls.resolvers import URLPattern
from django.utils.safestring import SafeText
from django.db.models.fields import Field
from django.utils.datastructures import _ListOrTuple
from django.utils.functional import _StrOrPromise
from django.utils.safestring import SafeString
from typing_extensions import Literal, TypedDict
IS_POPUP_VAR: str
TO_FIELD_VAR: str
HORIZONTAL: Any
VERTICAL: Any
HORIZONTAL: Literal[1] = ...
VERTICAL: Literal[2] = ...
_Direction = Union[Literal[1], Literal[2]]
def get_content_type_for_model(obj: Union[Type[Model], Model]) -> ContentType: ...
def get_ul_class(radio_style: int) -> str: ...
@@ -37,107 +66,142 @@ class IncorrectLookupParameters(Exception): ...
FORMFIELD_FOR_DBFIELD_DEFAULTS: Any
csrf_protect_m: Any
class BaseModelAdmin:
autocomplete_fields: Any = ...
raw_id_fields: Any = ...
fields: Any = ...
exclude: Any = ...
fieldsets: Any = ...
form: Any = ...
filter_vertical: Any = ...
filter_horizontal: Any = ...
radio_fields: Any = ...
prepopulated_fields: Any = ...
formfield_overrides: Any = ...
readonly_fields: Any = ...
ordering: Any = ...
sortable_by: Any = ...
view_on_site: bool = ...
_FieldGroups = Sequence[Union[str, Sequence[str]]]
class _OptionalFieldOpts(TypedDict, total=False):
classes: Sequence[str]
description: str
class _FieldOpts(_OptionalFieldOpts, total=True):
fields: _FieldGroups
# Workaround for mypy issue, a Sequence type should be preferred here.
# https://github.com/python/mypy/issues/8921
# _FieldsetSpec = Sequence[Tuple[Optional[str], _FieldOpts]]
_FieldsetSpec = _ListOrTuple[Tuple[Optional[str], _FieldOpts]]
_ListFilterT = Union[
Type[ListFilter],
Field,
str,
Tuple[Union[Field, str], Type[FieldListFilter]],
List[Union[Field, str, Type[FieldListFilter]]],
]
# Generic type specifically for models, for use in BaseModelAdmin and subclasses
# https://github.com/typeddjango/django-stubs/issues/482
_ModelT = TypeVar("_ModelT", bound=Model)
class BaseModelAdmin(Generic[_ModelT]):
autocomplete_fields: Sequence[str] = ...
raw_id_fields: Sequence[str] = ...
fields: Optional[_FieldGroups] = ...
exclude: Optional[Sequence[str]] = ...
fieldsets: Optional[_FieldsetSpec] = ...
form: Type[forms.ModelForm[_ModelT]] = ...
filter_vertical: Sequence[str] = ...
filter_horizontal: Sequence[str] = ...
radio_fields: Mapping[str, _Direction] = ...
prepopulated_fields: Dict[str, Sequence[str]] = ...
formfield_overrides: Mapping[Type[Field], Mapping[str, Any]] = ...
readonly_fields: Sequence[str] = ...
ordering: Optional[Sequence[str]] = ...
sortable_by: Optional[_ListOrTuple[str]] = ...
view_on_site: Union[bool, Callable[[_ModelT], str]] = ...
show_full_result_count: bool = ...
checks_class: Any = ...
def check(self, **kwargs: Any) -> List[Union[str, Error]]: ...
def formfield_for_dbfield(
self, db_field: Field, request: Optional[HttpRequest], **kwargs: Any
) -> Optional[Field]: ...
def formfield_for_choice_field(
self, db_field: Field, request: Optional[HttpRequest], **kwargs: Any
) -> TypedChoiceField: ...
model: Type[_ModelT]
opts: Options[_ModelT]
admin_site: AdminSite
def __init__(self) -> None: ...
def check(self, **kwargs: Any) -> List[CheckMessage]: ...
def formfield_for_dbfield(self, db_field: Field, request: HttpRequest, **kwargs: Any) -> Optional[FormField]: ...
def formfield_for_choice_field(self, db_field: Field, request: HttpRequest, **kwargs: Any) -> TypedChoiceField: ...
def get_field_queryset(
self, db: None, db_field: RelatedField, request: Optional[HttpRequest]
self, db: Optional[str], db_field: RelatedField, request: HttpRequest
) -> Optional[QuerySet]: ...
def formfield_for_foreignkey(
self, db_field: ForeignKey, request: Optional[HttpRequest], **kwargs: Any
) -> Optional[ModelChoiceField]: ...
self, db_field: ForeignKey, request: HttpRequest, **kwargs: Any
) -> ModelChoiceField: ...
def formfield_for_manytomany(
self, db_field: ManyToManyField, request: Optional[HttpRequest], **kwargs: Any
) -> ModelMultipleChoiceField: ...
def get_autocomplete_fields(self, request: HttpRequest) -> Tuple: ...
def get_view_on_site_url(self, obj: Optional[Model] = ...) -> Optional[str]: ...
def get_empty_value_display(self) -> SafeText: ...
def get_exclude(self, request: HttpRequest, obj: Optional[Model] = ...) -> Any: ...
def get_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Sequence[Union[Callable, str]]: ...
def get_fieldsets(
self, request: HttpRequest, obj: Optional[Model] = ...
) -> List[Tuple[Optional[str], Dict[str, Any]]]: ...
def get_ordering(self, request: HttpRequest) -> Union[List[str], Tuple]: ...
def get_readonly_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Union[List[str], Tuple]: ...
def get_prepopulated_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Dict[str, Tuple[str]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet: ...
def get_sortable_by(self, request: HttpRequest) -> Union[List[Callable], List[str], Tuple]: ...
self, db_field: ManyToManyField, request: HttpRequest, **kwargs: Any
) -> Optional[ModelMultipleChoiceField]: ...
def get_autocomplete_fields(self, request: HttpRequest) -> Sequence[str]: ...
def get_view_on_site_url(self, obj: Optional[_ModelT] = ...) -> Optional[str]: ...
def get_empty_value_display(self) -> SafeString: ...
def get_exclude(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Optional[Sequence[str]]: ...
def get_fields(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> _FieldGroups: ...
def get_fieldsets(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> _FieldsetSpec: ...
def get_inlines(self, request: HttpRequest, obj: Optional[_ModelT]) -> List[Type[InlineModelAdmin]]: ...
def get_ordering(self, request: HttpRequest) -> Sequence[str]: ...
def get_readonly_fields(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Sequence[str]: ...
def get_prepopulated_fields(
self, request: HttpRequest, obj: Optional[_ModelT] = ...
) -> Dict[str, Sequence[str]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet[_ModelT]: ...
def get_sortable_by(self, request: HttpRequest) -> Sequence[str]: ...
def lookup_allowed(self, lookup: str, value: str) -> bool: ...
def to_field_allowed(self, request: HttpRequest, to_field: str) -> bool: ...
def has_add_permission(self, request: HttpRequest) -> bool: ...
def has_change_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_delete_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_view_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_change_permission(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> bool: ...
def has_delete_permission(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> bool: ...
def has_view_permission(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> bool: ...
def has_view_or_change_permission(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> bool: ...
def has_module_permission(self, request: HttpRequest) -> bool: ...
class ModelAdmin(BaseModelAdmin):
list_display: Sequence[Union[str, Callable]] = ...
list_display_links: Optional[Sequence[Union[str, Callable]]] = ...
list_filter: Sequence[Union[str, Type[ListFilter], Tuple[str, Type[ListFilter]]]] = ...
_DisplayT = _ListOrTuple[Union[str, Callable[[_ModelT], str]]]
class ModelAdmin(BaseModelAdmin[_ModelT]):
list_display: _DisplayT = ...
list_display_links: Optional[_DisplayT] = ...
list_filter: _ListOrTuple[_ListFilterT] = ...
list_select_related: Union[bool, Sequence[str]] = ...
list_per_page: int = ...
list_max_show_all: int = ...
list_editable: Sequence[str] = ...
search_fields: Sequence[str] = ...
date_hierarchy: Optional[Any] = ...
date_hierarchy: Optional[str] = ...
save_as: bool = ...
save_as_continue: bool = ...
save_on_top: bool = ...
paginator: Any = ...
paginator: Type = ...
preserve_filters: bool = ...
inlines: Sequence[Type[InlineModelAdmin]] = ...
add_form_template: Any = ...
change_form_template: Any = ...
change_list_template: Any = ...
delete_confirmation_template: Any = ...
delete_selected_confirmation_template: Any = ...
object_history_template: Any = ...
popup_response_template: Any = ...
actions: Any = ...
add_form_template: Optional[_TemplateForResponseT] = ...
change_form_template: Optional[_TemplateForResponseT] = ...
change_list_template: Optional[_TemplateForResponseT] = ...
delete_confirmation_template: Optional[_TemplateForResponseT] = ...
delete_selected_confirmation_template: Optional[_TemplateForResponseT] = ...
object_history_template: Optional[_TemplateForResponseT] = ...
popup_response_template: Optional[_TemplateForResponseT] = ...
actions: Optional[Sequence[Union[Callable[[ModelAdmin, HttpRequest, QuerySet], None], str]]] = ...
action_form: Any = ...
actions_on_top: bool = ...
actions_on_bottom: bool = ...
actions_selection_counter: bool = ...
model: Type[Model] = ...
opts: Options = ...
model: Type[_ModelT] = ...
opts: Options[_ModelT] = ...
admin_site: AdminSite = ...
def __init__(self, model: Type[Model], admin_site: Optional[AdminSite]) -> None: ...
def get_inline_instances(self, request: HttpRequest, obj: Optional[Model] = ...) -> List[InlineModelAdmin]: ...
def __init__(self, model: Type[_ModelT], admin_site: AdminSite) -> None: ...
def get_inline_instances(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> List[InlineModelAdmin]: ...
def get_urls(self) -> List[URLPattern]: ...
@property
def urls(self) -> List[URLPattern]: ...
@property
def media(self) -> Media: ...
def get_model_perms(self, request: HttpRequest) -> Dict[str, bool]: ...
def get_form(self, request: Any, obj: Optional[Any] = ..., change: bool = ..., **kwargs: Any): ...
def get_form(
self, request: HttpRequest, obj: Optional[_ModelT] = ..., change: bool = ..., **kwargs: Any
) -> Type[forms.ModelForm[_ModelT]]: ...
def get_changelist(self, request: HttpRequest, **kwargs: Any) -> Type[ChangeList]: ...
def get_changelist_instance(self, request: HttpRequest) -> ChangeList: ...
def get_object(self, request: HttpRequest, object_id: str, from_field: None = ...) -> Optional[Model]: ...
def get_changelist_form(self, request: Any, **kwargs: Any): ...
def get_changelist_formset(self, request: Any, **kwargs: Any): ...
def get_formsets_with_inlines(self, request: HttpRequest, obj: Optional[Model] = ...) -> Iterator[Any]: ...
def get_object(
self, request: HttpRequest, object_id: str, from_field: Optional[str] = ...
) -> Optional[_ModelT]: ...
def get_changelist_form(self, request: HttpRequest, **kwargs: Any) -> Type[ModelForm[_ModelT]]: ...
def get_changelist_formset(
self, request: HttpRequest, **kwargs: Any
) -> Type[BaseModelFormSet[_ModelT, ModelForm[_ModelT]]]: ...
def get_formsets_with_inlines(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Iterator[Any]: ...
def get_paginator(
self,
request: HttpRequest,
@@ -146,28 +210,28 @@ class ModelAdmin(BaseModelAdmin):
orphans: int = ...,
allow_empty_first_page: bool = ...,
) -> Paginator: ...
def log_addition(self, request: HttpRequest, object: Model, message: Any) -> LogEntry: ...
def log_change(self, request: HttpRequest, object: Model, message: Any) -> LogEntry: ...
def log_deletion(self, request: HttpRequest, object: Model, object_repr: str) -> LogEntry: ...
def action_checkbox(self, obj: Model) -> SafeText: ...
def get_actions(self, request: HttpRequest) -> OrderedDict: ...
def log_addition(self, request: HttpRequest, object: _ModelT, message: Any) -> LogEntry: ...
def log_change(self, request: HttpRequest, object: _ModelT, message: Any) -> LogEntry: ...
def log_deletion(self, request: HttpRequest, object: _ModelT, object_repr: str) -> LogEntry: ...
def action_checkbox(self, obj: _ModelT) -> SafeString: ...
def get_actions(self, request: HttpRequest) -> Dict[str, Optional[Tuple[Callable[..., str], str, str]]]: ...
def get_action_choices(
self, request: HttpRequest, default_choices: List[Tuple[str, str]] = ...
) -> List[Tuple[str, str]]: ...
def get_action(self, action: Union[Callable, str]) -> Tuple[Callable, str, str]: ...
def get_list_display(self, request: HttpRequest) -> Sequence[str]: ...
def get_list_display_links(self, request: HttpRequest, list_display: Sequence[str]) -> Optional[Sequence[str]]: ...
def get_list_filter(self, request: HttpRequest) -> Sequence[str]: ...
def get_list_select_related(self, request: HttpRequest) -> Sequence[str]: ...
def get_search_fields(self, request: HttpRequest) -> List[str]: ...
def get_action(self, action: Union[Callable, str]) -> Optional[Tuple[Callable[..., str], str, str]]: ...
def get_list_display(self, request: HttpRequest) -> _DisplayT: ...
def get_list_display_links(self, request: HttpRequest, list_display: _DisplayT) -> _DisplayT: ...
def get_list_filter(self, request: HttpRequest) -> Sequence[_ListFilterT]: ...
def get_list_select_related(self, request: HttpRequest) -> Union[bool, Sequence[str]]: ...
def get_search_fields(self, request: HttpRequest) -> Sequence[str]: ...
def get_search_results(
self, request: HttpRequest, queryset: QuerySet, search_term: str
) -> Tuple[QuerySet, bool]: ...
) -> Tuple[QuerySet[_ModelT], bool]: ...
def get_preserved_filters(self, request: HttpRequest) -> str: ...
def _get_edited_object_pks(self, request: HttpRequest, prefix: str) -> List[str]: ...
def _get_list_editable_queryset(self, request: HttpRequest, prefix: str) -> QuerySet: ...
def _get_list_editable_queryset(self, request: HttpRequest, prefix: str) -> QuerySet[_ModelT]: ...
def construct_change_message(
self, request: HttpRequest, form: AdminPasswordChangeForm, formsets: None, add: bool = ...
self, request: HttpRequest, form: AdminPasswordChangeForm, formsets: Iterable[BaseFormSet], add: bool = ...
) -> List[Dict[str, Dict[str, List[str]]]]: ...
def message_user(
self,
@@ -177,79 +241,96 @@ class ModelAdmin(BaseModelAdmin):
extra_tags: str = ...,
fail_silently: bool = ...,
) -> None: ...
def save_form(self, request: Any, form: Any, change: Any): ...
def save_model(self, request: Any, obj: Any, form: Any, change: Any) -> None: ...
def delete_model(self, request: HttpRequest, obj: Model) -> None: ...
def save_form(self, request: HttpRequest, form: Any, change: Any) -> Any: ...
def save_model(self, request: HttpRequest, obj: _ModelT, form: Any, change: Any) -> None: ...
def delete_model(self, request: HttpRequest, obj: _ModelT) -> None: ...
def delete_queryset(self, request: HttpRequest, queryset: QuerySet) -> None: ...
def save_formset(self, request: Any, form: Any, formset: Any, change: Any) -> None: ...
def save_related(self, request: Any, form: Any, formsets: Any, change: Any) -> None: ...
def save_formset(self, request: HttpRequest, form: Any, formset: Any, change: Any) -> None: ...
def save_related(self, request: HttpRequest, form: Any, formsets: Any, change: Any) -> None: ...
def render_change_form(
self,
request: Any,
context: Any,
request: HttpRequest,
context: Dict[str, Any],
add: bool = ...,
change: bool = ...,
form_url: str = ...,
obj: Optional[Any] = ...,
): ...
def response_add(
self, request: HttpRequest, obj: Model, post_url_continue: Optional[str] = ...
obj: Optional[_ModelT] = ...,
) -> HttpResponse: ...
def response_change(self, request: HttpRequest, obj: Model) -> HttpResponse: ...
def response_post_save_add(self, request: HttpRequest, obj: Model) -> HttpResponseRedirect: ...
def response_post_save_change(self, request: HttpRequest, obj: Model) -> HttpResponseRedirect: ...
def response_action(self, request: HttpRequest, queryset: QuerySet) -> Optional[HttpResponseBase]: ...
def response_add(
self, request: HttpRequest, obj: _ModelT, post_url_continue: Optional[str] = ...
) -> HttpResponse: ...
def response_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponse: ...
def response_post_save_add(self, request: HttpRequest, obj: _ModelT) -> HttpResponseRedirect: ...
def response_post_save_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponseRedirect: ...
# Probably FileResponse cannot come from ModelAdmin views
def response_action(self, request: HttpRequest, queryset: QuerySet) -> Optional[HttpResponse]: ...
def response_delete(self, request: HttpRequest, obj_display: str, obj_id: int) -> HttpResponse: ...
def render_delete_form(self, request: Any, context: Any): ...
def render_delete_form(self, request: HttpRequest, context: Dict[str, Any]) -> HttpResponse: ...
def get_inline_formsets(
self, request: HttpRequest, formsets: List[Any], inline_instances: List[Any], obj: Optional[Model] = ...
self, request: HttpRequest, formsets: List[Any], inline_instances: List[Any], obj: Optional[_ModelT] = ...
) -> List[Any]: ...
def get_changeform_initial_data(self, request: HttpRequest) -> Dict[str, str]: ...
def get_changeform_initial_data(self, request: HttpRequest) -> Dict[str, Union[str, List[str]]]: ...
def changeform_view(
self,
request: HttpRequest,
object_id: Optional[str] = ...,
form_url: str = ...,
extra_context: Optional[Dict[str, bool]] = ...,
) -> Any: ...
def autocomplete_view(self, request: HttpRequest) -> JsonResponse: ...
def add_view(self, request: HttpRequest, form_url: str = ..., extra_context: None = ...) -> HttpResponse: ...
def change_view(
self, request: HttpRequest, object_id: str, form_url: str = ..., extra_context: Optional[Dict[str, bool]] = ...
extra_context: Optional[Dict[str, Any]] = ...,
) -> HttpResponse: ...
def changelist_view(
self, request: HttpRequest, extra_context: Optional[Dict[str, str]] = ...
) -> TemplateResponse: ...
def add_view(
self, request: HttpRequest, form_url: str = ..., extra_context: Optional[Dict[str, Any]] = ...
) -> HttpResponse: ...
def change_view(
self, request: HttpRequest, object_id: str, form_url: str = ..., extra_context: Optional[Dict[str, Any]] = ...
) -> HttpResponse: ...
def changelist_view(self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...) -> HttpResponse: ...
def get_deleted_objects(
self, objs: QuerySet, request: HttpRequest
) -> Tuple[List[Any], Dict[Any, Any], Set[Any], List[Any]]: ...
def delete_view(self, request: HttpRequest, object_id: str, extra_context: None = ...) -> Any: ...
def history_view(self, request: HttpRequest, object_id: str, extra_context: None = ...) -> HttpResponse: ...
self, objs: Union[Sequence[_ModelT], QuerySet[_ModelT]], request: HttpRequest
) -> Tuple[List[Model], Dict[str, int], Set[str], List[str]]: ...
def delete_view(
self, request: HttpRequest, object_id: str, extra_context: Optional[Dict[str, Any]] = ...
) -> HttpResponse: ...
def history_view(
self, request: HttpRequest, object_id: str, extra_context: Optional[Dict[str, Any]] = ...
) -> HttpResponse: ...
class InlineModelAdmin(BaseModelAdmin):
model: Any = ...
fk_name: Any = ...
formset: Any = ...
_ChildModelT = TypeVar("_ChildModelT", bound=Model)
_ParentModelT = TypeVar("_ParentModelT", bound=Model)
class InlineModelAdmin(Generic[_ChildModelT, _ParentModelT], BaseModelAdmin[_ChildModelT]):
model: Type[_ChildModelT] = ...
fk_name: Optional[str] = ...
formset: Type[BaseInlineFormSet[_ChildModelT, _ParentModelT, forms.ModelForm[_ChildModelT]]] = ...
extra: int = ...
min_num: Optional[int] = ...
max_num: Optional[int] = ...
template: str = ...
verbose_name: Optional[str] = ...
verbose_name_plural: Optional[str] = ...
verbose_name: Optional[_StrOrPromise] = ...
verbose_name_plural: Optional[_StrOrPromise] = ...
can_delete: bool = ...
show_change_link: bool = ...
classes: Any = ...
admin_site: Any = ...
parent_model: Any = ...
opts: Any = ...
has_registered_model: Any = ...
def __init__(self, parent_model: Union[Type[Model], Model], admin_site: AdminSite) -> None: ...
classes: Optional[Sequence[str]] = ...
admin_site: AdminSite = ...
parent_model: Type[_ParentModelT] = ...
opts: Options[_ChildModelT] = ...
has_registered_model: bool = ...
def __init__(self, parent_model: Type[_ParentModelT], admin_site: AdminSite) -> None: ...
@property
def media(self) -> Media: ...
def get_extra(self, request: HttpRequest, obj: Optional[Model] = ..., **kwargs: Any) -> int: ...
def get_min_num(self, request: HttpRequest, obj: Optional[Model] = ..., **kwargs: Any) -> Optional[int]: ...
def get_max_num(self, request: HttpRequest, obj: Optional[Model] = ..., **kwargs: Any) -> Optional[int]: ...
def get_formset(self, request: Any, obj: Optional[Any] = ..., **kwargs: Any): ...
def get_extra(self, request: HttpRequest, obj: Optional[_ParentModelT] = ..., **kwargs: Any) -> int: ...
def get_min_num(self, request: HttpRequest, obj: Optional[_ParentModelT] = ..., **kwargs: Any) -> Optional[int]: ...
def get_max_num(self, request: HttpRequest, obj: Optional[_ParentModelT] = ..., **kwargs: Any) -> Optional[int]: ...
def get_formset(
self, request: HttpRequest, obj: Optional[_ParentModelT] = ..., **kwargs: Any
) -> Type[BaseInlineFormSet[_ChildModelT, _ParentModelT, forms.ModelForm[_ChildModelT]]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet[_ChildModelT]: ...
def has_add_permission(self, request: HttpRequest, obj: Optional[_ParentModelT]) -> bool: ... # type: ignore
def has_change_permission(self, request: HttpRequest, obj: Optional[_ParentModelT] = ...) -> bool: ... # type: ignore
def has_delete_permission(self, request: HttpRequest, obj: Optional[_ParentModelT] = ...) -> bool: ... # type: ignore
def has_view_permission(self, request: HttpRequest, obj: Optional[_ParentModelT] = ...) -> bool: ... # type: ignore
class StackedInline(InlineModelAdmin): ...
class TabularInline(InlineModelAdmin): ...
class StackedInline(InlineModelAdmin[_ChildModelT, _ParentModelT]):
template: str = ...
class TabularInline(InlineModelAdmin[_ChildModelT, _ParentModelT]):
template: str = ...

View File

@@ -1,36 +1,54 @@
import sys
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from django.apps.config import AppConfig
from django.contrib.admin.options import ModelAdmin
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.forms import AuthenticationForm
from django.core.checks import CheckMessage
from django.db.models.base import Model
from django.db.models.query import QuerySet
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from django.urls.resolvers import URLResolver
from django.utils.functional import LazyObject
from django.urls import URLPattern, URLResolver
from django.utils.functional import LazyObject, _StrOrPromise
from django.apps.config import AppConfig
if sys.version_info >= (3, 9):
from weakref import WeakSet
all_sites: Any
all_sites: WeakSet[AdminSite]
else:
from typing import MutableSet
all_sites: MutableSet[AdminSite]
_ActionCallback = Callable[[ModelAdmin, HttpRequest, QuerySet], Optional[TemplateResponse]]
class AlreadyRegistered(Exception): ...
class NotRegistered(Exception): ...
class AdminSite:
site_title: Any = ...
site_header: Any = ...
index_title: Any = ...
site_title: str = ...
site_header: str = ...
index_title: str = ...
site_url: str = ...
login_form: Any = ...
index_template: Any = ...
app_index_template: Any = ...
login_template: Any = ...
logout_template: Any = ...
password_change_template: Any = ...
password_change_done_template: Any = ...
login_form: Optional[Type[AuthenticationForm]] = ...
index_template: Optional[str] = ...
app_index_template: Optional[str] = ...
login_template: Optional[str] = ...
logout_template: Optional[str] = ...
password_change_template: Optional[str] = ...
password_change_done_template: Optional[str] = ...
name: str = ...
enable_nav_sidebar: bool = ...
empty_value_display: str = ...
final_catch_all_view: bool = ...
_empty_value_display: str = ...
_registry: Dict[Type[Model], ModelAdmin]
_global_actions: Dict[str, _ActionCallback]
_actions: Dict[str, _ActionCallback]
def __init__(self, name: str = ...) -> None: ...
def check(self, app_configs: Optional[Iterable[AppConfig]]) -> List[Any]: ...
def check(self, app_configs: Optional[Iterable[AppConfig]]) -> List[CheckMessage]: ...
def register(
self,
model_or_iterable: Union[Type[Model], Iterable[Type[Model]]],
@@ -39,36 +57,35 @@ class AdminSite:
) -> None: ...
def unregister(self, model_or_iterable: Union[Type[Model], Iterable[Type[Model]]]) -> None: ...
def is_registered(self, model: Type[Model]) -> bool: ...
def add_action(self, action: Callable, name: Optional[str] = ...) -> None: ...
def add_action(self, action: _ActionCallback, name: Optional[str] = ...) -> None: ...
def disable_action(self, name: str) -> None: ...
def get_action(self, name: str) -> Callable: ...
@property
def actions(self): ...
@property
def empty_value_display(self): ...
@empty_value_display.setter
def empty_value_display(self, empty_value_display: Any) -> None: ...
def has_permission(self, request: WSGIRequest) -> bool: ...
def actions(self) -> Iterable[Tuple[str, _ActionCallback]]: ...
def has_permission(self, request: HttpRequest) -> bool: ...
def admin_view(self, view: Callable, cacheable: bool = ...) -> Callable: ...
def get_urls(self) -> List[URLResolver]: ...
def get_urls(self) -> List[Union[URLResolver, URLPattern]]: ...
@property
def urls(self) -> Tuple[List[URLResolver], str, str]: ...
def each_context(self, request: Any): ...
def urls(self) -> Tuple[List[Union[URLResolver, URLPattern]], str, str]: ...
def each_context(self, request: HttpRequest) -> Dict[str, Any]: ...
def password_change(
self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...
self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
def password_change_done(
self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...
self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
def i18n_javascript(self, request: WSGIRequest, extra_context: Optional[Dict[Any, Any]] = ...) -> HttpResponse: ...
def logout(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def login(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> HttpResponse: ...
def get_app_list(self, request: WSGIRequest) -> List[Any]: ...
def index(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def i18n_javascript(self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...) -> HttpResponse: ...
def logout(self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def login(self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...) -> HttpResponse: ...
def _build_app_dict(self, request: HttpRequest, label: Optional[_StrOrPromise] = ...) -> Dict[str, Any]: ...
def get_app_list(self, request: HttpRequest) -> List[Any]: ...
def index(self, request: HttpRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def app_index(
self, request: WSGIRequest, app_label: str, extra_context: Optional[Dict[str, Any]] = ...
self, request: HttpRequest, app_label: str, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
def autocomplete_view(self, request: HttpRequest) -> HttpResponse: ...
def catch_all_view(self, request: HttpRequest, url: str) -> HttpResponse: ...
class DefaultAdminSite(LazyObject): ...
site: Any
site: AdminSite

View File

@@ -1,28 +1,29 @@
from typing import Any, Dict, Iterator, List, Optional, Union, Iterable
from typing import Any, Dict, Iterable, Iterator, List, Optional, Union
from django.contrib.admin.filters import FieldListFilter
from django.contrib.admin.templatetags.base import InclusionAdminNode
from django.contrib.admin.views.main import ChangeList
from django.db.models.base import Model
from django.forms.boundfield import BoundField
from django.forms.models import ModelForm
from django.template.base import Parser, Token
from django.template.context import RequestContext
from django.utils.safestring import SafeText
from django.utils.safestring import SafeString
from .base import InclusionAdminNode
register: Any
DOT: str
def paginator_number(cl: ChangeList, i: int) -> SafeText: ...
def pagination(cl: ChangeList) -> Dict[str, Iterable[Any]]: ...
def paginator_number(cl: ChangeList, i: int) -> SafeString: ...
def pagination(cl: ChangeList) -> Dict[str, Any]: ...
def pagination_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def result_headers(cl: ChangeList) -> Iterator[Dict[str, Optional[Union[int, str]]]]: ...
def items_for_result(cl: ChangeList, result: Model, form: None) -> Iterator[SafeText]: ...
def items_for_result(cl: ChangeList, result: Model, form: Optional[ModelForm]) -> Iterator[SafeString]: ...
class ResultList(list):
form: None = ...
def __init__(self, form: None, *items: Any) -> None: ...
form: Optional[ModelForm] = ...
def __init__(self, form: Optional[ModelForm], *items: Any) -> None: ...
def results(cl: ChangeList) -> Iterator[ResultList]: ...
def result_hidden_fields(cl: ChangeList) -> Iterator[BoundField]: ...
@@ -36,7 +37,7 @@ def date_hierarchy(cl: ChangeList) -> Optional[Dict[str, Any]]: ...
def date_hierarchy_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def search_form(cl: ChangeList) -> Dict[str, Union[bool, ChangeList, str]]: ...
def search_form_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def admin_list_filter(cl: ChangeList, spec: FieldListFilter) -> SafeText: ...
def admin_list_filter(cl: ChangeList, spec: FieldListFilter) -> SafeString: ...
def admin_actions(context: RequestContext) -> RequestContext: ...
def admin_actions_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def change_list_object_tools_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...

View File

@@ -1,5 +0,0 @@
from typing import Any
register: Any
def static(path: str) -> str: ...

View File

@@ -3,11 +3,11 @@ from uuid import UUID
from django.db.models.options import Options
from django.template.context import RequestContext
from django.utils.safestring import SafeText
from django.utils.safestring import SafeString
register: Any
def admin_urlname(value: Options, arg: SafeText) -> str: ...
def admin_urlname(value: Options, arg: SafeString) -> str: ...
def admin_urlquote(value: Union[int, str, UUID]) -> Union[int, str, UUID]: ...
def add_preserved_filters(
context: Union[Dict[str, Union[Options, str]], RequestContext],

View File

@@ -3,15 +3,15 @@ from typing import Any, Callable, Dict, List
from django.template.base import Parser, Token
from django.template.context import Context
from django.template.library import InclusionNode
from django.utils.safestring import SafeText
from django.utils.safestring import SafeString
class InclusionAdminNode(InclusionNode):
args: List[Any]
func: Callable
kwargs: Dict[Any, Any]
kwargs: Dict[str, Any]
takes_context: bool
template_name: str = ...
def __init__(
self, parser: Parser, token: Token, func: Callable, template_name: str, takes_context: bool = ...
) -> None: ...
def render(self, context: Context) -> SafeText: ...
def render(self, context: Context) -> SafeString: ...

View File

@@ -1,4 +1,5 @@
from typing import Any, Callable
from contextlib import contextmanager
from typing import Any, Callable, Generator
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.selenium import SeleniumTestCase
@@ -8,16 +9,18 @@ class CSPMiddleware(MiddlewareMixin): ...
class AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):
def wait_until(self, callback: Callable, timeout: int = ...) -> None: ...
def wait_for_popup(self, num_windows: int = ..., timeout: int = ...) -> None: ...
def wait_for_and_switch_to_popup(self, num_windows: int = ..., timeout: int = ...) -> None: ...
def wait_for(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_for_text(self, css_selector: str, text: str, timeout: int = ...) -> None: ...
def wait_for_value(self, css_selector: str, text: str, timeout: int = ...) -> None: ...
def wait_until_visible(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_until_invisible(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_page_loaded(self) -> None: ...
def wait_page_ready(self, timeout: int = ...) -> None: ...
@contextmanager
def wait_page_loaded(self, timeout: int = ...) -> Generator[None, None, None]: ...
def admin_login(self, username: str, password: str, login_url: str = ...) -> None: ...
def get_css_value(self, selector: str, attribute: str) -> Any: ...
def get_select_option(self, selector: str, value: Any) -> Any: ...
def select_option(self, selector: str, value: Any) -> None: ...
def deselect_option(self, selector: str, value: Any) -> None: ...
def assertSelectOptions(self, selector: str, values: Any) -> None: ...
def assertSelectedOptions(self, selector: str, values: Any) -> None: ...
def has_css_class(self, selector: str, klass: str) -> bool: ...

View File

@@ -1,35 +1,35 @@
import collections
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, Union
import datetime
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type, Union, overload
from uuid import UUID
from django.contrib.admin.options import BaseModelAdmin
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.db.models.deletion import Collector
from django.db.models.fields.reverse_related import ManyToOneRel
from django.db.models.fields import Field, reverse_related
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.forms import BaseForm
from django.db.models.fields import Field, reverse_related
from django.forms.formsets import BaseFormSet
from django.http.request import HttpRequest
from django.utils.datastructures import _IndexableCollection
from typing_extensions import Literal, TypedDict
class FieldIsAForeignKeyColumnName(Exception): ...
def lookup_needs_distinct(opts: Options, lookup_path: str) -> bool: ...
def prepare_lookup_value(key: str, value: Union[datetime, str]) -> Union[bool, datetime, str]: ...
def prepare_lookup_value(key: str, value: Union[datetime.datetime, str]) -> Union[bool, datetime.datetime, str]: ...
def quote(s: Union[int, str, UUID]) -> str: ...
def unquote(s: str) -> str: ...
def flatten(fields: Any) -> List[Union[Callable, str]]: ...
def flatten_fieldsets(fieldsets: Any) -> List[Union[Callable, str]]: ...
def get_deleted_objects(
objs: Sequence[Optional[Model]], request: WSGIRequest, admin_site: AdminSite
) -> Tuple[List[Any], Dict[Any, Any], Set[Any], List[Any]]: ...
objs: Union[Sequence[Optional[Model]], QuerySet[Model]], request: HttpRequest, admin_site: AdminSite
) -> Tuple[List[Model], Dict[str, int], Set[str], List[str]]: ...
class NestedObjects(Collector):
data: collections.OrderedDict
data: Dict[str, Any]
dependencies: Dict[Any, Any]
fast_deletes: List[Any]
field_updates: Dict[Any, Any]
@@ -39,21 +39,37 @@ class NestedObjects(Collector):
model_objs: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def add_edge(self, source: Optional[Model], target: Model) -> None: ...
def related_objects(self, related: ManyToOneRel, objs: Sequence[Optional[Model]]) -> QuerySet: ...
def related_objects(
self, related_model: Type[Model], related_fields: Iterable[Field], objs: _IndexableCollection[Model]
) -> QuerySet[Model]: ...
def nested(self, format_callback: Callable = ...) -> List[Any]: ...
def can_fast_delete(self, *args: Any, **kwargs: Any) -> bool: ...
def model_format_dict(obj: Any): ...
class _ModelFormatDict(TypedDict):
verbose_name: str
verbose_name_plural: str
def model_format_dict(obj: Union[Model, Type[Model], QuerySet, Options[Model]]) -> _ModelFormatDict: ...
def model_ngettext(obj: Union[Options, QuerySet], n: Optional[int] = ...) -> str: ...
def lookup_field(
name: Union[Callable, str], obj: Model, model_admin: BaseModelAdmin = ...
) -> Tuple[Optional[Field], Any, Any]: ...
name: Union[Callable, str], obj: Model, model_admin: Optional[BaseModelAdmin] = ...
) -> Tuple[Optional[Field], Optional[str], Any]: ...
@overload
def label_for_field( # type: ignore
name: Union[Callable, str],
model: Type[Model],
model_admin: Optional[BaseModelAdmin] = ...,
return_attr: Literal[True] = ...,
form: Optional[BaseForm] = ...,
) -> Tuple[str, Union[Callable, str, None]]: ...
@overload
def label_for_field(
name: Union[Callable, str],
model: Type[Model],
model_admin: Optional[BaseModelAdmin] = ...,
return_attr: bool = ...,
return_attr: Literal[False] = ...,
form: Optional[BaseForm] = ...,
) -> Union[Tuple[Optional[str], Union[Callable, Type[str]]], str]: ...
) -> str: ...
def help_text_for_field(name: str, model: Type[Model]) -> str: ...
def display_for_field(value: Any, field: Field, empty_value_display: str) -> str: ...
def display_for_value(value: Any, empty_value_display: str, boolean: bool = ...) -> str: ...
@@ -64,5 +80,5 @@ def get_model_from_relation(field: Union[Field, reverse_related.ForeignObjectRel
def reverse_field_path(model: Type[Model], path: str) -> Tuple[Type[Model], str]: ...
def get_fields_from_path(model: Type[Model], path: str) -> List[Field]: ...
def construct_change_message(
form: AdminPasswordChangeForm, formsets: None, add: bool
form: AdminPasswordChangeForm, formsets: Iterable[BaseFormSet], add: bool
) -> List[Dict[str, Dict[str, List[str]]]]: ...

View File

@@ -1,10 +1,11 @@
from typing import Any
from typing import Any, Optional
from django.contrib.admin.options import ModelAdmin
from django.core.handlers.wsgi import WSGIRequest
from django.db.models import Model
from django.http.request import HttpRequest
from django.views.generic.list import BaseListView
class AutocompleteJsonView(BaseListView):
model_admin: ModelAdmin = ...
term: Any = ...
def has_perm(self, request: WSGIRequest, obj: None = ...) -> bool: ...
def has_perm(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...

View File

@@ -1,7 +1,12 @@
from typing import Callable, TypeVar, overload
from typing import Callable, Optional, TypeVar, overload
_C = TypeVar("_C", bound=Callable)
@overload
def staff_member_required(view_func: _C = ..., redirect_field_name: str = ..., login_url: str = ...) -> _C: ...
def staff_member_required(
view_func: _C = ..., redirect_field_name: Optional[str] = ..., login_url: str = ...
) -> _C: ...
@overload
def staff_member_required(view_func: None = ..., redirect_field_name: str = ..., login_url: str = ...) -> Callable: ...
def staff_member_required(
view_func: None = ..., redirect_field_name: Optional[str] = ..., login_url: str = ...
) -> Callable: ...

View File

@@ -1,19 +1,16 @@
from collections import OrderedDict
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type, Union
from django.contrib.admin.filters import ListFilter, SimpleListFilter
from django.contrib.admin.options import ( # noqa: F401
ModelAdmin,
IS_POPUP_VAR as IS_POPUP_VAR,
TO_FIELD_VAR as TO_FIELD_VAR,
)
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.admin.filters import ListFilter
from django.contrib.admin.options import IS_POPUP_VAR as IS_POPUP_VAR # noqa: F401
from django.contrib.admin.options import TO_FIELD_VAR as TO_FIELD_VAR
from django.contrib.admin.options import ModelAdmin, _DisplayT, _ListFilterT
from django.db.models.base import Model
from django.db.models.expressions import Combinable, CombinedExpression, OrderBy
from django.db.models.query import QuerySet
from django.db.models.expressions import Expression
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.formsets import BaseFormSet
from django.http.request import HttpRequest
from typing_extensions import Literal
ALL_VAR: str
ORDER_VAR: str
@@ -21,69 +18,75 @@ ORDER_TYPE_VAR: str
PAGE_VAR: str
SEARCH_VAR: str
ERROR_FLAG: str
IGNORED_PARAMS: Any
IGNORED_PARAMS: Tuple[str, ...]
class ChangeList:
model: Type[Model] = ...
opts: Options = ...
lookup_opts: Options = ...
root_queryset: QuerySet = ...
list_display: List[str] = ...
list_display_links: List[str] = ...
list_filter: Tuple = ...
date_hierarchy: None = ...
search_fields: Tuple = ...
list_select_related: bool = ...
list_display: _DisplayT = ...
list_display_links: _DisplayT = ...
list_filter: Sequence[_ListFilterT] = ...
date_hierarchy: Any = ...
search_fields: Sequence[str] = ...
list_select_related: Union[bool, Sequence[str]] = ...
list_per_page: int = ...
list_max_show_all: int = ...
model_admin: ModelAdmin = ...
preserved_filters: str = ...
sortable_by: Tuple[str] = ...
sortable_by: Optional[Sequence[str]] = ...
page_num: int = ...
show_all: bool = ...
is_popup: bool = ...
to_field: None = ...
params: Dict[Any, Any] = ...
list_editable: Tuple = ...
to_field: Any = ...
params: Dict[str, Any] = ...
list_editable: Sequence[str] = ...
query: str = ...
queryset: Any = ...
title: Any = ...
pk_attname: Any = ...
title: str = ...
pk_attname: str = ...
formset: Optional[BaseFormSet]
def __init__(
self,
request: WSGIRequest,
request: HttpRequest,
model: Type[Model],
list_display: Union[List[Union[Callable, str]], Tuple[str]],
list_display_links: Optional[Union[List[Callable], List[str], Tuple[str]]],
list_filter: Union[List[Type[SimpleListFilter]], List[str], Tuple],
list_display: _DisplayT,
list_display_links: _DisplayT,
list_filter: Sequence[_ListFilterT],
date_hierarchy: Optional[str],
search_fields: Union[List[str], Tuple],
list_select_related: Union[Tuple, bool],
search_fields: Sequence[str],
list_select_related: Union[bool, Sequence[str]],
list_per_page: int,
list_max_show_all: int,
list_editable: Union[List[str], Tuple],
list_editable: Sequence[str],
model_admin: ModelAdmin,
sortable_by: Union[List[Callable], List[str], Tuple],
sortable_by: Optional[Sequence[str]],
) -> None: ...
def get_filters_params(self, params: None = ...) -> Dict[str, str]: ...
def get_filters(self, request: WSGIRequest) -> Tuple[List[ListFilter], bool, Dict[str, Union[bool, str]], bool]: ...
def get_filters_params(self, params: Optional[Dict[str, Any]] = ...) -> Dict[str, Any]: ...
def get_filters(
self, request: HttpRequest
) -> Tuple[List[ListFilter], bool, Dict[str, Union[bool, str]], bool, bool]: ...
def get_query_string(
self, new_params: Optional[Dict[str, None]] = ..., remove: Optional[List[str]] = ...
self, new_params: Optional[Dict[str, Any]] = ..., remove: Optional[Iterable[str]] = ...
) -> str: ...
result_count: Any = ...
show_full_result_count: Any = ...
show_admin_actions: Any = ...
full_result_count: Any = ...
result_count: int = ...
show_full_result_count: bool = ...
show_admin_actions: bool = ...
full_result_count: Optional[int] = ...
result_list: Any = ...
can_show_all: Any = ...
multi_page: Any = ...
can_show_all: bool = ...
multi_page: bool = ...
paginator: Any = ...
def get_results(self, request: WSGIRequest) -> None: ...
def get_ordering_field(self, field_name: Union[Callable, str]) -> Optional[Union[CombinedExpression, str]]: ...
def get_ordering(self, request: WSGIRequest, queryset: QuerySet) -> List[Union[OrderBy, Combinable, str]]: ...
def get_ordering_field_columns(self) -> OrderedDict: ...
def get_queryset(self, request: WSGIRequest) -> QuerySet: ...
def get_results(self, request: HttpRequest) -> None: ...
def get_ordering_field(self, field_name: Union[Callable, str]) -> Optional[Union[Expression, str]]: ...
def get_ordering(self, request: HttpRequest, queryset: QuerySet) -> List[Union[Expression, str]]: ...
def get_ordering_field_columns(self) -> Dict[int, Literal["desc", "asc"]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet: ...
filter_specs: List[ListFilter]
has_filters: bool
has_active_filters: bool
clear_all_filters_qs: str
def apply_select_related(self, qs: QuerySet) -> QuerySet: ...
def has_related_field_in_list_display(self) -> bool: ...
def url_for_result(self, result: Model) -> str: ...

View File

@@ -1,29 +1,36 @@
from typing import Any, Dict, Optional, Tuple, Union
from uuid import UUID
from django.contrib.admin.sites import AdminSite
from django.db.models.fields.reverse_related import ForeignObjectRel, ManyToOneRel
from django.forms.models import ModelChoiceIterator
from django.forms.widgets import Media
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
from django import forms
from django.contrib.admin.sites import AdminSite
from django.core.files.base import File
from django.db.models.fields import _FieldChoices
from django.db.models.fields.reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel
from django.forms.models import ModelChoiceIterator
from django.forms.widgets import Media, _OptAttrs
from django.utils.functional import _StrOrPromise
class FilteredSelectMultiple(forms.SelectMultiple):
@property
def media(self) -> Media: ...
verbose_name: Any = ...
is_stacked: Any = ...
def __init__(self, verbose_name: str, is_stacked: bool, attrs: None = ..., choices: Tuple = ...) -> None: ...
verbose_name: _StrOrPromise = ...
is_stacked: bool = ...
def __init__(
self,
verbose_name: _StrOrPromise,
is_stacked: bool,
attrs: Optional[_OptAttrs] = ...,
choices: _FieldChoices = ...,
) -> None: ...
class AdminDateWidget(forms.DateInput):
@property
def media(self) -> Media: ...
def __init__(self, attrs: Optional[_OptAttrs] = ..., format: Optional[str] = ...) -> None: ...
class AdminTimeWidget(forms.TimeInput):
@property
def media(self) -> Media: ...
def __init__(self, attrs: Optional[_OptAttrs] = ..., format: Optional[str] = ...) -> None: ...
class AdminSplitDateTime(forms.SplitDateTimeWidget):
template_name: str
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
def get_context(self, name: str, value: Any, attrs: Optional[_OptAttrs]) -> Dict[str, Any]: ...
class AdminSplitDateTime(forms.SplitDateTimeWidget): ...
class AdminRadioSelect(forms.RadioSelect): ...
class AdminFileWidget(forms.ClearableFileInput): ...
@@ -32,18 +39,27 @@ def url_params_from_lookup_dict(lookups: Any) -> Dict[str, str]: ...
class ForeignKeyRawIdWidget(forms.TextInput):
rel: ManyToOneRel = ...
admin_site: AdminSite = ...
db: None = ...
def __init__(self, rel: ForeignObjectRel, admin_site: AdminSite, attrs: None = ..., using: None = ...) -> None: ...
db: Optional[str] = ...
def __init__(
self, rel: ManyToOneRel, admin_site: AdminSite, attrs: Optional[_OptAttrs] = ..., using: Optional[str] = ...
) -> None: ...
def base_url_parameters(self) -> Dict[str, str]: ...
def get_context(self, name: str, value: Any, attrs: Optional[_OptAttrs]) -> Dict[str, Any]: ...
def url_parameters(self) -> Dict[str, str]: ...
def label_and_url_for_value(self, value: Union[int, str, UUID]) -> Tuple[str, str]: ...
def label_and_url_for_value(self, value: Any) -> Tuple[str, str]: ...
class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): ...
class ManyToManyRawIdWidget(ForeignKeyRawIdWidget):
rel: ManyToManyRel = ... # type: ignore
def get_context(self, name: str, value: Any, attrs: Optional[_OptAttrs]) -> Dict[str, Any]: ...
def url_parameters(self) -> Dict[str, str]: ...
def label_and_url_for_value(self, value: Any) -> Tuple[str, str]: ...
def format_value(self, value: Any) -> Optional[str]: ...
def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Iterable[File]], name: str) -> Any: ...
class RelatedFieldWidgetWrapper(forms.Widget):
template_name: str = ...
choices: ModelChoiceIterator = ...
widget: forms.Widget = ...
widget: forms.ChoiceWidget = ...
rel: ManyToOneRel = ...
can_add_related: bool = ...
can_change_related: bool = ...
@@ -52,8 +68,8 @@ class RelatedFieldWidgetWrapper(forms.Widget):
admin_site: AdminSite = ...
def __init__(
self,
widget: forms.Widget,
rel: ForeignObjectRel,
widget: forms.ChoiceWidget,
rel: ManyToOneRel,
admin_site: AdminSite,
can_add_related: Optional[bool] = ...,
can_change_related: bool = ...,
@@ -61,42 +77,66 @@ class RelatedFieldWidgetWrapper(forms.Widget):
can_view_related: bool = ...,
) -> None: ...
@property
def media(self) -> Media: ...
def media(self) -> Media: ... # type: ignore
@property
def is_hidden(self) -> bool: ...
def get_related_url(self, info: Tuple[str, str], action: str, *args: Any) -> str: ...
def get_context(self, name: str, value: Any, attrs: Optional[_OptAttrs]) -> Dict[str, Any]: ...
def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Iterable[File]], name: str) -> Any: ...
def value_omitted_from_data(
self, data: Mapping[str, Any], files: Mapping[str, Iterable[File]], name: str
) -> bool: ...
def id_for_label(self, id_: str) -> str: ...
class AdminTextareaWidget(forms.Textarea): ...
class AdminTextInputWidget(forms.TextInput): ...
class AdminEmailInputWidget(forms.EmailInput): ...
class AdminURLFieldWidget(forms.URLInput): ...
class AdminTextareaWidget(forms.Textarea):
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
class AdminTextInputWidget(forms.TextInput):
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
class AdminEmailInputWidget(forms.EmailInput):
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
class AdminURLFieldWidget(forms.URLInput):
template_name: str
def __init__(self, attrs: Optional[_OptAttrs] = ..., validator_class: Any = ...) -> None: ...
def get_context(self, name: str, value: Any, attrs: Optional[_OptAttrs]) -> Dict[str, Any]: ...
class AdminIntegerFieldWidget(forms.NumberInput):
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
class_name: str = ...
class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): ...
class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget):
class_name: str = ...
class AdminUUIDInputWidget(forms.TextInput):
def __init__(self, attrs: Optional[Dict[str, str]] = ...) -> None: ...
def __init__(self, attrs: Optional[_OptAttrs] = ...) -> None: ...
SELECT2_TRANSLATIONS: Any
SELECT2_TRANSLATIONS: Dict[str, str] = ...
class AutocompleteMixin:
url_name: str = ...
rel: Any = ...
admin_site: Any = ...
db: Any = ...
field: Any = ...
admin_site: AdminSite = ...
db: Optional[str] = ...
choices: Any = ...
attrs: Any = ...
attrs: _OptAttrs = ...
def __init__(
self,
rel: ForeignObjectRel,
field: Any,
admin_site: AdminSite,
attrs: Optional[Dict[str, str]] = ...,
choices: Tuple = ...,
using: None = ...,
attrs: Optional[_OptAttrs] = ...,
choices: Any = ...,
using: Optional[str] = ...,
) -> None: ...
def get_url(self) -> str: ...
@property
def media(self) -> Media: ...
def build_attrs(self, base_attrs: _OptAttrs, extra_attrs: Optional[_OptAttrs] = ...) -> Dict[str, Any]: ...
# typo in source: `attr` instead of `attrs`
def optgroups(
self, name: str, value: Sequence[str], attr: Optional[_OptAttrs] = ...
) -> List[Tuple[Optional[str], List[Dict[str, Any]], Optional[int]]]: ...
class AutocompleteSelect(AutocompleteMixin, forms.Select): ...
class AutocompleteSelectMultiple(AutocompleteMixin, forms.SelectMultiple): ...
class AutocompleteSelect(AutocompleteMixin, forms.Select): ... # type: ignore
class AutocompleteSelectMultiple(AutocompleteMixin, forms.SelectMultiple): ... # type: ignore

View File

@@ -0,0 +1,7 @@
from typing import Any
from django.apps import AppConfig as AppConfig
class AdminDocsConfig(AppConfig):
name: str = ...
verbose_name: Any = ...

View File

@@ -1,10 +1,14 @@
from typing import Any, Callable, Dict, Optional, Tuple
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import HttpResponse
from django.http.request import HttpRequest
from django.http.response import HttpResponse, HttpResponseBase
from django.utils.deprecation import MiddlewareMixin
class XViewMiddleware(MiddlewareMixin):
def process_view(
self, request: WSGIRequest, view_func: Callable, view_args: Tuple, view_kwargs: Dict[Any, Any]
self,
request: HttpRequest,
view_func: Callable[..., HttpResponseBase],
view_args: Tuple,
view_kwargs: Dict[Any, Any],
) -> Optional[HttpResponse]: ...

View File

@@ -1,3 +1,5 @@
from typing import Any, List
from typing import List
urlpatterns: List[Any] = ...
from django.urls import _AnyURL
urlpatterns: List[_AnyURL] = ...

View File

@@ -1,24 +1,25 @@
from typing import Any, Callable, Optional
from typing import Any, Callable, Dict, List, Optional, Tuple
from django.utils.safestring import SafeString
docutils_is_available: bool
def get_view_name(view_func: Callable) -> str: ...
def trim_docstring(docstring: Any): ...
def parse_docstring(docstring: Any): ...
def parse_rst(text: Any, default_reference_context: Any, thing_being_parsed: Optional[Any] = ...): ...
def parse_docstring(docstring: str) -> Tuple[str, str, Dict[str, str]]: ...
def parse_rst(text: str, default_reference_context: Any, thing_being_parsed: Optional[Any] = ...) -> SafeString: ...
ROLES: Any
ROLES: Dict[str, str]
def create_reference_role(rolename: Any, urlbase: Any): ...
def create_reference_role(rolename: str, urlbase: str) -> None: ...
def default_reference_role(
name: Any,
rawtext: Any,
text: Any,
name: str,
rawtext: str,
text: str,
lineno: Any,
inliner: Any,
options: Optional[Any] = ...,
content: Optional[Any] = ...,
): ...
) -> Tuple[List[Any], List[Any]]: ...
named_group_matcher: Any
unnamed_group_matcher: Any

View File

@@ -1,6 +1,7 @@
from typing import Any, Optional, Union
from typing import Any, Callable, Iterable, List, Optional, Pattern, Tuple, Union
from django.db.models.fields import Field
from django.urls import _AnyURL
from django.views.generic import TemplateView
MODEL_METHODS_EXCLUDE: Any
@@ -15,7 +16,9 @@ class ModelIndexView(BaseAdminDocsView): ...
class ModelDetailView(BaseAdminDocsView): ...
class TemplateDetailView(BaseAdminDocsView): ...
def get_return_data_type(func_name: Any): ...
def get_return_data_type(func_name: Any) -> str: ...
def get_readable_field_data_type(field: Union[Field, str]) -> str: ...
def extract_views_from_urlpatterns(urlpatterns: Any, base: str = ..., namespace: Optional[Any] = ...): ...
def extract_views_from_urlpatterns(
urlpatterns: Iterable[_AnyURL], base: str = ..., namespace: Optional[str] = ...
) -> List[Tuple[Callable, Pattern[str], Optional[str], Optional[str]]]: ...
def simplify_regex(pattern: str) -> str: ...

View File

@@ -2,17 +2,14 @@ from typing import Any, List, Optional, Type, Union
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.contrib.auth.models import AnonymousUser
from django.db.models.options import Options
from django.http.request import HttpRequest
from django.test.client import Client
from .signals import (
user_logged_in as user_logged_in,
user_logged_out as user_logged_out,
user_login_failed as user_login_failed,
)
from .signals import user_logged_in as user_logged_in
from .signals import user_logged_out as user_logged_out
from .signals import user_login_failed as user_login_failed
SESSION_KEY: str
BACKEND_SESSION_KEY: str
@@ -21,14 +18,14 @@ REDIRECT_FIELD_NAME: str
def load_backend(path: str) -> ModelBackend: ...
def get_backends() -> List[ModelBackend]: ...
def authenticate(request: Any = ..., **credentials: Any) -> Optional[AbstractBaseUser]: ...
def authenticate(request: Optional[HttpRequest] = ..., **credentials: Any) -> Optional[AbstractBaseUser]: ...
def login(
request: HttpRequest, user: AbstractBaseUser, backend: Optional[Union[Type[ModelBackend], str]] = ...
request: HttpRequest, user: Optional[AbstractBaseUser], backend: Optional[Union[Type[ModelBackend], str]] = ...
) -> None: ...
def logout(request: HttpRequest) -> None: ...
def get_user_model() -> Type[Model]: ...
def get_user(request: HttpRequest) -> Union[AbstractBaseUser, AnonymousUser]: ...
def get_user_model() -> Type[AbstractBaseUser]: ...
def get_user(request: Union[HttpRequest, Client]) -> Union[AbstractBaseUser, AnonymousUser]: ...
def get_permission_codename(action: str, opts: Options) -> str: ...
def update_session_auth_hash(request: WSGIRequest, user: AbstractUser) -> None: ...
def update_session_auth_hash(request: HttpRequest, user: AbstractBaseUser) -> None: ...
default_app_config: str

View File

@@ -1,9 +1,8 @@
from typing import Any
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import HttpResponse
from django.contrib import admin
from django.http.request import HttpRequest
from django.http.response import HttpResponse
csrf_protect_m: Any
sensitive_post_parameters_m: Any
@@ -15,4 +14,4 @@ class UserAdmin(admin.ModelAdmin):
add_fieldsets: Any = ...
add_form: Any = ...
change_password_form: Any = ...
def user_change_password(self, request: WSGIRequest, id: str, form_url: str = ...) -> HttpResponse: ...
def user_change_password(self, request: HttpRequest, id: str, form_url: str = ...) -> HttpResponse: ...

View File

@@ -1,18 +1,17 @@
from typing import Any, Optional, Set, Union
from typing import Any, Optional, Set, TypeVar, Union
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser, User, Permission
from django.contrib.auth.models import AnonymousUser, Permission
from django.db.models import QuerySet
from django.db.models.base import Model
from django.http.request import HttpRequest
_AnyUser = Union[Model, AnonymousUser]
_AnyUser = Union[AbstractBaseUser, AnonymousUser]
UserModel: Any
class BaseBackend:
def authenticate(
self, request: Any, username: Optional[str] = ..., password: Optional[str] = ..., **kwargs: Any
) -> Optional[AbstractBaseUser]: ...
def authenticate(self, request: Optional[HttpRequest], **kwargs: Any) -> Optional[AbstractBaseUser]: ...
def get_user(self, user_id: int) -> Optional[AbstractBaseUser]: ...
def get_user_permissions(self, user_obj: _AnyUser, obj: Optional[Model] = ...) -> Set[str]: ...
def get_group_permissions(self, user_obj: _AnyUser, obj: Optional[Model] = ...) -> Set[str]: ...
@@ -20,6 +19,13 @@ class BaseBackend:
def has_perm(self, user_obj: _AnyUser, perm: str, obj: Optional[Model] = ...) -> bool: ...
class ModelBackend(BaseBackend):
def authenticate(
self,
request: Optional[HttpRequest],
username: Optional[str] = ...,
password: Optional[str] = ...,
**kwargs: Any
) -> Optional[AbstractBaseUser]: ...
def has_module_perms(self, user_obj: _AnyUser, app_label: str) -> bool: ...
def user_can_authenticate(self, user: Optional[_AnyUser]) -> bool: ...
def with_perm(
@@ -28,13 +34,15 @@ class ModelBackend(BaseBackend):
is_active: bool = ...,
include_superusers: bool = ...,
obj: Optional[Model] = ...,
): ...
) -> QuerySet[AbstractBaseUser]: ...
class AllowAllUsersModelBackend(ModelBackend): ...
_U = TypeVar("_U", bound=AbstractBaseUser)
class RemoteUserBackend(ModelBackend):
create_unknown_user: bool = ...
def clean_username(self, username: str) -> str: ...
def configure_user(self, user: User) -> User: ...
def configure_user(self, request: HttpRequest, user: _U) -> _U: ...
class AllowAllUsersRemoteUserBackend(RemoteUserBackend): ...

View File

@@ -1,8 +1,10 @@
from typing import Any, Optional, Tuple, List, overload, TypeVar
from django.db.models.base import Model
from typing import Any, List, Optional, Tuple, TypeVar, Union, overload
from django.db import models
from django.db.models.base import Model
from django.db.models.expressions import Combinable
from django.db.models.fields import BooleanField
from typing_extensions import Literal
_T = TypeVar("_T", bound=Model)
@@ -17,12 +19,13 @@ class AbstractBaseUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_active: Union[bool, BooleanField[Union[bool, Combinable], bool]] = ...
def get_username(self) -> str: ...
def natural_key(self) -> Tuple[str]: ...
@property
def is_anonymous(self) -> bool: ...
def is_anonymous(self) -> Literal[False]: ...
@property
def is_authenticated(self) -> bool: ...
def is_authenticated(self) -> Literal[True]: ...
def set_password(self, raw_password: Optional[str]) -> None: ...
def check_password(self, raw_password: str) -> bool: ...
def set_unusable_password(self) -> None: ...

View File

@@ -1,8 +1,9 @@
from typing import Any, List, Iterable, Optional
from django.core.checks.messages import CheckMessage
from typing import Any, Optional, Sequence
from django.apps.config import AppConfig
from django.core.checks.messages import CheckMessage
def check_user_model(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[CheckMessage]: ...
def check_models_permissions(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...
def check_user_model(app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any) -> Sequence[CheckMessage]: ...
def check_models_permissions(
app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any
) -> Sequence[CheckMessage]: ...

View File

@@ -1,13 +1,22 @@
from typing import Callable, List, Optional, Set, Union
from typing import Callable, Iterable, Optional, TypeVar, Union, overload
from django.contrib.auth import REDIRECT_FIELD_NAME as REDIRECT_FIELD_NAME # noqa: F401
from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
from django.http.response import HttpResponseBase
_VIEW = TypeVar("_VIEW", bound=Callable[..., HttpResponseBase])
def user_passes_test(
test_func: Callable, login_url: Optional[str] = ..., redirect_field_name: str = ...
) -> Callable: ...
def login_required(
function: Optional[Callable] = ..., redirect_field_name: str = ..., login_url: Optional[str] = ...
) -> Callable: ...
test_func: Callable[[Union[AbstractBaseUser, AnonymousUser]], bool],
login_url: Optional[str] = ...,
redirect_field_name: str = ...,
) -> Callable[[_VIEW], _VIEW]: ...
# There are two ways of calling @login_required: @with(arguments) and @bare
@overload
def login_required(redirect_field_name: str = ..., login_url: Optional[str] = ...) -> Callable[[_VIEW], _VIEW]: ...
@overload
def login_required(function: _VIEW, redirect_field_name: str = ..., login_url: Optional[str] = ...) -> _VIEW: ...
def permission_required(
perm: Union[List[str], Set[str], str], login_url: None = ..., raise_exception: bool = ...
) -> Callable: ...
perm: Union[Iterable[str], str], login_url: Optional[str] = ..., raise_exception: bool = ...
) -> Callable[[_VIEW], _VIEW]: ...

View File

@@ -1,49 +1,58 @@
from typing import Any, Dict, Iterator, Optional
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AbstractUser, User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar, Union
from django import forms
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields import _ErrorMessagesT
from django.forms.fields import _ClassLevelWidgetT
from django.forms.widgets import Widget
from django.http.request import HttpRequest
UserModel: Any
UserModel: Type[AbstractBaseUser]
_User = TypeVar("_User", bound=AbstractBaseUser)
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name: str = ...
read_only: bool = ...
def get_context(self, name: str, value: Any, attrs: Optional[Dict[str, Any]]) -> Dict[str, Any]: ...
class ReadOnlyPasswordHashField(forms.Field):
widget: _ClassLevelWidgetT = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
class UsernameField(forms.CharField): ...
class UsernameField(forms.CharField):
def to_python(self, value: Optional[Any]) -> Optional[Any]: ...
def widget_attrs(self, widget: Widget) -> Dict[str, Any]: ...
class UserCreationForm(forms.ModelForm):
error_messages: Any = ...
password1: Any = ...
password2: Any = ...
class UserCreationForm(forms.ModelForm[_User]):
error_messages: _ErrorMessagesT = ...
password1: forms.Field = ...
password2: forms.Field = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def clean_password2(self) -> str: ...
def save(self, commit: bool = ...) -> _User: ...
class UserChangeForm(forms.ModelForm):
password: Any = ...
class UserChangeForm(forms.ModelForm[_User]):
password: forms.Field = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def clean_password(self) -> str: ...
class AuthenticationForm(forms.Form):
username: Any = ...
password: Any = ...
error_messages: Any = ...
request: WSGIRequest = ...
user_cache: None = ...
username_field: Any = ...
def __init__(self, request: Any = ..., *args: Any, **kwargs: Any) -> None: ...
username: forms.Field = ...
password: forms.Field = ...
error_messages: _ErrorMessagesT = ...
request: Optional[HttpRequest] = ...
user_cache: Any = ...
username_field: models.Field = ...
def __init__(self, request: Optional[HttpRequest] = ..., *args: Any, **kwargs: Any) -> None: ...
def confirm_login_allowed(self, user: AbstractBaseUser) -> None: ...
def get_user(self) -> User: ...
def get_user(self) -> AbstractBaseUser: ...
def get_invalid_login_error(self) -> ValidationError: ...
def clean(self) -> Dict[str, Any]: ...
class PasswordResetForm(forms.Form):
email: Any = ...
email: forms.Field = ...
def send_mail(
self,
subject_template_name: str,
@@ -53,7 +62,7 @@ class PasswordResetForm(forms.Form):
to_email: str,
html_email_template_name: Optional[str] = ...,
) -> None: ...
def get_users(self, email: str) -> Iterator[Any]: ...
def get_users(self, email: str) -> Iterable[AbstractBaseUser]: ...
def save(
self,
domain_override: Optional[str] = ...,
@@ -62,30 +71,33 @@ class PasswordResetForm(forms.Form):
use_https: bool = ...,
token_generator: PasswordResetTokenGenerator = ...,
from_email: Optional[str] = ...,
request: Optional[WSGIRequest] = ...,
request: Optional[HttpRequest] = ...,
html_email_template_name: Optional[str] = ...,
extra_email_context: Optional[Dict[str, str]] = ...,
) -> None: ...
class SetPasswordForm(forms.Form):
error_messages: Any = ...
new_password1: Any = ...
new_password2: Any = ...
user: User = ...
def __init__(self, user: Optional[AbstractBaseUser], *args: Any, **kwargs: Any) -> None: ...
error_messages: _ErrorMessagesT = ...
new_password1: forms.Field = ...
new_password2: forms.Field = ...
user: AbstractBaseUser = ...
def __init__(self, user: AbstractBaseUser, *args: Any, **kwargs: Any) -> None: ...
def clean_new_password2(self) -> str: ...
def save(self, commit: bool = ...) -> AbstractBaseUser: ...
class PasswordChangeForm(SetPasswordForm):
old_password: Any = ...
error_messages: _ErrorMessagesT = ...
old_password: forms.Field = ...
def clean_old_password(self) -> str: ...
class AdminPasswordChangeForm(forms.Form):
error_messages: Any = ...
error_messages: _ErrorMessagesT = ...
required_css_class: str = ...
password1: Any = ...
password2: Any = ...
user: User = ...
def __init__(self, user: AbstractUser, *args: Any, **kwargs: Any) -> None: ...
password1: forms.Field = ...
password2: forms.Field = ...
user: AbstractBaseUser = ...
def __init__(self, user: AbstractBaseUser, *args: Any, **kwargs: Any) -> None: ...
def clean_password2(self) -> str: ...
def save(self, commit: bool = ...) -> AbstractUser: ...
def save(self, commit: bool = ...) -> AbstractBaseUser: ...
@property
def changed_data(self) -> List[str]: ...

View File

@@ -1,4 +1,4 @@
from typing import Any, Callable, Dict, List, Optional
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
UNUSABLE_PASSWORD_PREFIX: str
UNUSABLE_PASSWORD_SUFFIX_LENGTH: int
@@ -7,17 +7,19 @@ def is_password_usable(encoded: Optional[str]) -> bool: ...
def check_password(
password: Optional[str], encoded: str, setter: Optional[Callable] = ..., preferred: str = ...
) -> bool: ...
def make_password(password: Optional[str], salt: Optional[str] = ..., hasher: str = ...) -> str: ...
def make_password(
password: Optional[str], salt: Optional[str] = ..., hasher: Union[str, BasePasswordHasher] = ...
) -> str: ...
def get_hashers() -> List[BasePasswordHasher]: ...
def get_hashers_by_algorithm() -> Dict[str, BasePasswordHasher]: ...
def reset_hashers(**kwargs: Any) -> None: ...
def get_hasher(algorithm: str = ...) -> BasePasswordHasher: ...
def get_hasher(algorithm: Union[str, BasePasswordHasher] = ...) -> BasePasswordHasher: ...
def identify_hasher(encoded: str) -> BasePasswordHasher: ...
def mask_hash(hash: str, show: int = ..., char: str = ...) -> str: ...
class BasePasswordHasher:
algorithm: str = ...
library: str = ...
library: Union[str, Tuple[str, str]] = ...
rounds: int = ...
time_cost: int = ...
memory_cost: int = ...

View File

@@ -12,4 +12,4 @@ def create_permissions(
**kwargs: Any
) -> None: ...
def get_system_username() -> str: ...
def get_default_username(check_db: bool = ...) -> str: ...
def get_default_username(check_db: bool = ..., database: str = ...) -> str: ...

View File

@@ -1,11 +1,11 @@
from typing import Union
from django.contrib.auth.models import AnonymousUser, User
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser
from django.http.request import HttpRequest
from django.utils.deprecation import MiddlewareMixin
def get_user(request: WSGIRequest) -> Union[AnonymousUser, User]: ...
def get_user(request: HttpRequest) -> Union[AnonymousUser, AbstractBaseUser]: ...
class AuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request: HttpRequest) -> None: ...

View File

@@ -1,7 +1,7 @@
from typing import Any, Callable, List, Optional
from typing import Any, Callable, Optional, Sequence
from django import http
from django.http.response import HttpResponse, HttpResponseRedirect
from django.http.response import HttpResponseBase, HttpResponseRedirect
class AccessMixin:
login_url: Any = ...
@@ -14,15 +14,15 @@ class AccessMixin:
def handle_no_permission(self) -> HttpResponseRedirect: ...
class LoginRequiredMixin(AccessMixin):
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ...
class PermissionRequiredMixin(AccessMixin):
permission_required: Any = ...
def get_permission_required(self) -> List[str]: ...
def get_permission_required(self) -> Sequence[str]: ...
def has_permission(self) -> bool: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ...
class UserPassesTestMixin(AccessMixin):
def test_func(self) -> Optional[bool]: ...
def get_test_func(self) -> Callable: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ...

View File

@@ -1,13 +1,14 @@
from typing import Any, Collection, Optional, Set, Tuple, Type, TypeVar, Union
from typing import Any, Iterable, Optional, Set, Tuple, Type, TypeVar, Union
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.base_user import AbstractBaseUser as AbstractBaseUser, BaseUserManager as BaseUserManager
from django.contrib.auth.base_user import AbstractBaseUser as AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager as BaseUserManager
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import QuerySet
from django.db.models.base import Model
from django.db.models.manager import EmptyManager
from django.db import models
from typing_extensions import Literal
_AnyUser = Union[Model, "AnonymousUser"]
@@ -33,7 +34,7 @@ class Group(models.Model):
name = models.CharField(max_length=150)
permissions = models.ManyToManyField(Permission)
def natural_key(self): ...
def natural_key(self) -> Tuple[str]: ...
_T = TypeVar("_T", bound=Model)
@@ -42,16 +43,16 @@ class UserManager(BaseUserManager[_T]):
self, username: str, email: Optional[str] = ..., password: Optional[str] = ..., **extra_fields: Any
) -> _T: ...
def create_superuser(
self, username: str, email: Optional[str], password: Optional[str], **extra_fields: Any
self, username: str, email: Optional[str] = ..., password: Optional[str] = ..., **extra_fields: Any
) -> _T: ...
def with_perm(
self,
perm: Union[str, Permission],
is_active: bool = ...,
include_superusers: bool = ...,
backend: Optional[Union[Type[ModelBackend], str]] = ...,
backend: Optional[str] = ...,
obj: Optional[Model] = ...,
): ...
) -> QuerySet[_T]: ...
class PermissionsMixin(models.Model):
is_superuser = models.BooleanField()
@@ -61,10 +62,10 @@ class PermissionsMixin(models.Model):
def get_group_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[str]: ...
def get_all_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[str]: ...
def has_perm(self, perm: str, obj: Optional[_AnyUser] = ...) -> bool: ...
def has_perms(self, perm_list: Collection[str], obj: Optional[_AnyUser] = ...) -> bool: ...
def has_perms(self, perm_list: Iterable[str], obj: Optional[_AnyUser] = ...) -> bool: ...
def has_module_perms(self, app_label: str) -> bool: ...
class AbstractUser(AbstractBaseUser, PermissionsMixin): # type: ignore
class AbstractUser(AbstractBaseUser, PermissionsMixin):
username_validator: UnicodeUsernameValidator = ...
username = models.CharField(max_length=150)
@@ -86,26 +87,26 @@ class User(AbstractUser): ...
class AnonymousUser:
id: Any = ...
pk: Any = ...
username: str = ...
is_staff: bool = ...
is_active: bool = ...
is_superuser: bool = ...
def save(self) -> Any: ...
def delete(self) -> Any: ...
def set_password(self, raw_password: str) -> Any: ...
username: Literal[""] = ...
is_staff: Literal[False] = ...
is_active: Literal[False] = ...
is_superuser: Literal[False] = ...
def save(self) -> None: ...
def delete(self) -> None: ...
def set_password(self, raw_password: str) -> None: ...
def check_password(self, raw_password: str) -> Any: ...
@property
def groups(self) -> EmptyManager: ...
def groups(self) -> EmptyManager[Group]: ...
@property
def user_permissions(self) -> EmptyManager: ...
def user_permissions(self) -> EmptyManager[Permission]: ...
def get_user_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[str]: ...
def get_group_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[Any]: ...
def get_all_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[str]: ...
def has_perm(self, perm: str, obj: Optional[_AnyUser] = ...) -> bool: ...
def has_perms(self, perm_list: Collection[str], obj: Optional[_AnyUser] = ...) -> bool: ...
def has_perms(self, perm_list: Iterable[str], obj: Optional[_AnyUser] = ...) -> bool: ...
def has_module_perms(self, module: str) -> bool: ...
@property
def is_anonymous(self) -> bool: ...
def is_anonymous(self) -> Literal[True]: ...
@property
def is_authenticated(self) -> bool: ...
def is_authenticated(self) -> Literal[False]: ...
def get_username(self) -> str: ...

View File

@@ -6,7 +6,8 @@ from django.db.models.base import Model
_UserModel = Model
class PasswordValidator(Protocol):
def password_changed(self, password: str, user: Optional[_UserModel] = ...): ...
def validate(self, __password: str, __user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...
def get_default_password_validators() -> List[PasswordValidator]: ...
def get_password_validators(validator_config: Sequence[Mapping[str, Any]]) -> List[PasswordValidator]: ...
@@ -37,7 +38,7 @@ class UserAttributeSimilarityValidator:
class CommonPasswordValidator:
DEFAULT_PASSWORD_LIST_PATH: Path = ...
passwords: Set[str] = ...
def __init__(self, password_list_path: Union[PosixPath, str] = ...) -> None: ...
def __init__(self, password_list_path: Union[Path, PosixPath, str] = ...) -> None: ...
def validate(self, password: str, user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...

View File

@@ -1,11 +1,17 @@
from typing import Any, Optional
from datetime import date, datetime
from typing import Any, Optional, Union
from django.contrib.auth.base_user import AbstractBaseUser
class PasswordResetTokenGenerator:
key_salt: str = ...
secret: Any = ...
algorithm: str = ...
def make_token(self, user: AbstractBaseUser) -> str: ...
def check_token(self, user: Optional[AbstractBaseUser], token: Optional[str]) -> bool: ...
def _make_token_with_timestamp(self, user: AbstractBaseUser, timestamp: int, legacy: bool = ...) -> str: ...
def _make_hash_value(self, user: AbstractBaseUser, timestamp: int) -> str: ...
def _num_seconds(self, dt: Union[datetime, date]) -> int: ...
def _now(self) -> datetime: ...
default_token_generator: Any

View File

@@ -1,3 +1,5 @@
from typing import Any, List
from typing import List
urlpatterns: List[Any] = ...
from django.urls import _AnyURL
urlpatterns: List[_AnyURL] = ...

View File

@@ -1,4 +1,4 @@
from django.core import validators
from django.core.validators import RegexValidator
class ASCIIUsernameValidator(validators.RegexValidator): ...
class UnicodeUsernameValidator(validators.RegexValidator): ...
class ASCIIUsernameValidator(RegexValidator): ...
class UnicodeUsernameValidator(RegexValidator): ...

View File

@@ -1,10 +1,9 @@
from typing import Any, Optional, Set
from typing import Any, Dict, Optional, Set
from django.contrib.auth.base_user import AbstractBaseUser
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.forms import AuthenticationForm
from django.http.request import HttpRequest
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.http.response import HttpResponse, HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
@@ -14,7 +13,7 @@ class SuccessURLAllowedHostsMixin:
success_url_allowed_hosts: Any = ...
def get_success_url_allowed_hosts(self) -> Set[str]: ...
class LoginView(SuccessURLAllowedHostsMixin, FormView):
class LoginView(SuccessURLAllowedHostsMixin, FormView[AuthenticationForm]):
authentication_form: Any = ...
redirect_field_name: Any = ...
redirect_authenticated_user: bool = ...
@@ -22,10 +21,11 @@ class LoginView(SuccessURLAllowedHostsMixin, FormView):
def get_redirect_url(self) -> str: ...
class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
next_page: Any = ...
redirect_field_name: Any = ...
next_page: Optional[str] = ...
redirect_field_name: str = ...
extra_context: Any = ...
def post(self, request: WSGIRequest, *args: Any, **kwargs: Any) -> TemplateResponse: ...
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
def get_next_page(self) -> Optional[str]: ...
def logout_then_login(request: HttpRequest, login_url: Optional[str] = ...) -> HttpResponseRedirect: ...
@@ -35,7 +35,7 @@ def redirect_to_login(
class PasswordContextMixin:
extra_context: Any = ...
def get_context_data(self, **kwargs: Any): ...
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: ...
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name: str = ...

View File

@@ -1,9 +1,10 @@
from typing import Any, List, Type
from django.contrib.admin.checks import InlineModelAdminChecks
from django.contrib.admin.options import InlineModelAdmin
from django.db.models.base import Model
class GenericInlineModelAdminChecks:
class GenericInlineModelAdminChecks(InlineModelAdminChecks):
def _check_exclude_of_parent_model(self, obj: GenericInlineModelAdmin, parent_model: Type[Model]) -> List[Any]: ...
def _check_relation(self, obj: GenericInlineModelAdmin, parent_model: Type[Model]) -> List[Any]: ...

View File

@@ -1,6 +1,11 @@
from typing import Any, List, Iterable, Optional
from typing import Any, Optional, Sequence
from django.apps.config import AppConfig
from django.core.checks.messages import CheckMessage
def check_generic_foreign_keys(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...
def check_model_name_lengths(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...
def check_generic_foreign_keys(
app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any
) -> Sequence[CheckMessage]: ...
def check_model_name_lengths(
app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any
) -> Sequence[CheckMessage]: ...

View File

@@ -1,9 +1,10 @@
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from django.contrib.contenttypes.models import ContentType
from django.core.checks.messages import Error
from django.core.checks.messages import CheckMessage
from django.db.models.base import Model
from django.db.models.expressions import Combinable
from django.db.models.fields import Field
from django.db.models.fields.mixins import FieldCacheMixin
from django.db.models.fields.related import ForeignObject
from django.db.models.fields.related_descriptors import ReverseManyToOneDescriptor
@@ -12,8 +13,6 @@ from django.db.models.query import QuerySet
from django.db.models.query_utils import FilteredRelation, PathInfo
from django.db.models.sql.where import WhereNode
from django.db.models.fields import Field, PositiveIntegerField
class GenericForeignKey(FieldCacheMixin):
# django-stubs implementation only fields
_pyi_private_set_type: Union[Any, Combinable]
@@ -41,7 +40,7 @@ class GenericForeignKey(FieldCacheMixin):
def contribute_to_class(self, cls: Type[Model], name: str, **kwargs: Any) -> None: ...
def get_filter_kwargs_for_object(self, obj: Model) -> Dict[str, Optional[ContentType]]: ...
def get_forward_related_filter(self, obj: Model) -> Dict[str, int]: ...
def check(self, **kwargs: Any) -> List[Error]: ...
def check(self, **kwargs: Any) -> List[CheckMessage]: ...
def get_cache_name(self) -> str: ...
def get_content_type(
self, obj: Optional[Model] = ..., id: Optional[int] = ..., using: Optional[str] = ...
@@ -49,7 +48,7 @@ class GenericForeignKey(FieldCacheMixin):
def get_prefetch_queryset(
self, instances: Union[List[Model], QuerySet], queryset: Optional[QuerySet] = ...
) -> Tuple[List[Model], Callable, Callable, bool, str, bool]: ...
def __get__(self, instance: Optional[Model], cls: Type[Model] = ...) -> Optional[Any]: ...
def __get__(self, instance: Optional[Model], cls: Optional[Type[Model]] = ...) -> Optional[Any]: ...
def __set__(self, instance: Model, value: Optional[Any]) -> None: ...
class GenericRel(ForeignObjectRel):
@@ -66,9 +65,9 @@ class GenericRel(ForeignObjectRel):
class GenericRelation(ForeignObject):
rel_class: Any = ...
mti_inherited: bool = ...
object_id_field_name: Any = ...
content_type_field_name: Any = ...
for_concrete_model: Any = ...
object_id_field_name: str = ...
content_type_field_name: str = ...
for_concrete_model: bool = ...
to_fields: Any = ...
def __init__(
self,
@@ -80,10 +79,9 @@ class GenericRelation(ForeignObject):
limit_choices_to: Optional[Union[Dict[str, Any], Callable[[], Any]]] = ...,
**kwargs: Any
) -> None: ...
def resolve_related_fields(self) -> List[Tuple[PositiveIntegerField, Field]]: ...
def resolve_related_fields(self) -> List[Tuple[Field, Field]]: ...
def get_path_info(self, filtered_relation: Optional[FilteredRelation] = ...) -> List[PathInfo]: ...
def get_reverse_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ...
def value_to_string(self, obj: Model) -> str: ...
def get_reverse_path_info(self, filtered_relation: Optional[FilteredRelation] = ...) -> List[PathInfo]: ...
def get_content_type(self) -> ContentType: ...
def get_extra_restriction(
self, where_class: Type[WhereNode], alias: Optional[str], remote_alias: str
@@ -92,4 +90,4 @@ class GenericRelation(ForeignObject):
class ReverseGenericManyToOneDescriptor(ReverseManyToOneDescriptor): ...
def create_generic_related_manager(superclass: Any, rel: Any): ...
def create_generic_related_manager(superclass: Any, rel: Any) -> Type[Any]: ... # GenericRelatedObjectManager

View File

@@ -1,8 +1,12 @@
from typing import Any, Optional
from typing import Any, Optional, Type, TypeVar
from django.forms.models import BaseModelFormSet
from django.db.models import Model
from django.forms.models import BaseModelFormSet, ModelForm
class BaseGenericInlineFormSet(BaseModelFormSet):
_M = TypeVar("_M", bound=Model)
_ModelFormT = TypeVar("_ModelFormT", bound=ModelForm)
class BaseGenericInlineFormSet(BaseModelFormSet[_M, _ModelFormT]):
instance: Any = ...
rel_name: Any = ...
save_as_new: Any = ...
@@ -16,14 +20,14 @@ class BaseGenericInlineFormSet(BaseModelFormSet):
queryset: Optional[Any] = ...,
**kwargs: Any
) -> None: ...
def initial_form_count(self): ...
def initial_form_count(self) -> int: ...
@classmethod
def get_default_prefix(cls): ...
def save_new(self, form: Any, commit: bool = ...): ...
def get_default_prefix(cls) -> str: ...
def save_new(self, form: Any, commit: bool = ...) -> _M: ...
def generic_inlineformset_factory(
model: Any,
form: Any = ...,
model: Type[_M],
form: Type[_ModelFormT] = ...,
formset: Any = ...,
ct_field: str = ...,
fk_field: str = ...,
@@ -38,4 +42,6 @@ def generic_inlineformset_factory(
for_concrete_model: bool = ...,
min_num: Optional[Any] = ...,
validate_min: bool = ...,
): ...
absolute_max: Optional[int] = ...,
can_delete_extra: bool = ...,
) -> Type[BaseGenericInlineFormSet[_M, _ModelFormT]]: ...

View File

@@ -1,4 +1,4 @@
from typing import Any, Dict, List, Optional, Tuple, Type
from typing import Any, Dict, List, Tuple, Type
from django.apps.config import AppConfig
from django.apps.registry import Apps

View File

@@ -1,8 +1,7 @@
from typing import Any, Dict, List
from django.db.models.deletion import Collector
from django.core.management import BaseCommand
from django.db.models.deletion import Collector
class Command(BaseCommand): ...

View File

@@ -0,0 +1,10 @@
from typing import Any
from django.contrib import admin
class FlatPageAdmin(admin.ModelAdmin):
form: Any = ...
fieldsets: Any = ...
list_display: Any = ...
list_filter: Any = ...
search_fields: Any = ...

View File

@@ -0,0 +1,7 @@
from typing import Any
from django.apps import AppConfig as AppConfig
class FlatPagesConfig(AppConfig):
name: str = ...
verbose_name: Any = ...

View File

@@ -1,6 +1,6 @@
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class FlatpageFallbackMiddleware(MiddlewareMixin):
def process_response(self, request: WSGIRequest, response: HttpResponse) -> HttpResponse: ...
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: ...

View File

@@ -1,5 +1,4 @@
from django.contrib.sites.models import Site
from django.db import models
class FlatPage(models.Model):

View File

@@ -1,3 +1,5 @@
from typing import Any, List
from typing import List
urlpatterns: List[Any] = ...
from django.urls import _AnyURL
urlpatterns: List[_AnyURL] = ...

View File

@@ -1,8 +1,8 @@
from django.contrib.flatpages.models import FlatPage
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.http.response import HttpResponse
DEFAULT_TEMPLATE: str
def flatpage(request: WSGIRequest, url: str) -> HttpResponse: ...
def render_flatpage(request: WSGIRequest, f: FlatPage) -> HttpResponse: ...
def flatpage(request: HttpRequest, url: str) -> HttpResponse: ...
def render_flatpage(request: HttpRequest, f: FlatPage) -> HttpResponse: ...

View File

@@ -0,0 +1 @@
default_app_config: str

View File

@@ -0,0 +1,11 @@
from django.contrib.admin import HORIZONTAL as HORIZONTAL
from django.contrib.admin import VERTICAL as VERTICAL
from django.contrib.admin import AdminSite as AdminSite
from django.contrib.admin import ModelAdmin as ModelAdmin
from django.contrib.admin import StackedInline as StackedInline
from django.contrib.admin import TabularInline as TabularInline
from django.contrib.admin import autodiscover as autodiscover
from django.contrib.admin import register as register
from django.contrib.admin import site as site
from django.contrib.gis.admin.options import GeoModelAdmin as GeoModelAdmin
from django.contrib.gis.admin.options import OSMGeoAdmin as OSMGeoAdmin

View File

@@ -0,0 +1,48 @@
from typing import Any, Union
from django.contrib.admin import ModelAdmin as ModelAdmin
spherical_mercator_srid: int
class GeoModelAdmin(ModelAdmin):
default_lon: int = ...
default_lat: int = ...
default_zoom: int = ...
display_wkt: bool = ...
display_srid: bool = ...
extra_js: Any = ...
num_zoom: int = ...
max_zoom: bool = ...
min_zoom: bool = ...
units: Union[str, bool] = ...
max_resolution: Union[str, bool] = ...
max_extent: Union[str, bool] = ...
modifiable: bool = ...
mouse_position: bool = ...
scale_text: bool = ...
layerswitcher: bool = ...
scrollable: bool = ...
map_width: int = ...
map_height: int = ...
map_srid: int = ...
map_template: str = ...
openlayers_url: str = ...
point_zoom: Any = ...
wms_url: str = ...
wms_layer: str = ...
wms_name: str = ...
wms_options: Any = ...
debug: bool = ...
widget: Any = ...
@property
def media(self) -> Any: ...
def get_map_widget(self, db_field: Any) -> Any: ...
class OSMGeoAdmin(GeoModelAdmin):
map_template: str = ...
num_zoom: int = ...
map_srid: Any = ...
max_extent: str = ...
max_resolution: str = ...
point_zoom: int = ...
units: str = ...

View File

@@ -0,0 +1,11 @@
from logging import Logger
from typing import Any
from django.forms.widgets import Textarea as Textarea
geo_context: Any
logger: Logger
class OpenLayersWidget(Textarea):
def get_context(self, name: Any, value: Any, attrs: Any) -> Any: ...
def map_options(self) -> Any: ...

View File

@@ -0,0 +1,8 @@
from typing import Any
from django.apps import AppConfig as AppConfig
class GISConfig(AppConfig):
name: str = ...
verbose_name: Any = ...
def ready(self) -> None: ...

View File

@@ -0,0 +1,8 @@
from typing import Any
class WKTAdapter:
wkt: Any = ...
srid: Any = ...
def __init__(self, geom: Any) -> None: ...
def __eq__(self, other: Any) -> Any: ...
def __hash__(self) -> Any: ...

View File

@@ -0,0 +1,44 @@
from typing import Any
class BaseSpatialFeatures:
gis_enabled: bool = ...
has_spatialrefsys_table: bool = ...
supports_add_srs_entry: bool = ...
supports_geometry_field_introspection: bool = ...
supports_3d_storage: bool = ...
supports_3d_functions: bool = ...
supports_transform: bool = ...
supports_null_geometries: bool = ...
supports_empty_geometries: bool = ...
supports_distance_geodetic: bool = ...
supports_length_geodetic: bool = ...
supports_perimeter_geodetic: bool = ...
supports_area_geodetic: bool = ...
supports_num_points_poly: bool = ...
supports_left_right_lookups: bool = ...
supports_dwithin_distance_expr: bool = ...
supports_raster: bool = ...
supports_geometry_field_unique_index: bool = ...
@property
def supports_bbcontains_lookup(self) -> bool: ...
@property
def supports_contained_lookup(self) -> bool: ...
@property
def supports_crosses_lookup(self) -> bool: ...
@property
def supports_distances_lookups(self) -> bool: ...
@property
def supports_dwithin_lookup(self) -> bool: ...
@property
def supports_relate_lookup(self) -> bool: ...
@property
def supports_isvalid_lookup(self) -> bool: ...
@property
def supports_collect_aggr(self) -> bool: ...
@property
def supports_extent_aggr(self) -> bool: ...
@property
def supports_make_line_aggr(self) -> bool: ...
@property
def supports_union_aggr(self) -> bool: ...
def __getattr__(self, name: Any) -> bool: ...

View File

@@ -0,0 +1,33 @@
from typing import Any
class SpatialRefSysMixin:
@property
def srs(self) -> Any: ...
@property
def ellipsoid(self) -> Any: ...
@property
def name(self) -> Any: ...
@property
def spheroid(self) -> Any: ...
@property
def datum(self) -> Any: ...
@property
def projected(self) -> Any: ...
@property
def local(self) -> Any: ...
@property
def geographic(self) -> Any: ...
@property
def linear_name(self) -> Any: ...
@property
def linear_units(self) -> Any: ...
@property
def angular_name(self) -> Any: ...
@property
def angular_units(self) -> Any: ...
@property
def units(self) -> Any: ...
@classmethod
def get_units(cls, wkt: Any) -> Any: ...
@classmethod
def get_spheroid(cls, wkt: Any, string: bool = ...) -> Any: ...

View File

@@ -0,0 +1,34 @@
from typing import Any, Set
class BaseSpatialOperations:
postgis: bool = ...
spatialite: bool = ...
mysql: bool = ...
oracle: bool = ...
spatial_version: Any = ...
select: str = ...
@property
def select_extent(self) -> str: ...
geography: bool = ...
geometry: bool = ...
disallowed_aggregates: Any = ...
geom_func_prefix: str = ...
function_names: Any = ...
unsupported_functions: Set[str] = ...
from_text: bool = ...
def convert_extent(self, box: Any, srid: Any) -> Any: ...
def convert_extent3d(self, box: Any, srid: Any) -> Any: ...
def geo_quote_name(self, name: Any) -> Any: ...
def geo_db_type(self, f: Any) -> Any: ...
def get_distance(self, f: Any, value: Any, lookup_type: Any) -> Any: ...
def get_geom_placeholder(self, f: Any, value: Any, compiler: Any) -> Any: ...
def check_expression_support(self, expression: Any) -> None: ...
def spatial_aggregate_name(self, agg_name: Any) -> Any: ...
def spatial_function_name(self, func_name: Any) -> Any: ...
def geometry_columns(self) -> Any: ...
def spatial_ref_sys(self) -> Any: ...
distance_expr_for_lookup: Any = ...
def get_db_converters(self, expression: Any) -> Any: ...
def get_geometry_converter(self, expression: Any) -> Any: ...
def get_area_att_for_field(self, field: Any) -> Any: ...
def get_distance_att_for_field(self, field: Any) -> Any: ...

View File

@@ -0,0 +1,9 @@
from typing import Any
from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper
class DatabaseWrapper(MySQLDatabaseWrapper):
SchemaEditorClass: Any = ...
features_class: Any = ...
introspection_class: Any = ...
ops_class: Any = ...

View File

@@ -0,0 +1,20 @@
from typing import Any, Dict
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures as BaseSpatialFeatures
from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures
class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures):
has_spatialrefsys_table: bool = ...
supports_add_srs_entry: bool = ...
supports_distance_geodetic: bool = ...
supports_length_geodetic: bool = ...
supports_area_geodetic: bool = ...
supports_transform: bool = ...
supports_null_geometries: bool = ...
supports_num_points_poly: bool = ...
@property
def empty_intersection_returns_none(self) -> bool: ...
@property
def supports_geometry_field_unique_index(self) -> bool: ... # type: ignore
@property
def django_test_skips(self) -> Dict[str, Any]: ... # type: ignore

View File

@@ -0,0 +1,8 @@
from typing import Any
from django.db.backends.mysql.introspection import DatabaseIntrospection as DatabaseIntrospection
class MySQLIntrospection(DatabaseIntrospection):
data_types_reverse: Any = ...
def get_geometry_type(self, table_name: Any, description: Any) -> Any: ...
def supports_spatial_index(self, cursor: Any, table_name: Any) -> Any: ...

View File

@@ -0,0 +1,27 @@
from typing import Any, Callable, Dict, List, Optional, Set, Type
from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations as BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.geos.geometry import GEOSGeometryBase
from django.db.backends.mysql.operations import DatabaseOperations as DatabaseOperations
class MySQLOperations(BaseSpatialOperations, DatabaseOperations):
name: str = ...
geom_func_prefix: str = ...
Adapter: Any = ...
@property
def mariadb(self) -> bool: ...
@property
def mysql(self) -> bool: ... # type: ignore
@property
def select(self) -> str: ... # type: ignore
@property
def from_text(self) -> str: ... # type: ignore
@property
def gis_operators(self) -> Dict[str, SpatialOperator]: ...
disallowed_aggregates: Any = ...
@property
def unsupported_functions(self) -> Set[str]: ... # type: ignore
def geo_db_type(self, f: Any) -> Any: ...
def get_distance(self, f: Any, value: Any, lookup_type: Any) -> List[Any]: ...
def get_geometry_converter(self, expression: Any) -> Callable[[Any, Any, Any], Optional[GEOSGeometryBase]]: ...

View File

@@ -0,0 +1,18 @@
from logging import Logger
from typing import Any
from django.db.backends.mysql.schema import DatabaseSchemaEditor as DatabaseSchemaEditor
logger: Logger
class MySQLGISSchemaEditor(DatabaseSchemaEditor):
sql_add_spatial_index: str = ...
sql_drop_spatial_index: str = ...
geometry_sql: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def skip_default(self, field: Any) -> Any: ...
def column_sql(self, model: Any, field: Any, include_default: bool = ...) -> Any: ...
def create_model(self, model: Any) -> None: ...
def add_field(self, model: Any, field: Any) -> None: ...
def remove_field(self, model: Any, field: Any) -> None: ...
def create_spatial_indexes(self) -> None: ...

View File

@@ -0,0 +1,9 @@
from typing import Any
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
class OracleSpatialAdapter(WKTAdapter):
input_size: Any = ...
wkt: Any = ...
srid: Any = ...
def __init__(self, geom: Any) -> None: ...

View File

@@ -0,0 +1,9 @@
from typing import Any
from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper
class DatabaseWrapper(OracleDatabaseWrapper):
SchemaEditorClass: Any = ...
features_class: Any = ...
introspection_class: Any = ...
ops_class: Any = ...

View File

@@ -0,0 +1,9 @@
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures as BaseSpatialFeatures
from django.db.backends.oracle.features import DatabaseFeatures as OracleDatabaseFeatures
class DatabaseFeatures(BaseSpatialFeatures, OracleDatabaseFeatures):
supports_add_srs_entry: bool = ...
supports_geometry_field_introspection: bool = ...
supports_geometry_field_unique_index: bool = ...
supports_perimeter_geodetic: bool = ...
supports_dwithin_distance_expr: bool = ...

View File

@@ -0,0 +1,8 @@
from typing import Any
from django.db.backends.oracle.introspection import DatabaseIntrospection as DatabaseIntrospection
class OracleIntrospection(DatabaseIntrospection):
@property
def data_types_reverse(self) -> Any: ...
def get_geometry_type(self, table_name: Any, description: Any) -> Any: ...

View File

@@ -0,0 +1,33 @@
from typing import Any
from django.contrib.gis.db import models
from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin
class OracleGeometryColumns(models.Model):
table_name: Any = ...
column_name: Any = ...
srid: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@classmethod
def table_name_col(cls) -> Any: ...
@classmethod
def geom_col_name(cls) -> Any: ...
class OracleSpatialRefSys(models.Model, SpatialRefSysMixin):
cs_name: Any = ...
srid: Any = ...
auth_srid: Any = ...
auth_name: Any = ...
wktext: Any = ...
cs_bounds: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@property
def wkt(self) -> Any: ...

View File

@@ -0,0 +1,42 @@
from typing import Any
from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations as BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator as SpatialOperator
from django.db.backends.oracle.operations import DatabaseOperations as DatabaseOperations
DEFAULT_TOLERANCE: str
class SDOOperator(SpatialOperator):
sql_template: str = ...
class SDODWithin(SpatialOperator):
sql_template: str = ...
class SDODisjoint(SpatialOperator):
sql_template: Any = ...
class SDORelate(SpatialOperator):
sql_template: str = ...
def check_relate_argument(self, arg: Any) -> None: ...
class OracleOperations(BaseSpatialOperations, DatabaseOperations):
name: str = ...
oracle: bool = ...
disallowed_aggregates: Any = ...
Adapter: Any = ...
extent: str = ...
unionagg: str = ...
function_names: Any = ...
select: str = ...
gis_operators: Any = ...
unsupported_functions: Any = ...
def geo_quote_name(self, name: Any) -> Any: ...
def geo_db_type(self, f: Any) -> Any: ...
def get_distance(self, f: Any, value: Any, lookup_type: Any) -> Any: ...
def get_geom_placeholder(self, f: Any, value: Any, compiler: Any) -> Any: ...
def spatial_aggregate_name(self, agg_name: Any) -> Any: ...
def geometry_columns(self) -> Any: ...
def spatial_ref_sys(self) -> Any: ...
def modify_insert_params(self, placeholder: Any, params: Any) -> Any: ...
def get_geometry_converter(self, expression: Any) -> Any: ...
def get_area_att_for_field(self, field: Any) -> Any: ...

View File

@@ -0,0 +1,19 @@
from typing import Any
from django.db.backends.oracle.schema import DatabaseSchemaEditor
class OracleGISSchemaEditor(DatabaseSchemaEditor):
sql_add_geometry_metadata: str = ...
sql_add_spatial_index: str = ...
sql_drop_spatial_index: str = ...
sql_clear_geometry_table_metadata: str = ...
sql_clear_geometry_field_metadata: str = ...
geometry_sql: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def geo_quote_name(self, name: Any) -> Any: ...
def column_sql(self, model: Any, field: Any, include_default: bool = ...) -> Any: ...
def create_model(self, model: Any) -> None: ...
def delete_model(self, model: Any) -> None: ...
def add_field(self, model: Any, field: Any) -> None: ...
def remove_field(self, model: Any, field: Any) -> None: ...
def run_geometry_sql(self) -> None: ...

Some files were not shown because too many files have changed in this diff Show More