213 Commits

Author SHA1 Message Date
Dave Halter
28afe59881 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.
2021-02-26 22:15:01 +01: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
Nikita Sobolev
7ba578f6b2 Refactors validators types (#284)
* Update __init__.pyi

* It should not fail right now 🤔

* Refactor validators a bit

* Fixes CI

* Update __init__.pyi
2019-12-21 15:44:26 +03:00
Maksim Kurnikov
cb123de105 BaseManager.from_queryset(): properly resolve methods for QuerySet defined in another file (#282)
* BaseManager.from_queryset() from another file

* only anal_type per argument

* add resolve for return_type

* fix mypy errors

* remove leftover comment
2019-12-18 20:01:20 +03:00
Maksim Kurnikov
38135f2d1f Merge pull request #281 from mkurnikov/update-deps
Update dev deps, mypy to 0.760
2019-12-18 00:13:11 +03:00
Maxim Kurnikov
998b659749 bump to 1.4.0 2019-12-18 00:03:29 +03:00
Maxim Kurnikov
72f69e1c5e remove unused ignores 2019-12-18 00:02:55 +03:00
Maxim Kurnikov
d666ecd36f update dev deps, mypy to 0.760 2019-12-17 23:50:50 +03:00
Maksim Kurnikov
c1af26c027 handle return value of anal_type properly (#280) 2019-12-17 23:36:44 +03:00
Maxim Kurnikov
3c3dfcbc9f bump to 1.3.3 2019-12-17 19:20:27 +03:00
Maksim Kurnikov
1196336e3b Perform anal_type for arguments and return type when copying methods to another class (#279)
* Found the reproducible test case

* fix import resolution for method copy

* remove irrelevant parts from test

* fix mypy errors

Co-authored-by: Boger <kotvberloge@gmail.com>
2019-12-17 19:19:31 +03:00
Maksim Kurnikov
665f4d8ea1 Make related manager inherit from objects of related model (#278)
* related manager inherits from objects of related model

* fix test typechecking

* lint
2019-12-17 19:06:27 +03:00
Dima Boger
b3ed9e4827 Add inheritance QuerySet support for from_queryset (#275)
* Add testcase for queryset inheritance

* Add PoC

* Add condition for stop to looping over mro

* Change harcoded queryset class name to constant from fullnames
2019-12-16 20:16:41 +03:00
Marti Raudsepp
fb1593630a Expand stubs for django.core.management.color (#276)
Many attributes were previously missing; 'DEBUG' and 'INFO' attributes
were never supported by Django.
2019-12-16 20:16:21 +03:00
JR Heard
031d42a75d update ChoiceField's choices kwarg's annotation (#273)
per the [docs](https://docs.djangoproject.com/en/3.0/ref/forms/fields/#choicefield), `choices` is:

> Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable.
2019-12-14 09:30:50 +03:00
Maxim Kurnikov
f7e1cfc6c7 bump to 1.3.2 2019-12-13 23:55:08 +03:00
Maksim Kurnikov
d0c25e3bce Allow to run from_queryset() with BaseManager, Manager (#271)
* allow to run from_queryset() with BaseManager, Manager

* fix tests
2019-12-13 20:16:33 +03:00
Maksim Kurnikov
1c31e71ffc enable 'model_forms' for tests typechecking (#270) 2019-12-13 13:30:21 +03:00
Dmitry Groshev
6b3b6be3c1 add .model field to _BaseQuerySet (#268) 2019-12-12 21:50:59 +03:00
Maksim Kurnikov
5832605053 Remove warning about unsupported expression types (#266)
* remove warning about unsupported expression for _meta.get_field()

* lint
2019-12-12 08:20:52 +03:00
Maksim Kurnikov
31e795016f values(), values_list() with ManyToManyField (#267) 2019-12-12 08:09:47 +03:00
Maxim Kurnikov
0cba3f9fd6 bump to 1.3.1 2019-12-12 08:03:47 +03:00
Maksim Kurnikov
f02050911f various annotation improvements (#258) 2019-12-12 06:42:29 +03:00
henribru
e8e6fca78c Fix return type of refresh_from_db (#244) 2019-12-12 05:36:11 +03:00
Maksim Kurnikov
ade48b6546 Add support for BaseManager.from_queryset() (#251)
* add support for BaseManager.from_queryset()

* cleanups

* lint fixes
2019-12-12 05:35:56 +03:00
Maksim Kurnikov
b8f29027d8 Suppress IncompleteDefnException on final_iteration and continue with the loop (#260)
* suppress IncompleteDefnException on final_iteration

* lint
2019-12-12 01:04:24 +03:00
Hannes Ljungberg
eba3f6cb15 Update django.contrib.auth with Django 3.0 compatibility (#256)
* Add support for BaseBackend

* Add User.get_user_permissions

* Add support for UserManager.with_perm

* Add support for reset_url_token
2019-12-11 01:10:10 +03:00
Maksim Kurnikov
5a45544e76 Optimize tests typechecking script (#255)
* skip whole Django repo for tests typechecking

* lint
2019-12-11 00:52:08 +03:00
Maksim Kurnikov
8c2de7da56 add a number of django test directories for typecheck (#257) 2019-12-11 00:51:32 +03:00
Maksim Kurnikov
d43c6dc7e2 Merge pull request #254 from mkurnikov/better-force-text-types
Better types for django.utils.encoding
2019-12-10 23:36:38 +03:00
Maxim Kurnikov
f7e2109e06 add @overload clauses to smart_text, smart_bytes, force_bytes 2019-12-10 23:22:23 +03:00
Hannes Ljungberg
cea62abf5a Add support for database functions introduced in 3.0 (#253)
* Add support for hash database functions

* Add support for Sign
2019-12-10 22:36:11 +03:00
Hannes Ljungberg
3b69ec6a72 Add support for RangeBoundary (#252) 2019-12-10 22:09:55 +03:00
Seth Yastrov
7e794534c0 Better type for force_text using overloads/Literal
- If a str is passed in, it returns a str.
- If strings_only = True and a "protected type" is passed in, returns that type.
- Default if it doesn't match the overloads: return a str
2019-12-10 21:28:40 +03:00
Hannes Ljungberg
f5f33b061d Add support for exclusion constraints (#249) 2019-12-10 20:50:28 +03:00
Ran Benita
58b26fdbd3 Improve TestCase.assertNumQueries type (#250) 2019-12-10 19:37:13 +03:00
Youssef Moussaoui
9ca79c24a2 Move BLANK_CHOICE to django.db.models.fields (#242) 2019-12-08 08:19:24 +03:00
Maxim Kurnikov
540e28f4c6 bump version to 1.3.0 2019-12-06 23:37:19 +03:00
Maksim Kurnikov
4ac43c6ed6 Add Django 3.0 testing to CI (#246)
* add Django 3.0 testing to CI

* remove importlib_metadata usage

* conditionally load choices module for tests
2019-12-06 23:36:24 +03:00
Maksim Kurnikov
cadd6c963b fix model's on_cascade= parameter for test, update to latest gdal (#247) 2019-12-06 03:40:55 +03:00
Konstantin Alekseev
041754f817 Fix smtp backend open (#240) 2019-12-01 20:46:11 +03:00
Konstantin Alekseev
c0c5d1e588 Cleanup EmailMessage types (#208)
* Cleanup EmailMessage types

* Typecheck email module tests.
2019-12-01 17:14:16 +03:00
Maksim Kurnikov
f824003cc4 remove unused ignore pattern (#239) 2019-12-01 00:09:36 +03:00
Youssef Moussaoui
58f1833cab Declare is_relation and related_model on Field (#230) 2019-11-30 22:40:22 +03:00
Maksim Kurnikov
cbb6a7a9ac Merge pull request #238 from mkurnikov/mypy-750
Mypy 0.750 support
2019-11-30 22:27:50 +03:00
Maxim Kurnikov
2c4827bbaf properly change type of self for methods on custom manager classes 2019-11-30 22:08:16 +03:00
Maxim Kurnikov
5a151bf851 update django tests branch 2019-11-30 20:56:31 +03:00
Konstantin Alekseev
cbc7159995 Support mypy 0.750 2019-11-30 13:39:28 +03:00
Patrick Gingras
df4c17a947 added base_fields and declared_fields properties to Form (#235) 2019-11-27 22:48:05 +03:00
yaegassy
445abc046c README.md Fix: sample code for "Notes" (#234) 2019-11-26 15:40:21 +03:00
Anthony Ricaud
557b7a4fa3 Add new View.setup method introduced in Django 2.2 (#233)
https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/#django.views.generic.base.View.setup
https://github.com/django/django/blob/2.2/django/views/generic/base.py#L83-L87
2019-11-20 23:49:38 +03:00
Maksim Kurnikov
8343d76895 Fix has_perm() methods for auth backend, and for contrib.auth.models (#232)
* fix has_perm() methods

* lint
2019-11-19 04:54:17 +03:00
Maksim Kurnikov
8d986a0f43 remove catch-all __getattr__ for Manager, fix some issues with manager methods (#227) 2019-11-12 20:36:07 +03:00
Pilifer
e9a90ebff0 More precise annotations of utils.timezone functions that return instances of tzinfo subclasses. (#209)
* fix annotations of utils.timezone

* use intermediary tzinfo subclass exposed in pytz typeshed

* fix annotations of get_fixed_timezone as it returns datetime.timezone in Django 2.2

* add explanatory comment to get_current_timezone annotations

* black utils.timezone.pyi
2019-11-12 18:27:54 +03:00
Christopher Sabater Cordero
7b74a6944a Add a few missing types to the stubfiles (#214)
* Add types to stub files.

* Fix black and flake8 errors.
2019-11-12 18:25:31 +03:00
Seth Yastrov
83f11a0fc6 Add Tags.translation to stub (#226) 2019-11-12 18:23:29 +03:00
Seth Yastrov
2829faf1af Both CSRF_COOKIE_SAMESITE and SESSION_COOKIE_SAMESITE should be Optional (#216) 2019-11-12 16:13:16 +03:00
src
d061e84cc7 Add HttpResponsePermanentRedirect to django.shortcuts (#211) 2019-11-12 16:12:36 +03:00
Anna Sidwell
3a9263dc62 Two small improvements (#217)
* Add return type for admin.SimpleListFilter.lookups

* force_login() can take any user, not just builtin
2019-11-12 13:31:24 +03:00
Yngve Høiseth
14aea2b4d4 Allow returning bool from test_func (#220) 2019-11-12 05:52:23 +03:00
Maksim Kurnikov
287c64d6fb Pin to 0.740 and fix CI (#225)
* update django sources

* pin mypy version, update to 0.740

* fix tests typechecking

* fix lint
2019-11-12 05:17:36 +03:00
Nikita Sobolev
6601121db2 Fixes travis url 2019-10-21 23:47:06 +03:00
Andrey
87d59c7c1a Fix django.contrib.admin.options.BaseModelAdmin.has_add_permission (#205)
* Fix `django.contrib.admin.options.BaseModelAdmin.has_add_permission` (#203).

* Add `django.db.models.base.Model.unique_error_message` (#204).
2019-10-11 12:16:21 +03:00
Maxim Kurnikov
8402e7c53e improve annotations in some places (#202)
* improve annotations in some places

* linting
2019-10-07 14:50:45 +03:00
Maxim Kurnikov
dceb075152 fix annotation for BaseCommand.handle() (#201) 2019-10-05 21:36:41 +03:00
Maxim Kurnikov
7e3f4bfa02 Fix ForeignKey type for self-reference defined in the abstract model (#200) 2019-10-05 21:36:29 +03:00
Maxim Kurnikov
db9ff6aaf6 Fix crash if model from same app referenced in RelatedField cannot be resolved (#199)
* do not crash if model from same app refd in ForeignKey cannot be resolved

* bump to 1.2.0
2019-10-05 20:00:51 +03:00
Maxim Kurnikov
717be5940f Reorganize code a bit, add current directory to sys.path (#198)
* reorganize code a bit

* add current directory to sys.path

* remove PYTHONPATH mention from the docs

* linting
2019-10-05 19:44:29 +03:00
Nikita Sobolev
b939bc96b7 Improves README with new example repo, python version matrix (#195) 2019-10-01 15:24:48 +03:00
425 changed files with 9459 additions and 2067 deletions

20
.github/workflows/misspel.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: misspell
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * *'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: sobolevn/misspell-fixer-action@0.1.0
- uses: peter-evans/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: 'Fixes by misspell-fixer'
title: 'Typos fix by misspell-fixer'

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

@@ -0,0 +1,85 @@
name: test
on: [push, pull_request, workflow_dispatch]
jobs:
lint:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9']
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ matrix.python-version }}-lint-${{ hashFiles('./dev-requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-lint-
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./dev-requirements.txt
- name: Run pre-commit
run: pre-commit install && pre-commit run --all-files
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.7']
steps:
- uses: actions/checkout@v2
- 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@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ matrix.python-version }}-test-${{ hashFiles('./dev-requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-test-
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./dev-requirements.txt
- name: Run tests
run: pytest
typecheck:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.6', '3.7', '3.8', '3.9']
django-version: ['2.2', '3.0']
steps:
- uses: actions/checkout@v2
- 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@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ matrix.django-version }}-typecheck-${{ hashFiles('./dev-requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-${{ matrix.django-version }}-typecheck-
- name: Install dependencies
run: |
pip install -U pip setuptools wheel
pip install -r ./dev-requirements.txt
- name: Run tests
run: python ./scripts/typecheck_tests.py --django_version="${{ matrix.django-version }}"

15
.gitignore vendored
View File

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

4
.gitmodules vendored
View File

@@ -1,4 +0,0 @@
[submodule "django-sources"]
path = django-sources
url = https://github.com/django/django.git
branch = stable/2.2.x

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

@@ -0,0 +1,46 @@
# 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: v3.3.0
hooks:
- id: check-yaml
- id: trailing-whitespace
- id: check-executables-have-shebangs
- id: debug-statements
- id: check-merge-conflict
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.3
hooks:
- id: pyupgrade
args: ["--py36-plus"]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.6.4
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
- repo: local
hooks:
- id: mypy
name: mypy
entry: mypy
language: system
types: [ python ]
exclude: "scripts/|django_stubs_ext/"
args: [ "--config=mypy.ini", "--cache-dir=/dev/null", "--no-incremental" ]
- id: mypy
name: mypy (django_stubs_ext)
entry: mypy
language: system
types: [ python ]
files: "django_stubs_ext/|django_stubs_ext/tests/"
args: [ "--config=mypy.ini", "--cache-dir=/dev/null", "--no-incremental", "--strict" ]

View File

@@ -1,44 +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 test suite with python 3.7
python: 3.7
script: 'python ./scripts/typecheck_tests.py'
- name: Typecheck Django test suite with python 3.6
python: 3.6
script: 'python ./scripts/typecheck_tests.py'
- 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 apt update
sudo apt install binutils libproj-dev gdal-bin
pip install -U pip setuptools wheel
install: |
pip install -r ./dev-requirements.txt

112
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,112 @@
# 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 ./dev-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
```
We also test the stubs against the 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.0
```
### 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/tree/master/django_stubs_ext/django_stubs_ext/monkeypatch.py)

199
README.md
View File

@@ -1,16 +1,14 @@
<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.org/typeddjango/django-stubs.svg?branch=master)](https://travis-ci.org/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)
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.
Supports Python 3.6/3.7, and Django 2.1/2.2.
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.
Could be run on earlier versions of Django, but expect some missing imports warnings.
## Installation
@@ -18,68 +16,175 @@ Could be run on earlier versions of Django, but expect some missing imports warn
pip install django-stubs
```
## Mypy compatibility
| django-stubs | mypy version | django version |
| ------------ | ---- | ---- |
| 1.2.0 | 0.730 | 2.2.x
| 1.1.0 | 0.720 | 2.2.x
| 0.12.x | old semantic analyzer (<0.711), dmypy support | 2.1.x
### WARNING: All configuration from pre-1.0.0 versions is dropped, use one below.
### WARNING: 1.0.0 breaks `dmypy`, if you need it, stay on the 0.12.x series.
To make mypy aware of the plugin, you need to add
```ini
[mypy]
plugins =
mypy_django_plugin.main
```
in your `mypy.ini` file.
Plugin requires Django settings module (what you put into `DJANGO_SETTINGS_MODULE` variable) to be specified inside `mypy.ini` file.
```ini
[mypy]
strict_optional = True
; this one is new
[mypy.plugins.django-stubs]
django_settings_module = mysettings
django_settings_module = "myproject.settings"
```
where `mysettings` is a value of `DJANGO_SETTINGS_MODULE` (with or without quotes)
in your `mypy.ini` or `setup.cfg` [file](https://mypy.readthedocs.io/en/latest/config_file.html).
Do you have trouble with mypy / the django plugin not finding your settings module? Try adding the root path of your project to your PYTHONPATH environment variable. If you use pipenv you can add the following to an `.env` file in your project root which pipenv will run automatically before executing any commands.:
```
PYTHONPATH=${PYTHONPATH}:${PWD}
Two things happeining here:
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
We rely on different `django` and `mypy` versions:
| django-stubs | mypy version | django version | python version
| ------------ | ---- | ---- | ---- |
| 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
Current implementation uses Django runtime to extract models information, so it will crash, if your installed apps or `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.
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
```
New 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.
## Notes
Implementation monkey-patches Django to add `__class_getitem__` to the `Manager` class. If you'd use Python3.7 and do that too in your code, you can make things like
And then place in your top-level settings:
```python
class MyUserManager(models.Manager['MyUser']):
pass
class MyUser(models.Model):
objects = UserManager()
import django_stubs_ext
django_stubs_ext.monkeypatch()
```
work, which should make a error messages a bit better.
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` has the attribute `user` that resolves to the type
```python
Union[User, AnonymousUser]
```
where `User` is the user model specified by the `AUTH_USER_MODEL` setting.
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
```
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
`QuerySet.as_manager()` is not currently supported.
If you are using `MyQuerySet.as_manager()`, then your `Manager`/`QuerySet` methods will all not be linked to your model.
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():
foo = MyModel.objects.get(id=1) # This is `Any` but it should be `MyModel`
return foo.xyz # No error, but there should be
```
There is a workaround: use `Manager.from_queryset` instead.
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():
foo = MyModel.objects.get(id=1)
return foo.xyz # Gives an 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
You can always also reach out in gitter to discuss your contributions!

View File

@@ -1,7 +1,12 @@
black
pytest-mypy-plugins==1.1.0
psycopg2
flake8==3.7.8
flake8-pyi==19.3.0
isort==4.3.21
wheel
mypy==0.790
requests==2.24.0
coreapi==2.3.3
typing-extensions==3.7.4.3
gitpython==3.1.9
pre-commit==2.7.1
pytest==6.1.1
pytest-mypy-plugins==1.6.1
psycopg2-binary
-e ./django_stubs_ext
-e .

Submodule django-sources updated: f452d4232e...aa28213eb5

View File

@@ -1,5 +1,6 @@
from typing import Any, Iterator, Type, Optional, Dict
from django.apps.registry import Apps
from django.db.models.base import Model
MODELS_MODULE_NAME: str
@@ -7,11 +8,11 @@ MODELS_MODULE_NAME: str
class AppConfig:
name: str = ...
module: Optional[Any] = ...
apps: None = ...
apps: Optional[Apps] = ...
label: str = ...
verbose_name: str = ...
path: str = ...
models_module: None = ...
models_module: Optional[str] = ...
models: Dict[str, Type[Model]] = ...
def __init__(self, app_name: str, app_module: Optional[Any]) -> None: ...
@classmethod

View File

@@ -1,24 +1,22 @@
import threading
from collections import OrderedDict
from typing import Any, Callable, DefaultDict, Dict, Iterable, List, Optional, Tuple, Type, Union
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from django.db.migrations.state import AppConfigStub
from django.db.models.base import Model
from .config import AppConfig
class Apps:
all_models: Dict[str, OrderedDict[str, Type[Model]]] = ...
app_configs: OrderedDict[str, AppConfig] = ...
all_models: Dict[str, Dict[str, Type[Model]]] = ...
app_configs: Dict[str, AppConfig] = ...
stored_app_configs: List[Any] = ...
apps_ready: bool = ...
ready_event: threading.Event = ...
loading: bool = ...
_pending_operations: DefaultDict[Tuple[str, str], List]
_pending_operations: Dict[Tuple[str, str], List]
models_ready: bool = ...
ready: bool = ...
def __init__(self, installed_apps: Optional[Union[List[AppConfigStub], List[str], Tuple]] = ...) -> None: ...
def populate(self, installed_apps: Union[List[AppConfigStub], List[str], Tuple] = ...) -> None: ...
def __init__(self, installed_apps: Optional[Iterable[Union[AppConfig, str]]] = ...) -> None: ...
def populate(self, installed_apps: Iterable[Union[AppConfig, str]] = ...) -> None: ...
def check_apps_ready(self) -> None: ...
def check_models_ready(self) -> None: ...
def get_app_configs(self) -> Iterable[AppConfig]: ...
@@ -31,9 +29,9 @@ class Apps:
def get_containing_app_config(self, object_name: str) -> Optional[AppConfig]: ...
def get_registered_model(self, app_label: str, model_name: str) -> Type[Model]: ...
def get_swappable_settings_name(self, to_string: str) -> Optional[str]: ...
def set_available_apps(self, available: List[str]) -> None: ...
def set_available_apps(self, available: Iterable[str]) -> None: ...
def unset_available_apps(self) -> None: ...
def set_installed_apps(self, installed: Union[List[str], Tuple[str]]) -> None: ...
def set_installed_apps(self, installed: Iterable[str]) -> None: ...
def unset_installed_apps(self) -> None: ...
def clear_cache(self) -> None: ...
def lazy_model_operation(self, function: Callable, *model_keys: Any) -> None: ...

View File

@@ -345,7 +345,7 @@ SESSION_COOKIE_PATH = "/"
SESSION_COOKIE_HTTPONLY = True
# 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 = "Lax"
SESSION_COOKIE_SAMESITE: Optional[str] = ...
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
@@ -413,7 +413,7 @@ CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = "/"
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_SAMESITE: Optional[str] = ...
CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN"
CSRF_TRUSTED_ORIGINS: List[str] = ...
CSRF_USE_SESSIONS = False

View File

@@ -5,10 +5,10 @@ from django.http.response import HttpResponse, HttpResponseBase
from django.urls import URLResolver, URLPattern
handler400: Callable[..., HttpResponse] = ...
handler403: Callable[..., HttpResponse] = ...
handler404: Callable[..., HttpResponse] = ...
handler500: Callable[..., HttpResponse] = ...
handler400: Union[str, Callable[..., HttpResponse]] = ...
handler403: Union[str, Callable[..., HttpResponse]] = ...
handler404: Union[str, Callable[..., HttpResponse]] = ...
handler500: Union[str, Callable[..., HttpResponse]] = ...
IncludedURLConf = Tuple[List[URLResolver], Optional[str], Optional[str]]

View File

@@ -1,15 +1,17 @@
from typing import Any, List, Union
from typing import Any, List, Union, Optional, Sequence
from django.contrib.admin.options import BaseModelAdmin
from django.core.checks.messages import Error
from django.core.checks.messages import CheckMessage, Error
from django.apps.config import AppConfig
_CheckError = Union[str, Error]
def check_admin_app(app_configs: None, **kwargs: Any) -> List[_CheckError]: ...
def check_admin_app(app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any) -> List[_CheckError]: ...
def check_dependencies(**kwargs: Any) -> List[_CheckError]: ...
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): ...

View File

@@ -1,5 +1,6 @@
from typing import Any, Callable, Optional, Type
from django.contrib.admin.sites import AdminSite
from django.db.models.base import Model
def register(*models: Type[Model], site: Optional[Any] = ...) -> 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

@@ -24,7 +24,7 @@ class SimpleListFilter(ListFilter):
parameter_name: Any = ...
lookup_choices: Any = ...
def value(self) -> Optional[str]: ...
def lookups(self, request: Any, model_admin: Any) -> None: ...
def lookups(self, request: Any, model_admin: Any) -> List[Tuple[Any, str]]: ...
class FieldListFilter(ListFilter):
field: Field = ...

View File

@@ -1,7 +1,7 @@
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.forms import BaseForm
from django.forms.utils import ErrorDict
from django.forms.widgets import Media, Widget
from django.utils.safestring import SafeText
@@ -23,7 +23,7 @@ class AdminForm:
readonly_fields: Any = ...
def __init__(
self,
form: AdminPasswordChangeForm,
form: BaseForm,
fieldsets: List[Tuple[None, Dict[str, List[str]]]],
prepopulated_fields: Dict[Any, Any],
readonly_fields: Optional[Iterable[Any]] = ...,

View File

@@ -1,5 +1,24 @@
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,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
Mapping,
TypeVar,
)
from django.forms.forms import BaseForm
from django.forms.models import BaseInlineFormSet
from typing_extensions import Literal, TypedDict
from django.contrib.admin.filters import ListFilter
from django.contrib.admin.models import LogEntry
@@ -7,7 +26,7 @@ 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.related import ForeignKey, ManyToManyField, RelatedField
@@ -26,8 +45,10 @@ from django.db.models.fields import Field
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,25 +58,43 @@ 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 = ...
class _OptionalFieldOpts(TypedDict, total=False):
classes: Sequence[str]
description: str
class _FieldOpts(_OptionalFieldOpts, total=True):
fields: Sequence[Union[str, Sequence[str]]]
# Workaround for mypy issue, a Sequence type should be preferred here.
# https://github.com/python/mypy/issues/8921
# _FieldsetSpec = Sequence[Tuple[Optional[str], _FieldOpts]]
_T = TypeVar("_T")
_ListOrTuple = Union[Tuple[_T, ...], List[_T]]
_FieldsetSpec = _ListOrTuple[Tuple[Optional[str], _FieldOpts]]
# 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: Sequence[Union[str, Sequence[str]]] = ...
exclude: Sequence[str] = ...
fieldsets: _FieldsetSpec = ...
form: Type[BaseForm] = ...
filter_vertical: Sequence[str] = ...
filter_horizontal: Sequence[str] = ...
radio_fields: Mapping[str, _Direction] = ...
prepopulated_fields: Mapping[str, Sequence[str]] = ...
formfield_overrides: Mapping[Type[Field], Mapping[str, Any]] = ...
readonly_fields: Sequence[Union[str, Callable[[_ModelT], Any]]] = ...
ordering: Sequence[str] = ...
sortable_by: Sequence[str] = ...
view_on_site: bool = ...
show_full_result_count: bool = ...
checks_class: Any = ...
def check(self, **kwargs: Any) -> List[Union[str, Error]]: ...
def check(self, **kwargs: Any) -> List[CheckMessage]: ...
def formfield_for_dbfield(
self, db_field: Field, request: Optional[HttpRequest], **kwargs: Any
) -> Optional[Field]: ...
@@ -72,28 +111,28 @@ class BaseModelAdmin:
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_view_on_site_url(self, obj: Optional[_ModelT] = ...) -> 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_exclude(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Any: ...
def get_fields(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Sequence[Union[Callable, str]]: ...
def get_fieldsets(
self, request: HttpRequest, obj: Optional[Model] = ...
self, request: HttpRequest, obj: Optional[_ModelT] = ...
) -> 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_readonly_fields(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Union[List[str], Tuple]: ...
def get_prepopulated_fields(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Dict[str, Tuple[str]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet: ...
def get_sortable_by(self, request: HttpRequest) -> Union[List[Callable], List[str], Tuple]: ...
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, obj: Optional[Model] = ...) -> 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_add_permission(self, request: HttpRequest) -> 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_module_permission(self, request: HttpRequest) -> bool: ...
class ModelAdmin(BaseModelAdmin):
list_display: Sequence[Union[str, Callable]] = ...
class ModelAdmin(BaseModelAdmin[_ModelT]):
list_display: Sequence[Union[str, Callable[[_ModelT], Any]]] = ...
list_display_links: Optional[Sequence[Union[str, Callable]]] = ...
list_filter: Sequence[Union[str, Type[ListFilter], Tuple[str, Type[ListFilter]]]] = ...
list_select_related: Union[bool, Sequence[str]] = ...
@@ -101,43 +140,44 @@ class ModelAdmin(BaseModelAdmin):
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: str = ...
change_form_template: str = ...
change_list_template: str = ...
delete_confirmation_template: str = ...
delete_selected_confirmation_template: str = ...
object_history_template: str = ...
popup_response_template: str = ...
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] = ...
model: Type[_ModelT] = ...
opts: Options = ...
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: Optional[AdminSite]) -> None: ...
def get_inlines(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> List[Type[InlineModelAdmin]]: ...
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: Any, obj: Optional[_ModelT] = ..., change: bool = ..., **kwargs: Any): ...
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_object(self, request: HttpRequest, object_id: str, from_field: None = ...) -> Optional[_ModelT]: ...
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_formsets_with_inlines(self, request: HttpRequest, obj: Optional[_ModelT] = ...) -> Iterator[Any]: ...
def get_paginator(
self,
request: HttpRequest,
@@ -146,10 +186,10 @@ 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 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) -> SafeText: ...
def get_actions(self, request: HttpRequest) -> OrderedDict: ...
def get_action_choices(
self, request: HttpRequest, default_choices: List[Tuple[str, str]] = ...
@@ -178,8 +218,8 @@ class ModelAdmin(BaseModelAdmin):
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_model(self, request: Any, 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: ...
@@ -190,19 +230,19 @@ class ModelAdmin(BaseModelAdmin):
add: bool = ...,
change: bool = ...,
form_url: str = ...,
obj: Optional[Any] = ...,
obj: Optional[_ModelT] = ...,
): ...
def response_add(
self, request: HttpRequest, obj: Model, post_url_continue: Optional[str] = ...
self, request: HttpRequest, obj: _ModelT, post_url_continue: Optional[str] = ...
) -> 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_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: ...
def response_action(self, request: HttpRequest, queryset: QuerySet) -> Optional[HttpResponseBase]: ...
def response_delete(self, request: HttpRequest, obj_display: str, obj_id: int) -> HttpResponse: ...
def render_delete_form(self, request: Any, context: Any): ...
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 changeform_view(
@@ -226,10 +266,10 @@ class ModelAdmin(BaseModelAdmin):
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: ...
class InlineModelAdmin(BaseModelAdmin):
model: Any = ...
fk_name: Any = ...
formset: Any = ...
class InlineModelAdmin(BaseModelAdmin[_ModelT]):
model: Type[_ModelT] = ...
fk_name: str = ...
formset: Type[BaseInlineFormSet] = ...
extra: int = ...
min_num: Optional[int] = ...
max_num: Optional[int] = ...
@@ -238,18 +278,18 @@ class InlineModelAdmin(BaseModelAdmin):
verbose_name_plural: Optional[str] = ...
can_delete: bool = ...
show_change_link: bool = ...
classes: Any = ...
admin_site: Any = ...
classes: Optional[Sequence[str]] = ...
admin_site: AdminSite = ...
parent_model: Any = ...
opts: Any = ...
has_registered_model: Any = ...
def __init__(self, parent_model: Union[Type[Model], Model], admin_site: AdminSite) -> None: ...
def __init__(self, parent_model: Union[Type[_ModelT], _ModelT], 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[_ModelT] = ..., **kwargs: Any) -> int: ...
def get_min_num(self, request: HttpRequest, obj: Optional[_ModelT] = ..., **kwargs: Any) -> Optional[int]: ...
def get_max_num(self, request: HttpRequest, obj: Optional[_ModelT] = ..., **kwargs: Any) -> Optional[int]: ...
def get_formset(self, request: Any, obj: Optional[_ModelT] = ..., **kwargs: Any): ...
class StackedInline(InlineModelAdmin): ...
class TabularInline(InlineModelAdmin): ...
class StackedInline(InlineModelAdmin[_ModelT]): ...
class TabularInline(InlineModelAdmin[_ModelT]): ...

View File

@@ -1,34 +1,51 @@
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.contrib.auth.forms import AuthenticationForm
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.db.models.query import QuerySet
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.core.checks import CheckMessage
all_sites: Any
if sys.version_info >= (3, 9):
from weakref import WeakSet
all_sites: WeakSet[AdminSite]
else:
from typing import MutableSet
all_sites: MutableSet[AdminSite]
_ActionCallback = Callable[[ModelAdmin, WSGIRequest, 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[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 = ...
_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: None) -> List[Any]: ...
def check(self, app_configs: Optional[Iterable[AppConfig]]) -> List[CheckMessage]: ...
def register(
self,
model_or_iterable: Union[Type[Model], Iterable[Type[Model]]],
@@ -37,30 +54,37 @@ 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: None = ...) -> 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): ...
def actions(self) -> Iterable[Tuple[str, _ActionCallback]]: ...
@property
def empty_value_display(self): ...
def empty_value_display(self) -> str: ...
@empty_value_display.setter
def empty_value_display(self, empty_value_display: Any) -> None: ...
def empty_value_display(self, empty_value_display: str) -> None: ...
def has_permission(self, request: WSGIRequest) -> bool: ...
def admin_view(self, view: Callable, cacheable: bool = ...) -> Callable: ...
def get_urls(self) -> List[URLResolver]: ...
@property
def urls(self) -> Tuple[List[URLResolver], str, str]: ...
def each_context(self, request: Any): ...
def password_change(self, request: WSGIRequest, extra_context: Dict[str, str] = ...) -> TemplateResponse: ...
def password_change_done(self, request: WSGIRequest, extra_context: None = ...) -> TemplateResponse: ...
def i18n_javascript(self, request: WSGIRequest, extra_context: Optional[Dict[Any, Any]] = ...) -> HttpResponse: ...
def logout(self, request: WSGIRequest, extra_context: None = ...) -> TemplateResponse: ...
def login(self, request: WSGIRequest, extra_context: None = ...) -> HttpResponse: ...
def each_context(self, request: WSGIRequest) -> Dict[str, Any]: ...
def password_change(
self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
def password_change_done(
self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
def i18n_javascript(self, request: WSGIRequest, extra_context: Optional[Dict[str, 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 _build_app_dict(self, request: WSGIRequest, label: Optional[str] = ...) -> Dict[str, Any]: ...
def get_app_list(self, request: WSGIRequest) -> List[Any]: ...
def index(self, request: WSGIRequest, extra_context: Optional[Dict[str, str]] = ...) -> TemplateResponse: ...
def app_index(self, request: WSGIRequest, app_label: str, extra_context: None = ...) -> TemplateResponse: ...
def index(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def app_index(
self, request: WSGIRequest, app_label: str, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
class DefaultAdminSite(LazyObject): ...
site: Any
site: AdminSite

View File

@@ -27,7 +27,7 @@ class ResultList(list):
def results(cl: ChangeList) -> Iterator[ResultList]: ...
def result_hidden_fields(cl: ChangeList) -> Iterator[BoundField]: ...
def result_list(
cl: ChangeList
cl: ChangeList,
) -> Dict[
str, Union[List[Dict[str, Optional[Union[int, str]]]], List[ResultList], List[BoundField], ChangeList, int]
]: ...

View File

@@ -9,12 +9,10 @@ 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.mixins import FieldCacheMixin
from django.db.models.fields.reverse_related import ManyToOneRel
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.forms import BaseForm
from django.utils.safestring import SafeText
from django.db.models.fields import Field, reverse_related
@@ -27,7 +25,7 @@ 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: QuerySet, request: WSGIRequest, admin_site: AdminSite
objs: Sequence[Optional[Model]], request: WSGIRequest, admin_site: AdminSite
) -> Tuple[List[Any], Dict[Any, Any], Set[Any], List[Any]]: ...
class NestedObjects(Collector):
@@ -41,22 +39,14 @@ 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 collect(
self,
objs: Union[Sequence[Optional[Model]], QuerySet],
source: Optional[Type[Model]] = ...,
source_attr: Optional[str] = ...,
**kwargs: Any
) -> None: ...
def related_objects(self, related: ManyToOneRel, objs: List[Model]) -> QuerySet: ...
def nested(self, format_callback: Callable = ...) -> Union[List[SafeText], List[int]]: ...
def can_fast_delete(self, *args: Any, **kwargs: Any) -> bool: ...
def related_objects(self, related: ManyToOneRel, objs: Sequence[Optional[Model]]) -> QuerySet: ...
def nested(self, format_callback: Callable = ...) -> List[Any]: ...
def model_format_dict(obj: Any): ...
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], Callable, Callable]: ...
) -> Tuple[Optional[Field], Any, Any]: ...
def label_for_field(
name: Union[Callable, str],
model: Type[Model],
@@ -65,16 +55,14 @@ def label_for_field(
form: Optional[BaseForm] = ...,
) -> Union[Tuple[Optional[str], Union[Callable, Type[str]]], str]: ...
def help_text_for_field(name: str, model: Type[Model]) -> str: ...
def display_for_field(
value: Any, field: Union[Field, reverse_related.OneToOneRel], empty_value_display: str
) -> 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: ...
class NotRelationField(Exception): ...
def get_model_from_relation(field: Union[Field, reverse_related.ForeignObjectRel]) -> Type[Model]: ...
def reverse_field_path(model: Type[Model], path: str) -> Tuple[Type[Model], str]: ...
def get_fields_from_path(model: Type[Model], path: str) -> List[Union[Field, FieldCacheMixin]]: ...
def get_fields_from_path(model: Type[Model], path: str) -> List[Field]: ...
def construct_change_message(
form: AdminPasswordChangeForm, formsets: None, add: bool
) -> List[Dict[str, Dict[str, List[str]]]]: ...

View File

@@ -1,7 +1,11 @@
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

@@ -81,9 +81,7 @@ class ChangeList:
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
) -> Union[List[Union[Combinable, str]], List[Union[OrderBy, 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 apply_select_related(self, qs: QuerySet) -> QuerySet: ...

View File

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

View File

@@ -2,17 +2,16 @@ 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.contrib.auth.models import AnonymousUser
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
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
@@ -23,12 +22,12 @@ def load_backend(path: str) -> ModelBackend: ...
def get_backends() -> List[ModelBackend]: ...
def authenticate(request: Any = ..., **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(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,29 +1,41 @@
from typing import Any, Optional, Set, Union
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User, Permission
from django.db.models.base import Model
from django.http.request import HttpRequest
_AnyUser = Union[Model, AnonymousUser]
UserModel: Any
class ModelBackend:
class BaseBackend:
def authenticate(
self, request: Any, username: Optional[Union[int, str]] = ..., password: Optional[str] = ..., **kwargs: Any
self, request: HttpRequest, username: Optional[str] = ..., password: Optional[str] = ..., **kwargs: Any
) -> Optional[AbstractBaseUser]: ...
def user_can_authenticate(self, user: Optional[AbstractBaseUser]) -> bool: ...
def get_user_permissions(self, user_obj: AbstractBaseUser, obj: None = ...) -> Set[str]: ...
def get_group_permissions(self, user_obj: AbstractBaseUser, obj: None = ...) -> Set[str]: ...
def get_all_permissions(self, user_obj: AbstractBaseUser, obj: Optional[str] = ...) -> Set[str]: ...
def has_perm(
self, user_obj: Union[AbstractBaseUser, AnonymousUser], perm: str, obj: Optional[str] = ...
) -> bool: ...
def has_module_perms(self, user_obj: Union[AbstractBaseUser, AnonymousUser], app_label: str) -> bool: ...
def get_user(self, user_id: int) -> 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]: ...
def get_all_permissions(self, user_obj: _AnyUser, obj: Optional[Model] = ...) -> Set[str]: ...
def has_perm(self, user_obj: _AnyUser, perm: str, obj: Optional[Model] = ...) -> bool: ...
class ModelBackend(BaseBackend):
def has_module_perms(self, user_obj: _AnyUser, app_label: str) -> bool: ...
def user_can_authenticate(self, user: Optional[_AnyUser]) -> bool: ...
def with_perm(
self,
perm: Union[str, Permission],
is_active: bool = ...,
include_superusers: bool = ...,
obj: Optional[Model] = ...,
): ...
class AllowAllUsersModelBackend(ModelBackend): ...
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: User) -> User: ...
class AllowAllUsersRemoteUserBackend(RemoteUserBackend): ...

View File

@@ -1,9 +1,16 @@
from typing import Any, Optional, Tuple, List, overload, TypeVar
import sys
from typing import Any, Optional, Tuple, List, overload, TypeVar, Union
from django.db.models.base import Model
from django.db.models.expressions import Combinable
from django.db.models.fields import BooleanField
from django.db import models
if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal
_T = TypeVar("_T", bound=Model)
class BaseUserManager(models.Manager[_T]):
@@ -13,18 +20,18 @@ class BaseUserManager(models.Manager[_T]):
def get_by_natural_key(self, username: Optional[str]) -> _T: ...
class AbstractBaseUser(models.Model):
REQUIRED_FIELDS: List[str] = ...
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
REQUIRED_FIELDS: List[str] = ...
class Meta: ...
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 set_password(self, raw_password: Optional[str]) -> None: ...
def is_authenticated(self) -> Literal[True]: ...
def set_password(self, raw_password: str) -> None: ...
def check_password(self, raw_password: str) -> bool: ...
def set_unusable_password(self) -> None: ...
def has_usable_password(self) -> bool: ...

View File

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

View File

@@ -1,13 +1,21 @@
from typing import Callable, List, Optional, Set, Union
from typing import Callable, List, Optional, Set, Union, TypeVar, overload
from django.contrib.auth import REDIRECT_FIELD_NAME as REDIRECT_FIELD_NAME # noqa: F401
from django.http.response import HttpResponseBase
from django.contrib.auth.models import AbstractUser
_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[[AbstractUser], 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: ...
) -> Callable[[_VIEW], _VIEW]: ...

View File

@@ -1,7 +1,7 @@
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.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
@@ -86,6 +86,6 @@ class AdminPasswordChangeForm(forms.Form):
password1: Any = ...
password2: Any = ...
user: User = ...
def __init__(self, user: AbstractUser, *args: Any, **kwargs: Any) -> None: ...
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: ...

View File

@@ -1,4 +1,4 @@
from typing import Any, Callable, List
from typing import Any, Callable, List, Optional
from django import http
from django.http.response import HttpResponse, HttpResponseRedirect
@@ -23,6 +23,6 @@ class PermissionRequiredMixin(AccessMixin):
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
class UserPassesTestMixin(AccessMixin):
def test_func(self) -> None: ...
def test_func(self) -> Optional[bool]: ...
def get_test_func(self) -> Callable: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...

View File

@@ -1,5 +1,7 @@
from typing import Any, Collection, Optional, Set, Tuple, Type, TypeVar
import sys
from typing import Any, Collection, 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.validators import UnicodeUsernameValidator
from django.contrib.contenttypes.models import ContentType
@@ -8,22 +10,33 @@ from django.db.models.manager import EmptyManager
from django.db import models
if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal
_AnyUser = Union[Model, "AnonymousUser"]
def update_last_login(sender: Type[AbstractBaseUser], user: AbstractBaseUser, **kwargs: Any) -> None: ...
class PermissionManager(models.Manager):
class PermissionManager(models.Manager["Permission"]):
def get_by_natural_key(self, codename: str, app_label: str, model: str) -> Permission: ...
class Permission(models.Model):
content_type_id: int
objects: PermissionManager
name = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
codename = models.CharField(max_length=100)
def natural_key(self) -> Tuple[str, str, str]: ...
class GroupManager(models.Manager):
class GroupManager(models.Manager["Group"]):
def get_by_natural_key(self, name: str) -> Group: ...
class Group(models.Model):
objects: GroupManager
name = models.CharField(max_length=150)
permissions = models.ManyToManyField(Permission)
def natural_key(self): ...
@@ -37,15 +50,24 @@ class UserManager(BaseUserManager[_T]):
def create_superuser(
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]] = ...,
obj: Optional[Model] = ...,
): ...
class PermissionsMixin(models.Model):
is_superuser = models.BooleanField()
groups: models.ManyToManyField = models.ManyToManyField(Group)
user_permissions: models.ManyToManyField = models.ManyToManyField(Permission)
def get_group_permissions(self, obj: None = ...) -> Set[str]: ...
def get_all_permissions(self, obj: Optional[str] = ...) -> Set[str]: ...
def has_perm(self, perm: str, obj: Optional[str] = ...) -> bool: ...
def has_perms(self, perm_list: Collection[str], obj: None = ...) -> bool: ...
groups = models.ManyToManyField(Group)
user_permissions = models.ManyToManyField(Permission)
def get_user_permissions(self, obj: Optional[_AnyUser] = ...) -> Set[str]: ...
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_module_perms(self, app_label: str) -> bool: ...
class AbstractUser(AbstractBaseUser, PermissionsMixin): # type: ignore
@@ -82,13 +104,14 @@ class AnonymousUser:
def groups(self) -> EmptyManager: ...
@property
def user_permissions(self) -> EmptyManager: ...
def get_group_permissions(self, obj: None = ...) -> Set[Any]: ...
def get_all_permissions(self, obj: Any = ...) -> Set[str]: ...
def has_perm(self, perm: str, obj: None = ...) -> bool: ...
def has_perms(self, perm_list: Collection[str], obj: None = ...) -> bool: ...
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_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

@@ -1,3 +1,4 @@
from datetime import date
from typing import Any, Optional
from django.contrib.auth.base_user import AbstractBaseUser
@@ -5,7 +6,12 @@ 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) -> str: ...
def _make_hash_value(self, user: AbstractBaseUser, timestamp: int) -> str: ...
def _num_days(self, dt: date) -> float: ...
def _today(self) -> date: ...
default_token_generator: Any

View File

@@ -1,6 +1,7 @@
from typing import Any, Optional, Set
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.forms import AuthenticationForm
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.http.response import HttpResponseRedirect
@@ -14,7 +15,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 = ...
@@ -55,6 +56,7 @@ class PasswordResetDoneView(PasswordContextMixin, TemplateView):
class PasswordResetConfirmView(PasswordContextMixin, FormView):
post_reset_login: bool = ...
post_reset_login_backend: Any = ...
reset_url_token: str = ...
title: Any = ...
token_generator: Any = ...
validlink: bool = ...

View File

@@ -1,4 +1,6 @@
from typing import Any, List
from typing import Any, List, Optional, Sequence
def check_generic_foreign_keys(app_configs: None = ..., **kwargs: Any) -> List[Any]: ...
def check_model_name_lengths(app_configs: None = ..., **kwargs: Any) -> List[Any]: ...
from django.apps.config import AppConfig
def check_generic_foreign_keys(app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...
def check_model_name_lengths(app_configs: Optional[Sequence[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...

View File

@@ -1,7 +1,7 @@
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.mixins import FieldCacheMixin
@@ -41,7 +41,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] = ...
@@ -83,7 +83,6 @@ class GenericRelation(ForeignObject):
def resolve_related_fields(self) -> List[Tuple[PositiveIntegerField, 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_content_type(self) -> ContentType: ...
def get_extra_restriction(
self, where_class: Type[WhereNode], alias: Optional[str], remote_alias: str

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,45 @@
from django.contrib.admin import ModelAdmin as ModelAdmin
from typing import Any
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: bool = ...
max_resolution: bool = ...
max_extent: 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): ...
def formfield_for_dbfield(self, db_field: Any, request: Any, **kwargs: Any): ...
def get_map_widget(self, db_field: Any): ...
class OSMGeoAdmin(GeoModelAdmin):
map_template: str = ...
num_zoom: int = ...
map_srid: Any = ...
point_zoom: Any = ...

View File

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

View File

@@ -0,0 +1,7 @@
from django.apps import AppConfig as AppConfig
from typing import Any
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): ...
@property
def supports_contained_lookup(self): ...
@property
def supports_crosses_lookup(self): ...
@property
def supports_distances_lookups(self): ...
@property
def supports_dwithin_lookup(self): ...
@property
def supports_relate_lookup(self): ...
@property
def supports_isvalid_lookup(self): ...
@property
def supports_collect_aggr(self): ...
@property
def supports_extent_aggr(self): ...
@property
def supports_make_line_aggr(self): ...
@property
def supports_union_aggr(self): ...
def __getattr__(self, name: Any): ...

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,14 @@
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 = ...
def supports_empty_geometry_collection(self): ...
def supports_geometry_field_unique_index(self): ...

View File

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

View File

@@ -0,0 +1,17 @@
from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations as BaseSpatialOperations
from django.db.backends.mysql.operations import DatabaseOperations as DatabaseOperations
from typing import Any
class MySQLOperations(BaseSpatialOperations, DatabaseOperations):
mysql: bool = ...
name: str = ...
geom_func_prefix: str = ...
Adapter: Any = ...
def select(self): ...
def from_text(self): ...
def gis_operators(self): ...
disallowed_aggregates: Any = ...
def unsupported_functions(self): ...
def geo_db_type(self, f: Any): ...
def get_distance(self, f: Any, value: Any, lookup_type: Any): ...
def get_geometry_converter(self, expression: Any): ...

View File

@@ -0,0 +1,16 @@
from django.db.backends.mysql.schema import DatabaseSchemaEditor as DatabaseSchemaEditor
from typing import Any
logger: Any
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): ...
def column_sql(self, model: Any, field: Any, include_default: bool = ...): ...
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,8 @@
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from typing import Any
class OracleSpatialAdapter(WKTAdapter):
input_size: Any = ...
wkt: Any = ...
srid: Any = ...
def __init__(self, geom: Any) -> None: ...

View File

@@ -0,0 +1,8 @@
from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper
from typing import Any
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,6 @@
from django.db.backends.oracle.introspection import DatabaseIntrospection as DatabaseIntrospection
from typing import Any
class OracleIntrospection(DatabaseIntrospection):
def data_types_reverse(self): ...
def get_geometry_type(self, table_name: Any, description: Any): ...

View File

@@ -0,0 +1,30 @@
from django.contrib.gis.db import models as models
from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin as SpatialRefSysMixin
from typing import Any
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): ...
@classmethod
def geom_col_name(cls): ...
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): ...

View File

@@ -0,0 +1,42 @@
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
from typing import Any
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: ...
def as_sql(self, connection: Any, lookup: Any, template_params: Any, sql_params: Any): ...
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): ...
def geo_db_type(self, f: Any): ...
def get_distance(self, f: Any, value: Any, lookup_type: Any): ...
def get_geom_placeholder(self, f: Any, value: Any, compiler: Any): ...
def spatial_aggregate_name(self, agg_name: Any): ...
def geometry_columns(self): ...
def spatial_ref_sys(self): ...
def modify_insert_params(self, placeholder: Any, params: Any): ...
def get_geometry_converter(self, expression: Any): ...
def get_area_att_for_field(self, field: Any): ...

View File

@@ -0,0 +1,18 @@
from django.db.backends.oracle.schema import DatabaseSchemaEditor
from typing import Any
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): ...
def column_sql(self, model: Any, field: Any, include_default: bool = ...): ...
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: ...

View File

@@ -0,0 +1,13 @@
from typing import Any
class PostGISAdapter:
is_geometry: Any = ...
ewkb: Any = ...
srid: Any = ...
geography: Any = ...
def __init__(self, obj: Any, geography: bool = ...) -> None: ...
def __conform__(self, proto: Any): ...
def __eq__(self, other: Any) -> Any: ...
def __hash__(self) -> Any: ...
def prepare(self, conn: Any) -> None: ...
def getquoted(self): ...

View File

@@ -0,0 +1,10 @@
from django.db.backends.postgresql.base import DatabaseWrapper as Psycopg2DatabaseWrapper
from typing import Any
class DatabaseWrapper(Psycopg2DatabaseWrapper):
SchemaEditorClass: Any = ...
features: Any = ...
ops: Any = ...
introspection: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def prepare_database(self) -> None: ...

View File

@@ -0,0 +1,9 @@
from typing import Any
GDAL_TO_POSTGIS: Any
POSTGIS_TO_GDAL: Any
POSTGIS_HEADER_STRUCTURE: str
GDAL_TO_STRUCT: Any
STRUCT_SIZE: Any
BANDTYPE_PIXTYPE_MASK: int
BANDTYPE_FLAG_HASNODATA: Any

View File

@@ -0,0 +1,9 @@
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures as BaseSpatialFeatures
from django.db.backends.postgresql.features import DatabaseFeatures as Psycopg2DatabaseFeatures
class DatabaseFeatures(BaseSpatialFeatures, Psycopg2DatabaseFeatures):
supports_3d_storage: bool = ...
supports_3d_functions: bool = ...
supports_left_right_lookups: bool = ...
supports_raster: bool = ...
supports_empty_geometries: bool = ...

View File

@@ -0,0 +1,8 @@
from django.db.backends.postgresql.introspection import DatabaseIntrospection as DatabaseIntrospection
from typing import Any
class PostGISIntrospection(DatabaseIntrospection):
postgis_oid_lookup: Any = ...
ignored_tables: Any = ...
def get_field_type(self, data_type: Any, description: Any): ...
def get_geometry_type(self, table_name: Any, description: Any): ...

View File

@@ -0,0 +1,33 @@
from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin as SpatialRefSysMixin
from django.db import models as models
from typing import Any
class PostGISGeometryColumns(models.Model):
f_table_catalog: Any = ...
f_table_schema: Any = ...
f_table_name: Any = ...
f_geometry_column: Any = ...
coord_dimension: Any = ...
srid: Any = ...
type: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@classmethod
def table_name_col(cls): ...
@classmethod
def geom_col_name(cls): ...
class PostGISSpatialRefSys(models.Model, SpatialRefSysMixin):
srid: Any = ...
auth_name: Any = ...
auth_srid: Any = ...
srtext: Any = ...
proj4text: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@property
def wkt(self): ...

View File

@@ -0,0 +1,56 @@
from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.db.backends.postgresql.operations import DatabaseOperations
from django.db.models import Func
from typing import Any
BILATERAL: str
class PostGISOperator(SpatialOperator):
geography: Any = ...
raster: Any = ...
def __init__(self, geography: bool = ..., raster: bool = ..., **kwargs: Any) -> None: ...
def as_sql(self, connection: Any, lookup: Any, template_params: Any, *args: Any): ...
def check_raster(self, lookup: Any, template_params: Any): ...
class ST_Polygon(Func):
function: str = ...
def __init__(self, expr: Any) -> None: ...
def output_field(self): ...
class PostGISOperations(BaseSpatialOperations, DatabaseOperations):
name: str = ...
postgis: bool = ...
geography: bool = ...
geom_func_prefix: str = ...
Adapter: Any = ...
collect: Any = ...
extent: Any = ...
extent3d: Any = ...
length3d: Any = ...
makeline: Any = ...
perimeter3d: Any = ...
unionagg: Any = ...
gis_operators: Any = ...
unsupported_functions: Any = ...
select: str = ...
select_extent: Any = ...
def function_names(self): ...
def spatial_version(self): ...
def geo_db_type(self, f: Any): ...
def get_distance(self, f: Any, dist_val: Any, lookup_type: Any): ...
def get_geom_placeholder(self, f: Any, value: Any, compiler: Any): ...
def postgis_geos_version(self): ...
def postgis_lib_version(self): ...
def postgis_proj_version(self): ...
def postgis_version(self): ...
def postgis_full_version(self): ...
def postgis_version_tuple(self): ...
def proj_version_tuple(self): ...
def spatial_aggregate_name(self, agg_name: Any): ...
def geometry_columns(self): ...
def spatial_ref_sys(self): ...
def parse_raster(self, value: Any): ...
def distance_expr_for_lookup(self, lhs: Any, rhs: Any, **kwargs: Any): ...
def get_geometry_converter(self, expression: Any): ...
def get_area_att_for_field(self, field: Any): ...

View File

@@ -0,0 +1,7 @@
from typing import Any
def pack(structure: Any, data: Any): ...
def unpack(structure: Any, data: Any): ...
def chunk(data: Any, index: Any): ...
def from_pgraster(data: Any): ...
def to_pgraster(rast: Any): ...

View File

@@ -0,0 +1,10 @@
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from typing import Any
class PostGISSchemaEditor(DatabaseSchemaEditor):
geom_index_type: str = ...
geom_index_ops_nd: str = ...
rast_index_wrapper: str = ...
sql_alter_column_to_3d: str = ...
sql_alter_column_to_2d: str = ...
def geo_quote_name(self, name: Any): ...

View File

@@ -0,0 +1,5 @@
from django.contrib.gis.db.backends.base.adapter import WKTAdapter as WKTAdapter
from typing import Any
class SpatiaLiteAdapter(WKTAdapter):
def __conform__(self, protocol: Any): ...

View File

@@ -0,0 +1,13 @@
from django.db.backends.sqlite3.base import DatabaseWrapper as SQLiteDatabaseWrapper
from typing import Any
class DatabaseWrapper(SQLiteDatabaseWrapper):
SchemaEditorClass: Any = ...
client_class: Any = ...
features_class: Any = ...
introspection_class: Any = ...
ops_class: Any = ...
lib_spatialite_paths: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def get_new_connection(self, conn_params: Any): ...
def prepare_database(self) -> None: ...

View File

@@ -0,0 +1,4 @@
from django.db.backends.sqlite3.client import DatabaseClient as DatabaseClient
class SpatiaLiteClient(DatabaseClient):
executable_name: str = ...

View File

@@ -0,0 +1,6 @@
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures as BaseSpatialFeatures
from django.db.backends.sqlite3.features import DatabaseFeatures as SQLiteDatabaseFeatures
class DatabaseFeatures(BaseSpatialFeatures, SQLiteDatabaseFeatures):
supports_3d_storage: bool = ...
def supports_area_geodetic(self): ...

View File

@@ -0,0 +1,13 @@
from django.db.backends.sqlite3.introspection import (
DatabaseIntrospection as DatabaseIntrospection,
FlexibleFieldLookupDict as FlexibleFieldLookupDict,
)
from typing import Any
class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):
base_data_types_reverse: Any = ...
class SpatiaLiteIntrospection(DatabaseIntrospection):
data_types_reverse: Any = ...
def get_geometry_type(self, table_name: Any, description: Any): ...
def get_constraints(self, cursor: Any, table_name: Any): ...

View File

@@ -0,0 +1,33 @@
from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin as SpatialRefSysMixin
from django.db import models as models
from typing import Any
class SpatialiteGeometryColumns(models.Model):
f_table_name: Any = ...
f_geometry_column: Any = ...
coord_dimension: Any = ...
srid: Any = ...
spatial_index_enabled: Any = ...
type: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@classmethod
def table_name_col(cls): ...
@classmethod
def geom_col_name(cls): ...
class SpatialiteSpatialRefSys(models.Model, SpatialRefSysMixin):
srid: Any = ...
auth_name: Any = ...
auth_srid: Any = ...
ref_sys_name: Any = ...
proj4text: Any = ...
srtext: Any = ...
class Meta:
app_label: str = ...
db_table: str = ...
managed: bool = ...
@property
def wkt(self): ...

View File

@@ -0,0 +1,33 @@
from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator as SpatialOperator
from django.db.backends.sqlite3.operations import DatabaseOperations
from typing import Any
class SpatialiteNullCheckOperator(SpatialOperator):
def as_sql(self, connection: Any, lookup: Any, template_params: Any, sql_params: Any): ...
class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations):
name: str = ...
spatialite: bool = ...
Adapter: Any = ...
collect: str = ...
extent: str = ...
makeline: str = ...
unionagg: str = ...
gis_operators: Any = ...
disallowed_aggregates: Any = ...
select: str = ...
function_names: Any = ...
def unsupported_functions(self): ...
def spatial_version(self): ...
def geo_db_type(self, f: Any) -> None: ...
def get_distance(self, f: Any, value: Any, lookup_type: Any): ...
def geos_version(self): ...
def proj4_version(self): ...
def lwgeom_version(self): ...
def spatialite_version(self): ...
def spatialite_version_tuple(self): ...
def spatial_aggregate_name(self, agg_name: Any): ...
def geometry_columns(self): ...
def spatial_ref_sys(self): ...
def get_geometry_converter(self, expression: Any): ...

View File

@@ -0,0 +1,24 @@
from django.db.backends.sqlite3.schema import DatabaseSchemaEditor as DatabaseSchemaEditor
from typing import Any
class SpatialiteSchemaEditor(DatabaseSchemaEditor):
sql_add_geometry_column: str = ...
sql_add_spatial_index: str = ...
sql_drop_spatial_index: str = ...
sql_recover_geometry_metadata: str = ...
sql_remove_geometry_metadata: str = ...
sql_discard_geometry_columns: str = ...
sql_update_geometry_columns: str = ...
geometry_tables: Any = ...
geometry_sql: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def geo_quote_name(self, name: Any): ...
def column_sql(self, model: Any, field: Any, include_default: bool = ...): ...
def remove_geometry_metadata(self, model: Any, field: Any) -> None: ...
def create_model(self, model: Any) -> None: ...
def delete_model(self, model: Any, **kwargs: Any) -> None: ...
def add_field(self, model: Any, field: Any) -> None: ...
def remove_field(self, model: Any, field: Any) -> None: ...
def alter_db_table(
self, model: Any, old_db_table: Any, new_db_table: Any, disable_constraints: bool = ...
) -> None: ...

View File

@@ -0,0 +1,10 @@
from typing import Any, Optional
class SpatialOperator:
sql_template: Any = ...
op: Any = ...
func: Any = ...
def __init__(self, op: Optional[Any] = ..., func: Optional[Any] = ...) -> None: ...
@property
def default_template(self): ...
def as_sql(self, connection: Any, lookup: Any, template_params: Any, sql_params: Any): ...

View File

@@ -1,6 +1,8 @@
# noqa: F401
from django.db.models import *
from .fields import (
from django.contrib.gis.db.models.aggregates import *
from django.contrib.gis.db.models.fields import (
GeometryCollectionField as GeometryCollectionField,
GeometryField as GeometryField,
LineStringField as LineStringField,
MultiLineStringField as MultiLineStringField,
@@ -8,6 +10,5 @@ from .fields import (
MultiPolygonField as MultiPolygonField,
PointField as PointField,
PolygonField as PolygonField,
GeometryCollectionField as GeometryCollectionField,
RasterField as RasterField,
)

View File

@@ -0,0 +1,37 @@
from django.db.models import Aggregate
from typing import Any, Optional
class GeoAggregate(Aggregate):
function: Any = ...
is_extent: bool = ...
def output_field(self): ...
def as_sql(self, compiler: Any, connection: Any, function: Optional[Any] = ..., **extra_context: Any): ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
def resolve_expression(
self,
query: Optional[Any] = ...,
allow_joins: bool = ...,
reuse: Optional[Any] = ...,
summarize: bool = ...,
for_save: bool = ...,
): ...
class Collect(GeoAggregate):
name: str = ...
output_field_class: Any = ...
class Extent(GeoAggregate):
name: str = ...
def __init__(self, expression: Any, **extra: Any) -> None: ...
class Extent3D(GeoAggregate):
name: str = ...
def __init__(self, expression: Any, **extra: Any) -> None: ...
class MakeLine(GeoAggregate):
name: str = ...
output_field_class: Any = ...
class Union(GeoAggregate):
name: str = ...
output_field_class: Any = ...

View File

@@ -1,9 +1,6 @@
from typing import Any, Iterable, NamedTuple, Optional, TypeVar, Union, Tuple
from django.db.models.fields import Field, _ErrorMessagesToOverride, _FieldChoices, _ValidatorCallable
_Connection = Any
# __set__ value type
_ST = TypeVar("_ST")
# __get__ return type
@@ -15,7 +12,7 @@ class SRIDCacheEntry(NamedTuple):
geodetic: bool
spheroid: str
def get_srid_info(srid: int, connection: _Connection) -> SRIDCacheEntry: ...
def get_srid_info(srid: int, connection: Any) -> SRIDCacheEntry: ...
class BaseSpatialField(Field[_ST, _GT]):
def __init__(
@@ -44,12 +41,25 @@ class BaseSpatialField(Field[_ST, _GT]):
validators: Iterable[_ValidatorCallable] = ...,
error_messages: Optional[_ErrorMessagesToOverride] = ...,
): ...
def spheroid(self, connection: _Connection) -> str: ...
def units(self, connection: _Connection) -> Any: ...
def units_name(self, connection: _Connection) -> str: ...
def geodetic(self, connection: _Connection) -> bool: ...
def deconstruct(self): ...
def db_type(self, connection: Any): ...
def spheroid(self, connection: Any): ...
def units(self, connection: Any): ...
def units_name(self, connection: Any): ...
def geodetic(self, connection: Any): ...
def get_placeholder(self, value: Any, compiler: Any, connection: Any): ...
def get_srid(self, obj: Any): ...
def get_db_prep_value(self, value: Any, connection: Any, *args: Any, **kwargs: Any): ...
def get_raster_prep_value(self, value: Any, is_candidate: Any): ...
def get_prep_value(self, value: Any): ...
class GeometryField(BaseSpatialField):
description: Any = ...
form_class: Any = ...
geom_type: str = ...
geom_class: Any = ...
dim: Any = ...
geography: Any = ...
def __init__(
self,
verbose_name: Optional[Union[str, bytes]] = ...,
@@ -80,12 +90,61 @@ class GeometryField(BaseSpatialField):
validators: Iterable[_ValidatorCallable] = ...,
error_messages: Optional[_ErrorMessagesToOverride] = ...,
): ...
def deconstruct(self): ...
def formfield(self, **kwargs: Any): ...
def select_format(self, compiler: Any, sql: Any, params: Any): ...
class PointField(GeometryField): ...
class LineStringField(GeometryField): ...
class PolygonField(GeometryField): ...
class MultiPointField(GeometryField): ...
class MultiLineStringField(GeometryField): ...
class MultiPolygonField(GeometryField): ...
class GeometryCollectionField(GeometryField): ...
class RasterField(BaseSpatialField): ...
class PointField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class LineStringField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class PolygonField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class MultiPointField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class MultiLineStringField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class MultiPolygonField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class GeometryCollectionField(GeometryField):
geom_type: str = ...
geom_class: Any = ...
form_class: Any = ...
description: Any = ...
class ExtentField(Field):
description: Any = ...
def get_internal_type(self): ...
def select_format(self, compiler: Any, sql: Any, params: Any): ...
class RasterField(BaseSpatialField):
description: Any = ...
geom_type: str = ...
geography: bool = ...
def db_type(self, connection: Any): ...
def from_db_value(self, value: Any, expression: Any, connection: Any): ...
def get_transform(self, name: Any): ...

View File

@@ -0,0 +1,168 @@
from django.db.models import Func, Transform as StandardTransform
from typing import Any, Optional
NUMERIC_TYPES: Any
class GeoFuncMixin:
function: Any = ...
geom_param_pos: Any = ...
def __init__(self, *expressions: Any, **extra: Any) -> None: ...
def geo_field(self): ...
def as_sql(self, compiler: Any, connection: Any, function: Optional[Any] = ..., **extra_context: Any): ...
def resolve_expression(self, *args: Any, **kwargs: Any): ...
class GeoFunc(GeoFuncMixin, Func): ...
class GeomOutputGeoFunc(GeoFunc):
def output_field(self): ...
class SQLiteDecimalToFloatMixin:
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class OracleToleranceMixin:
tolerance: float = ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Area(OracleToleranceMixin, GeoFunc):
arity: int = ...
def output_field(self): ...
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Azimuth(GeoFunc):
output_field: Any = ...
arity: int = ...
geom_param_pos: Any = ...
class AsGeoJSON(GeoFunc):
output_field: Any = ...
def __init__(
self, expression: Any, bbox: bool = ..., crs: bool = ..., precision: int = ..., **extra: Any
) -> None: ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
class AsGML(GeoFunc):
geom_param_pos: Any = ...
output_field: Any = ...
def __init__(self, expression: Any, version: int = ..., precision: int = ..., **extra: Any) -> None: ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
class AsKML(GeoFunc):
output_field: Any = ...
def __init__(self, expression: Any, precision: int = ..., **extra: Any) -> None: ...
class AsSVG(GeoFunc):
output_field: Any = ...
def __init__(self, expression: Any, relative: bool = ..., precision: int = ..., **extra: Any) -> None: ...
class AsWKB(GeoFunc):
output_field: Any = ...
arity: int = ...
class AsWKT(GeoFunc):
output_field: Any = ...
arity: int = ...
class BoundingCircle(OracleToleranceMixin, GeoFunc):
def __init__(self, expression: Any, num_seg: int = ..., **extra: Any) -> None: ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Centroid(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
class Difference(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
geom_param_pos: Any = ...
class DistanceResultMixin:
def output_field(self): ...
def source_is_geography(self): ...
class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
geom_param_pos: Any = ...
spheroid: Any = ...
def __init__(self, expr1: Any, expr2: Any, spheroid: Optional[Any] = ..., **extra: Any) -> None: ...
def as_postgresql(self, compiler: Any, connection: Any, **extra_context: Any): ...
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Envelope(GeomOutputGeoFunc):
arity: int = ...
class ForcePolygonCW(GeomOutputGeoFunc):
arity: int = ...
class GeoHash(GeoFunc):
output_field: Any = ...
def __init__(self, expression: Any, precision: Optional[Any] = ..., **extra: Any) -> None: ...
def as_mysql(self, compiler: Any, connection: Any, **extra_context: Any): ...
class GeometryDistance(GeoFunc):
output_field: Any = ...
arity: int = ...
function: str = ...
arg_joiner: str = ...
geom_param_pos: Any = ...
class Intersection(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
geom_param_pos: Any = ...
class IsValid(OracleToleranceMixin, GeoFuncMixin, StandardTransform):
lookup_name: str = ...
output_field: Any = ...
def as_oracle(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
spheroid: Any = ...
def __init__(self, expr1: Any, spheroid: bool = ..., **extra: Any) -> None: ...
def as_postgresql(self, compiler: Any, connection: Any, **extra_context: Any): ...
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class LineLocatePoint(GeoFunc):
output_field: Any = ...
arity: int = ...
geom_param_pos: Any = ...
class MakeValid(GeomOutputGeoFunc): ...
class MemSize(GeoFunc):
output_field: Any = ...
arity: int = ...
class NumGeometries(GeoFunc):
output_field: Any = ...
arity: int = ...
class NumPoints(GeoFunc):
output_field: Any = ...
arity: int = ...
class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
arity: int = ...
def as_postgresql(self, compiler: Any, connection: Any, **extra_context: Any): ...
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class PointOnSurface(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
class Reverse(GeoFunc):
arity: int = ...
class Scale(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc):
def __init__(self, expression: Any, x: Any, y: Any, z: float = ..., **extra: Any) -> None: ...
class SnapToGrid(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc):
def __init__(self, expression: Any, *args: Any, **extra: Any) -> None: ...
class SymDifference(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
geom_param_pos: Any = ...
class Transform(GeomOutputGeoFunc):
def __init__(self, expression: Any, srid: Any, **extra: Any) -> None: ...
class Translate(Scale):
def as_sqlite(self, compiler: Any, connection: Any, **extra_context: Any): ...
class Union(OracleToleranceMixin, GeomOutputGeoFunc):
arity: int = ...
geom_param_pos: Any = ...

View File

@@ -0,0 +1,126 @@
from django.db.models import Lookup, Transform
from typing import Any
class RasterBandTransform(Transform): ...
class GISLookup(Lookup):
sql_template: Any = ...
transform_func: Any = ...
distance: bool = ...
band_rhs: Any = ...
band_lhs: Any = ...
template_params: Any = ...
def __init__(self, lhs: Any, rhs: Any) -> None: ...
def process_rhs_params(self) -> None: ...
def process_band_indices(self, only_lhs: bool = ...) -> None: ...
def get_db_prep_lookup(self, value: Any, connection: Any): ...
rhs: Any = ...
def process_rhs(self, compiler: Any, connection: Any): ...
def get_rhs_op(self, connection: Any, rhs: Any): ...
def as_sql(self, compiler: Any, connection: Any): ...
class OverlapsLeftLookup(GISLookup):
lookup_name: str = ...
class OverlapsRightLookup(GISLookup):
lookup_name: str = ...
class OverlapsBelowLookup(GISLookup):
lookup_name: str = ...
class OverlapsAboveLookup(GISLookup):
lookup_name: str = ...
class LeftLookup(GISLookup):
lookup_name: str = ...
class RightLookup(GISLookup):
lookup_name: str = ...
class StrictlyBelowLookup(GISLookup):
lookup_name: str = ...
class StrictlyAboveLookup(GISLookup):
lookup_name: str = ...
class SameAsLookup(GISLookup):
lookup_name: str = ...
class BBContainsLookup(GISLookup):
lookup_name: str = ...
class BBOverlapsLookup(GISLookup):
lookup_name: str = ...
class ContainedLookup(GISLookup):
lookup_name: str = ...
class ContainsLookup(GISLookup):
lookup_name: str = ...
class ContainsProperlyLookup(GISLookup):
lookup_name: str = ...
class CoveredByLookup(GISLookup):
lookup_name: str = ...
class CoversLookup(GISLookup):
lookup_name: str = ...
class CrossesLookup(GISLookup):
lookup_name: str = ...
class DisjointLookup(GISLookup):
lookup_name: str = ...
class EqualsLookup(GISLookup):
lookup_name: str = ...
class IntersectsLookup(GISLookup):
lookup_name: str = ...
class OverlapsLookup(GISLookup):
lookup_name: str = ...
class RelateLookup(GISLookup):
lookup_name: str = ...
sql_template: str = ...
pattern_regex: Any = ...
def process_rhs(self, compiler: Any, connection: Any): ...
class TouchesLookup(GISLookup):
lookup_name: str = ...
class WithinLookup(GISLookup):
lookup_name: str = ...
class DistanceLookupBase(GISLookup):
distance: bool = ...
sql_template: str = ...
def process_rhs_params(self) -> None: ...
def process_distance(self, compiler: Any, connection: Any): ...
class DWithinLookup(DistanceLookupBase):
lookup_name: str = ...
sql_template: str = ...
def process_distance(self, compiler: Any, connection: Any): ...
def process_rhs(self, compiler: Any, connection: Any): ...
class DistanceLookupFromFunction(DistanceLookupBase):
def as_sql(self, compiler: Any, connection: Any): ...
class DistanceGTLookup(DistanceLookupFromFunction):
lookup_name: str = ...
op: str = ...
class DistanceGTELookup(DistanceLookupFromFunction):
lookup_name: str = ...
op: str = ...
class DistanceLTLookup(DistanceLookupFromFunction):
lookup_name: str = ...
op: str = ...
class DistanceLTELookup(DistanceLookupFromFunction):
lookup_name: str = ...
op: str = ...

View File

@@ -0,0 +1,7 @@
from django.db.models.query_utils import DeferredAttribute
from typing import Any, Optional
class SpatialProxy(DeferredAttribute):
def __init__(self, klass: Any, field: Any, load_func: Optional[Any] = ...) -> None: ...
def __get__(self, instance: Any, cls: Optional[Any] = ...): ...
def __set__(self, instance: Any, value: Any): ...

View File

@@ -0,0 +1,18 @@
from django.db import models as models
from typing import Any
class AreaField(models.FloatField):
geo_field: Any = ...
def __init__(self, geo_field: Any) -> None: ...
def get_prep_value(self, value: Any): ...
def get_db_prep_value(self, value: Any, connection: Any, prepared: bool = ...): ...
def from_db_value(self, value: Any, expression: Any, connection: Any): ...
def get_internal_type(self): ...
class DistanceField(models.FloatField):
geo_field: Any = ...
def __init__(self, geo_field: Any) -> None: ...
def get_prep_value(self, value: Any): ...
def get_db_prep_value(self, value: Any, connection: Any, prepared: bool = ...): ...
def from_db_value(self, value: Any, expression: Any, connection: Any): ...
def get_internal_type(self): ...

View File

@@ -0,0 +1,28 @@
from django.contrib.syndication.views import Feed as BaseFeed
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
from typing import Any
class GeoFeedMixin:
def georss_coords(self, coords: Any): ...
def add_georss_point(self, handler: Any, coords: Any, w3c_geo: bool = ...) -> None: ...
def add_georss_element(self, handler: Any, item: Any, w3c_geo: bool = ...) -> None: ...
class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self): ...
def add_item_elements(self, handler: Any, item: Any) -> None: ...
def add_root_elements(self, handler: Any) -> None: ...
class GeoAtom1Feed(Atom1Feed, GeoFeedMixin):
def root_attributes(self): ...
def add_item_elements(self, handler: Any, item: Any) -> None: ...
def add_root_elements(self, handler: Any) -> None: ...
class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self): ...
def add_item_elements(self, handler: Any, item: Any) -> None: ...
def add_root_elements(self, handler: Any) -> None: ...
class Feed(BaseFeed):
feed_type: Any = ...
def feed_extra_kwargs(self, obj: Any): ...
def item_extra_kwargs(self, item: Any): ...

View File

@@ -0,0 +1,33 @@
from django import forms as forms
from typing import Any, Optional
class GeometryField(forms.Field):
widget: Any = ...
geom_type: str = ...
default_error_messages: Any = ...
srid: Any = ...
def __init__(self, *, srid: Optional[Any] = ..., geom_type: Optional[Any] = ..., **kwargs: Any) -> None: ...
def to_python(self, value: Any): ...
def clean(self, value: Any): ...
def has_changed(self, initial: Any, data: Any): ...
class GeometryCollectionField(GeometryField):
geom_type: str = ...
class PointField(GeometryField):
geom_type: str = ...
class MultiPointField(GeometryField):
geom_type: str = ...
class LineStringField(GeometryField):
geom_type: str = ...
class MultiLineStringField(GeometryField):
geom_type: str = ...
class PolygonField(GeometryField):
geom_type: str = ...
class MultiPolygonField(GeometryField):
geom_type: str = ...

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