add missing files throughout the codebase (#102)

This commit is contained in:
Maxim Kurnikov
2019-07-09 05:18:15 +03:00
committed by GitHub
parent d8230a4147
commit 2799646723
67 changed files with 748 additions and 120 deletions

View File

@@ -7,7 +7,7 @@
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. 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.x series. Supports Python 3.6/3.7, and Django 2.1/2.2.
Could be run on earlier versions of Django, but expect some missing imports warnings. Could be run on earlier versions of Django, but expect some missing imports warnings.

View File

@@ -1,4 +1,5 @@
import collections import collections
import threading
from typing import Any, Callable, List, Optional, Tuple, Type, Union, Iterable, DefaultDict from typing import Any, Callable, List, Optional, Tuple, Type, Union, Iterable, DefaultDict
from django.db.migrations.state import AppConfigStub from django.db.migrations.state import AppConfigStub
@@ -11,6 +12,7 @@ class Apps:
app_configs: collections.OrderedDict = ... app_configs: collections.OrderedDict = ...
stored_app_configs: List[Any] = ... stored_app_configs: List[Any] = ...
apps_ready: bool = ... apps_ready: bool = ...
ready_event: threading.Event = ...
loading: bool = ... loading: bool = ...
_pending_operations: DefaultDict[Tuple[str, str], List] _pending_operations: DefaultDict[Tuple[str, str], List]
def __init__(self, installed_apps: Optional[Union[List[AppConfigStub], List[str], Tuple]] = ...) -> None: ... def __init__(self, installed_apps: Optional[Union[List[AppConfigStub], List[str], Tuple]] = ...) -> None: ...

View File

@@ -6,6 +6,8 @@ from django.utils.functional import LazyObject
from . import global_settings from . import global_settings
ENVIRONMENT_VARIABLE: str = ... ENVIRONMENT_VARIABLE: str = ...
DEFAULT_CONTENT_TYPE_DEPRECATED_MSG: str = ...
FILE_CHARSET_DEPRECATED_MSG: str = ...
# required for plugin to be able to distinguish this specific instance of LazySettings from others # required for plugin to be able to distinguish this specific instance of LazySettings from others
class _DjangoConfLazyObject(LazyObject): class _DjangoConfLazyObject(LazyObject):
@@ -22,3 +24,6 @@ class Settings:
def is_overridden(self, setting: str) -> bool: ... def is_overridden(self, setting: str) -> bool: ...
class UserSettingsHolder: ... class UserSettingsHolder: ...
class SettingsReference(str):
def __init__(self, value: str, setting_name: str) -> None: ...

View File

@@ -0,0 +1,23 @@
from typing import Any, Callable
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.selenium import SeleniumTestCase
from django.utils.deprecation import MiddlewareMixin
class CSPMiddleware(MiddlewareMixin): ...
class AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):
def wait_until(self, callback: Callable, timeout: int = ...) -> None: ...
def wait_for_popup(self, num_windows: int = ..., timeout: int = ...) -> None: ...
def wait_for(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_for_text(self, css_selector: str, text: str, timeout: int = ...) -> None: ...
def wait_for_value(self, css_selector: str, text: str, timeout: int = ...) -> None: ...
def wait_until_visible(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_until_invisible(self, css_selector: str, timeout: int = ...) -> None: ...
def wait_page_loaded(self) -> None: ...
def admin_login(self, username: str, password: str, login_url: str = ...) -> None: ...
def get_css_value(self, selector: str, attribute: str) -> Any: ...
def get_select_option(self, selector: str, value: Any) -> Any: ...
def assertSelectOptions(self, selector: str, values: Any) -> None: ...
def assertSelectedOptions(self, selector: str, values: Any) -> None: ...
def has_css_class(self, selector: str, klass: str) -> bool: ...

View File

@@ -2,7 +2,7 @@ from collections import OrderedDict
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from django.contrib.admin.filters import ListFilter, SimpleListFilter from django.contrib.admin.filters import ListFilter, SimpleListFilter
from django.contrib.admin.options import ModelAdmin from django.contrib.admin.options import ModelAdmin, IS_POPUP_VAR as IS_POPUP_VAR, TO_FIELD_VAR as TO_FIELD_VAR
from django.core.handlers.wsgi import WSGIRequest from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model from django.db.models.base import Model
from django.db.models.expressions import Combinable, CombinedExpression, OrderBy from django.db.models.expressions import Combinable, CombinedExpression, OrderBy

View File

@@ -74,6 +74,9 @@ class AdminIntegerFieldWidget(forms.NumberInput):
class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): ... class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): ...
class AdminUUIDInputWidget(forms.TextInput):
def __init__(self, attrs: Optional[Dict[str, str]] = ...) -> None: ...
SELECT2_TRANSLATIONS: Any SELECT2_TRANSLATIONS: Any
class AutocompleteMixin: class AutocompleteMixin:

View File

@@ -4,8 +4,15 @@ from .ranges import (
RangeField as RangeField, RangeField as RangeField,
IntegerRangeField as IntegerRangeField, IntegerRangeField as IntegerRangeField,
BigIntegerRangeField as BigIntegerRangeField, BigIntegerRangeField as BigIntegerRangeField,
DecimalRangeField as DecimalRangeField,
FloatRangeField as FloatRangeField, FloatRangeField as FloatRangeField,
DateRangeField as DateRangeField, DateRangeField as DateRangeField,
DateTimeRangeField as DateTimeRangeField, DateTimeRangeField as DateTimeRangeField,
) )
from .hstore import HStoreField as HStoreField from .hstore import HStoreField as HStoreField
from .citext import (
CICharField as CICharField,
CIEmailField as CIEmailField,
CIText as CIText,
CITextField as CITextField,
)

View File

@@ -1,7 +1,8 @@
from json import JSONEncoder from json import JSONEncoder
from typing import Any, Dict, List, Optional, Tuple, Type, Union from typing import Any, Optional, Type
from django.db.models import Field from django.db.models import Field
from django.db.models.lookups import Transform
from .mixins import CheckFieldDefaultMixin from .mixins import CheckFieldDefaultMixin
class JsonAdapter(object): class JsonAdapter(object):
@@ -22,9 +23,15 @@ class JSONField(CheckFieldDefaultMixin, Field):
**kwargs: Any **kwargs: Any
) -> None: ... ) -> None: ...
def db_type(self, connection: Any): ... def db_type(self, connection: Any): ...
def deconstruct(self) -> Tuple[None, str, List[Any], Dict[str, Union[Type[JSONEncoder], bool]]]: ...
def get_transform(self, name: Any): ... def get_transform(self, name: Any): ...
def get_prep_value(self, value: Any): ... def get_prep_value(self, value: Any): ...
def validate(self, value: Any, model_instance: Any) -> None: ... def validate(self, value: Any, model_instance: Any) -> None: ...
def value_to_string(self, obj: Any): ... def value_to_string(self, obj: Any): ...
def formfield(self, **kwargs: Any): ... def formfield(self, **kwargs: Any): ...
class KeyTransform(Transform):
operator: str = ...
nested_operator: str = ...
def __init__(self, key_name: str, *args: Any, **kwargs: Any) -> None: ...
class KeyTextTransform(KeyTransform): ...

View File

@@ -18,6 +18,9 @@ class IntegerRangeField(RangeField):
class BigIntegerRangeField(RangeField): class BigIntegerRangeField(RangeField):
def __get__(self, instance, owner) -> NumericRange: ... def __get__(self, instance, owner) -> NumericRange: ...
class DecimalRangeField(RangeField):
def __get__(self, instance, owner) -> NumericRange: ...
class FloatRangeField(RangeField): class FloatRangeField(RangeField):
def __get__(self, instance, owner) -> NumericRange: ... def __get__(self, instance, owner) -> NumericRange: ...

View File

@@ -0,0 +1,4 @@
from django.db.models import Func
class RandomUUID(Func): ...
class TransactionNow(Func): ...

View File

@@ -0,0 +1,29 @@
from typing import Any, Optional
from django.db.models import Index
class PostgresIndex(Index):
@property
def max_name_length(self) -> int: ...
class BrinIndex(PostgresIndex):
def __init__(
self, *, autosummarize: Optional[bool] = ..., pages_per_range: Optional[int] = ..., **kwargs: Any
) -> None: ...
class BTreeIndex(PostgresIndex):
def __init__(self, *, fillfactor: Optional[int] = ..., **kwargs: Any): ...
class GinIndex(PostgresIndex):
def __init__(
self, *, fastupdate: Optional[bool] = ..., gin_pending_list_limit: Optional[int] = ..., **kwargs: Any
) -> None: ...
class GistIndex(PostgresIndex):
def __init__(self, *, buffering: Optional[bool] = ..., fillfactor: Optional[int] = ..., **kwargs: Any) -> None: ...
class HashIndex(PostgresIndex):
def __init__(self, *, fillfactor: Optional[int] = ..., **kwargs: Any) -> None: ...
class SpGistIndex(PostgresIndex):
def __init__(self, *, fillfactor: Optional[int] = ..., **kwargs: Any) -> None: ...

View File

@@ -0,0 +1,47 @@
from typing import Any, Dict, Optional, TypeVar, Union
from django.db.models.expressions import Combinable, CombinedExpression, Func, Value
from django.db.models.lookups import Lookup
from django.db.models import Field
class SearchVectorExact(Lookup): ...
class SearchVectorField(Field): ...
class SearchQueryField(Field): ...
class SearchVectorCombinable:
ADD: str = ...
class SearchVector(SearchVectorCombinable, Func):
config: Optional[Any] = None
def __init__(self, *expressions: Union[str, Combinable], **extra: Any): ...
class CombinedSearchVector(SearchVectorCombinable, CombinedExpression):
def __init__(self, lhs, connector, rhs, config, output_field: Optional[Field, str] = ...): ...
_T = TypeVar("_T", bound="SearchQueryCombinable")
class SearchQueryCombinable:
BITAND: str = ...
BITOR: str = ...
def __or__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __ror__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __and__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __rand__(self: _T, other: SearchQueryCombinable) -> _T: ...
class SearchQuery(SearchQueryCombinable, Value):
SEARCH_TYPES: Dict[str, str] = {"plain": "plainto_tsquery", "phrase": "phraseto_tsquery", "raw": "to_tsquery"}
def __init__(self, value, output_field=None, *, config=None, invert=False, search_type="plain"): ...
def __invert__(self: _T) -> _T: ...
class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression):
def __init__(self, lhs, connector, rhs, config, output_field=None) -> None: ...
class SearchRank(Func):
def __init__(self, vector, query, **extra: Any) -> None: ...
class TrigramBase(Func):
def __init__(self, expression, string, **extra: Any) -> None: ...
class TrigramSimilarity(TrigramBase): ...
class TrigramDistance(TrigramBase): ...

View File

@@ -0,0 +1,5 @@
from typing import Any, Tuple
def get_hstore_oids(connection_alias: str) -> Tuple[Any, ...]: ...
def get_citext_oids(connection_alias: str) -> Tuple[Any, ...]: ...
def register_type_handlers(connection: Any, **kwargs: Any) -> None: ...

View File

@@ -0,0 +1,17 @@
from typing import Any, Dict, Iterable, Mapping, Optional
from django.core.validators import MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator
class ArrayMaxLengthValidator(MaxLengthValidator): ...
class ArrayMinLengthValidator(MinLengthValidator): ...
class KeysValidator:
messages: Dict[str, str] = ...
strict: bool = ...
def __init__(
self, keys: Iterable[str], strict: bool = ..., messages: Optional[Mapping[str, str]] = ...
) -> None: ...
def __call__(self, value: Any) -> None: ...
class RangeMaxValueValidator(MaxValueValidator): ...
class RangeMinValueValidator(MinValueValidator): ...

View File

@@ -0,0 +1,4 @@
from django.core.exceptions import SuspiciousOperation
class InvalidSessionKey(SuspiciousOperation): ...
class SuspiciousSession(SuspiciousOperation): ...

View File

@@ -1,3 +1,5 @@
from .messages import Warning as Warning, Info as Info, Debug as Debug, Error as Error, Critical as Critical from .messages import Warning as Warning, Info as Info, Debug as Debug, Error as Error, Critical as Critical
from .registry import run_checks as run_checks, Tags as Tags, register as register from .registry import run_checks as run_checks, Tags as Tags, register as register
from . import model_checks as model_checks

View File

@@ -0,0 +1,7 @@
from typing import Any, List
from . import Error
E001: Error = ...
def check_setting_language_code(app_configs: Any, **kwargs: Any) -> List[Error]: ...

View File

@@ -1,9 +1,11 @@
import types
from io import StringIO from io import StringIO
from typing import Any, Iterator, Optional, Union, IO, Type from typing import Any, IO, Iterator, Optional, Type, TypeVar, Union
from types import TracebackType
from django.core.files.utils import FileProxyMixin from django.core.files.utils import FileProxyMixin
_T = TypeVar("_T", bound="File")
class File(FileProxyMixin, IO[Any]): class File(FileProxyMixin, IO[Any]):
DEFAULT_CHUNK_SIZE: Any = ... DEFAULT_CHUNK_SIZE: Any = ...
file: StringIO = ... file: StringIO = ...
@@ -13,24 +15,24 @@ class File(FileProxyMixin, IO[Any]):
def __bool__(self) -> bool: ... def __bool__(self) -> bool: ...
def __len__(self) -> int: ... def __len__(self) -> int: ...
def size(self) -> int: ... def size(self) -> int: ...
def chunks(self, chunk_size: Optional[int] = ...) -> Iterator[Union[bytes, bytearray]]: ... def chunks(self, chunk_size: Optional[int] = ...) -> Iterator[bytes]: ...
def multiple_chunks(self, chunk_size: Optional[Any] = ...): ... def multiple_chunks(self, chunk_size: Optional[int] = ...) -> bool: ...
def __iter__(self) -> Iterator[Union[bytes, str]]: ... def __iter__(self) -> Iterator[Union[bytes, str]]: ...
def __next__(self) -> Union[bytes, str]: ... def __next__(self) -> Union[bytes, str]: ...
def __enter__(self) -> File: ... def __enter__(self: _T) -> _T: ...
def __exit__( def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], tb: Optional[TracebackType] self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
tb: Optional[types.TracebackType],
) -> bool: ... ) -> bool: ...
def open(self, mode: Optional[str] = ...) -> File: ... def open(self: _T, mode: Optional[str] = ...) -> _T: ...
def close(self) -> None: ... def close(self) -> None: ...
class ContentFile(File): class ContentFile(File):
file: StringIO file: StringIO
size: Any = ... size: Any = ...
def __init__(self, content: Union[bytes, str], name: Optional[str] = ...) -> None: ... def __init__(self, content: Union[bytes, str], name: Optional[str] = ...) -> None: ...
def __bool__(self) -> bool: ...
def open(self, mode: Optional[str] = ...) -> ContentFile: ...
def close(self) -> None: ...
def write(self, data: str) -> int: ... def write(self, data: str) -> int: ...
def endswith_cr(line: bytes) -> bool: ... def endswith_cr(line: bytes) -> bool: ...

View File

@@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from typing import Any, List, Optional, Tuple, IO from typing import Any, IO, List, Optional, Tuple
from django.core.files.base import File from django.core.files.base import File
from django.utils.functional import LazyObject from django.utils.functional import LazyObject
@@ -13,7 +13,7 @@ class Storage:
def path(self, name: str) -> str: ... def path(self, name: str) -> str: ...
def delete(self, name: str) -> None: ... def delete(self, name: str) -> None: ...
def exists(self, name: str) -> bool: ... def exists(self, name: str) -> bool: ...
def listdir(self, path: Any) -> Optional[Tuple[List[str], List[str]]]: ... def listdir(self, path: str) -> Tuple[List[str], List[str]]: ...
def size(self, name: str) -> int: ... def size(self, name: str) -> int: ...
def url(self, name: Optional[str]) -> str: ... def url(self, name: Optional[str]) -> str: ...
def get_accessed_time(self, name: str) -> datetime: ... def get_accessed_time(self, name: str) -> datetime: ...
@@ -21,6 +21,7 @@ class Storage:
def get_modified_time(self, name: str) -> datetime: ... def get_modified_time(self, name: str) -> datetime: ...
class FileSystemStorage(Storage): class FileSystemStorage(Storage):
OS_OPEN_FLAGS: int = ...
def __init__( def __init__(
self, self,
location: Optional[str] = ..., location: Optional[str] = ...,
@@ -42,3 +43,5 @@ class FileSystemStorage(Storage):
class DefaultStorage(LazyObject): ... class DefaultStorage(LazyObject): ...
default_storage: Any default_storage: Any
def get_storage_class(import_path: Optional[str] = ...) -> Storage: ...

View File

@@ -1,5 +1,5 @@
from typing import Any, Dict, IO, Iterator, Optional, Union from typing import Any, Dict, IO, Optional, Union
from django.core.files import temp as tempfile
from django.core.files.base import File from django.core.files.base import File
class UploadedFile(File): class UploadedFile(File):
@@ -39,8 +39,6 @@ class InMemoryUploadedFile(UploadedFile):
charset: Optional[str], charset: Optional[str],
content_type_extra: Dict[str, str] = ..., content_type_extra: Dict[str, str] = ...,
) -> None: ... ) -> None: ...
def chunks(self, chunk_size: Optional[int] = ...) -> Iterator[bytes]: ...
def multiple_chunks(self, chunk_size: Optional[int] = ...) -> bool: ...
class SimpleUploadedFile(InMemoryUploadedFile): class SimpleUploadedFile(InMemoryUploadedFile):
def __init__(self, name: str, content: Optional[Union[bytes, str]], content_type: str = ...) -> None: ... def __init__(self, name: str, content: Optional[Union[bytes, str]], content_type: str = ...) -> None: ...

View File

@@ -0,0 +1,16 @@
import types
from typing import Any, TypeVar, Type, Iterable
from django.core.mail.message import EmailMessage
_T = TypeVar("_T", bound="BaseEmailBackend")
class BaseEmailBackend:
def __init__(self, fail_silently: bool = ..., **kwargs: Any) -> None: ...
def open(self) -> bool: ...
def close(self) -> None: ...
def __enter__(self: _T) -> _T: ...
def __exit__(
self, exc_type: Type[BaseException], exc_value: BaseException, traceback: types.TracebackType
) -> None: ...
def send_messages(self, email_messages: Iterable[EmailMessage]) -> int: ...

View File

@@ -1,7 +1,14 @@
from collections import Callable
def supports_color() -> bool: ... def supports_color() -> bool: ...
class Style: ... class Style:
def DEBUG(self, text: str) -> str: ...
def INFO(self, text: str) -> str: ...
def SUCCESS(self, text: str) -> str: ...
def WARNING(self, text: str) -> str: ...
def ERROR(self, text: str) -> str: ...
def make_style(config_string: str = ...) -> Style: ... def make_style(config_string: str = ...) -> Style: ...
def no_style(): ... def no_style() -> Style: ...
def color_style() -> Style: ... def color_style() -> Style: ...

View File

@@ -0,0 +1,4 @@
from django.core.management.base import BaseCommand
class ProxyModelWarning(Warning): ...
class Command(BaseCommand): ...

View File

@@ -0,0 +1,19 @@
import zipfile
from typing import Iterable, List, Optional, Tuple
from django.core.management.base import BaseCommand
READ_STDIN: str = ...
class Command(BaseCommand):
missing_args_message: str = ...
def loaddata(self, fixture_labels: Iterable[str]) -> None: ...
def load_label(self, fixture_label: str) -> None: ...
def find_fixtures(self, fixture_label: str) -> List[Optional[str]]: ...
@property
def fixture_dirs(self) -> List[str]: ...
def parse_name(self, fixture_name: str) -> Tuple[str, str, str]: ...
class SingleZipReader(zipfile.ZipFile): ...
def humanize(dirname: str) -> str: ...

View File

@@ -0,0 +1,3 @@
from django.core.management.base import BaseCommand
class Command(BaseCommand): ...

View File

@@ -0,0 +1,3 @@
from django.core.management.base import BaseCommand
class Command(BaseCommand): ...

View File

@@ -27,4 +27,5 @@ class DefaultConnectionProxy:
def __setattr__(self, name: str, value: Any) -> None: ... def __setattr__(self, name: str, value: Any) -> None: ...
def __delattr__(self, name: str) -> None: ... def __delattr__(self, name: str) -> None: ...
def close_old_connections(**kwargs): ... def close_old_connections(**kwargs: Any) -> None: ...
def reset_queries(**kwargs: Any) -> None: ...

View File

@@ -25,7 +25,7 @@ class BaseDatabaseOperations:
CURRENT_ROW: str = ... CURRENT_ROW: str = ...
explain_prefix: Any = ... explain_prefix: Any = ...
connection: Any = ... connection: Any = ...
def __init__(self, connection: Union[DefaultConnectionProxy, BaseDatabaseWrapper]) -> None: ... def __init__(self, connection: Optional[Union[DefaultConnectionProxy, BaseDatabaseWrapper]]) -> None: ...
def autoinc_sql(self, table: str, column: str) -> None: ... def autoinc_sql(self, table: str, column: str) -> None: ...
def bulk_batch_size(self, fields: Any, objs: Any): ... def bulk_batch_size(self, fields: Any, objs: Any): ...
def cache_key_culling_sql(self) -> str: ... def cache_key_culling_sql(self) -> str: ...

View File

@@ -0,0 +1,17 @@
from typing import Dict, Tuple
from django.db.backends.base.base import BaseDatabaseWrapper
def psycopg2_version() -> Tuple[int, ...]: ...
PSYCOPG2_VERSION: Tuple[int, ...] = ...
class DatabaseWrapper(BaseDatabaseWrapper):
operators: Dict[str, str] = ...
pattern_esc: str = ...
pattern_ops: Dict[str, str] = ...
# PostgreSQL backend-specific attributes.
_named_cursor_idx: int = ...
@property
def pg_version(self) -> str: ...

View File

@@ -0,0 +1,3 @@
from django.db.backends.base.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation): ...

View File

@@ -0,0 +1,3 @@
from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations): ...

View File

@@ -0,0 +1,3 @@
from django.dispatch import Signal
connection_created: Signal = ...

View File

@@ -16,41 +16,7 @@ from .models import (
DeleteModel as DeleteModel, DeleteModel as DeleteModel,
RemoveIndex as RemoveIndex, RemoveIndex as RemoveIndex,
RenameModel as RenameModel, RenameModel as RenameModel,
AddConstraint as AddConstraint,
RemoveConstraint as RemoveConstraint,
) )
from .special import RunPython as RunPython, RunSQL as RunSQL, SeparateDatabaseAndState as SeparateDatabaseAndState from .special import RunPython as RunPython, RunSQL as RunSQL, SeparateDatabaseAndState as SeparateDatabaseAndState
from .fields import AddField, AlterField, RemoveField, RenameField
from .models import (
AddIndex,
AlterIndexTogether,
AlterModelManagers,
AlterModelOptions,
AlterModelTable,
AlterOrderWithRespectTo,
AlterUniqueTogether,
CreateModel,
DeleteModel,
RemoveIndex,
RenameModel,
)
from .special import RunPython, RunSQL, SeparateDatabaseAndState
__all__ = [
"CreateModel",
"DeleteModel",
"AlterModelTable",
"AlterUniqueTogether",
"RenameModel",
"AlterIndexTogether",
"AlterModelOptions",
"AddIndex",
"RemoveIndex",
"AddField",
"RemoveField",
"AlterField",
"RenameField",
"SeparateDatabaseAndState",
"RunSQL",
"RunPython",
"AlterOrderWithRespectTo",
"AlterModelManagers",
]

View File

@@ -4,6 +4,7 @@ from django.db.migrations.operations.base import Operation
from django.db.models.indexes import Index from django.db.models.indexes import Index
from django.db.models.manager import Manager from django.db.models.manager import Manager
from django.db.models.constraints import BaseConstraint
from django.db.models.fields import Field from django.db.models.fields import Field
class ModelOperation(Operation): class ModelOperation(Operation):
@@ -78,3 +79,9 @@ class RemoveIndex(IndexOperation):
model_name: str = ... model_name: str = ...
name: str = ... name: str = ...
def __init__(self, model_name: str, name: Union[str, Index]) -> None: ... def __init__(self, model_name: str, name: Union[str, Index]) -> None: ...
class AddConstraint(IndexOperation):
def __init__(self, model_name: str, constraint: BaseConstraint): ...
class RemoveConstraint(IndexOperation):
def __init__(self, model_name: str, name: str) -> None: ...

View File

@@ -1,4 +1,4 @@
from typing import Any, Callable, Dict, List, Set, Tuple, Union from typing import Any, Callable, Dict, List, Set, Tuple, Union, Type
class BaseSerializer: class BaseSerializer:
value: Any = ... value: Any = ...
@@ -38,3 +38,9 @@ class TypeSerializer(BaseSerializer): ...
class UUIDSerializer(BaseSerializer): ... class UUIDSerializer(BaseSerializer): ...
def serializer_factory(value: Any) -> BaseSerializer: ... def serializer_factory(value: Any) -> BaseSerializer: ...
class Serializer:
@classmethod
def register(cls, type_: type, serializer: Type[BaseSerializer]) -> None: ...
@classmethod
def unregister(cls, type_: type) -> None: ...

View File

@@ -1,4 +1,4 @@
from typing import Any, DefaultDict, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union from typing import Any, DefaultDict, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union, Set
from django.apps.registry import Apps from django.apps.registry import Apps
from django.db.models.base import Model from django.db.models.base import Model
@@ -42,6 +42,9 @@ class ModelState:
def name_lower(self) -> str: ... def name_lower(self) -> str: ...
def render(self, apps: Apps) -> Any: ... def render(self, apps: Apps) -> Any: ...
def get_related_models_tuples(model: Type[Model]) -> Set[Tuple[str, str]]: ...
def get_related_models_recursive(model: Type[Model]) -> Set[Tuple[str, str]]: ...
class ProjectState: class ProjectState:
is_delayed: bool is_delayed: bool
models: Dict[Any, Any] models: Dict[Any, Any]

View File

@@ -1,4 +1,4 @@
from typing import Any from typing import Any, Iterable, Union, Optional, List
COMPILED_REGEX_TYPE: Any COMPILED_REGEX_TYPE: Any

View File

@@ -1,8 +1,9 @@
from typing import Any, List, Set, Tuple, Union from typing import Any, List, Set, Tuple, Union, Type
from django.db.migrations.migration import Migration from django.db.migrations.migration import Migration
from django.db.migrations.operations.base import Operation from django.db.migrations.operations.base import Operation
from django.db.migrations.operations.models import CreateModel from django.db.migrations.operations.models import CreateModel
from django.db.migrations.serializer import BaseSerializer
class SettingsReference(str): class SettingsReference(str):
def __init__(self, value: str, setting_name: str) -> None: ... def __init__(self, value: str, setting_name: str) -> None: ...
@@ -31,5 +32,9 @@ class MigrationWriter:
def path(self) -> str: ... def path(self) -> str: ...
@classmethod @classmethod
def serialize(cls, value: Any) -> Tuple[str, Set[str]]: ... def serialize(cls, value: Any) -> Tuple[str, Set[str]]: ...
@classmethod
def register_serializer(cls, type_: type, serializer: Type[BaseSerializer]) -> None: ...
@classmethod
def unregister_serializer(cls, type_: type) -> None: ...
MIGRATION_TEMPLATE: str MIGRATION_TEMPLATE: str

View File

@@ -99,6 +99,10 @@ from .expressions import (
ExpressionList as ExpressionList, ExpressionList as ExpressionList,
Random as Random, Random as Random,
Ref as Ref, Ref as Ref,
Window as Window,
WindowFrame as WindowFrame,
RowRange as RowRange,
ValueRange as ValueRange,
) )
from .manager import BaseManager as BaseManager, Manager as Manager from .manager import BaseManager as BaseManager, Manager as Manager
@@ -118,3 +122,9 @@ from .aggregates import (
from .indexes import Index as Index from .indexes import Index as Index
from . import signals as signals from . import signals as signals
from .constraints import (
BaseConstraint as BaseConstraint,
CheckConstraint as CheckConstraint,
UniqueConstraint as UniqueConstraint,
)

View File

@@ -1,7 +1,10 @@
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, TypeVar, Union from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, TypeVar, Union
from django.core import checks
from django.db.models.manager import Manager from django.db.models.manager import Manager
from django.core.checks.messages import CheckMessage
class ModelBase(type): ... class ModelBase(type): ...
_Self = TypeVar("_Self", bound="Model") _Self = TypeVar("_Self", bound="Model")
@@ -36,6 +39,8 @@ class Model(metaclass=ModelBase):
): ... ): ...
def refresh_from_db(self: _Self, using: Optional[str] = ..., fields: Optional[List[str]] = ...) -> _Self: ... def refresh_from_db(self: _Self, using: Optional[str] = ..., fields: Optional[List[str]] = ...) -> _Self: ...
def get_deferred_fields(self) -> Set[str]: ... def get_deferred_fields(self) -> Set[str]: ...
@classmethod
def check(cls, **kwargs: Any) -> List[CheckMessage]: ...
def __getstate__(self) -> dict: ... def __getstate__(self) -> dict: ...
class ModelStateFieldsCacheDescriptor: ... class ModelStateFieldsCacheDescriptor: ...

View File

@@ -0,0 +1,27 @@
from typing import Any, Optional, Sequence, Tuple, Type, TypeVar
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models.base import Model
from django.db.models.query_utils import Q
_T = TypeVar("_T", bound="BaseConstraint")
class BaseConstraint:
name: str
def __init__(self, name: str) -> None: ...
def constraint_sql(
self, model: Optional[Type[Model]], schema_editor: Optional[BaseDatabaseSchemaEditor]
) -> str: ...
def create_sql(self, model: Optional[Type[Model]], schema_editor: Optional[BaseDatabaseSchemaEditor]) -> str: ...
def remove_sql(self, model: Optional[Type[Model]], schema_editor: Optional[BaseDatabaseSchemaEditor]) -> str: ...
def deconstruct(self) -> Any: ...
def clone(self: _T) -> _T: ...
class CheckConstraint(BaseConstraint):
check: Q
def __init__(self, *, check: Q, name: str) -> None: ...
class UniqueConstraint(BaseConstraint):
fields: Tuple[str]
condition: Optional[Q]
def __init__(self, *, fields: Sequence[str], name: str, condition: Optional[Q] = ...): ...

View File

@@ -1,4 +1,6 @@
from typing import Any, Callable, Iterable from typing import Any, Callable, Iterable, Optional, Union
from django.db.models.base import Model
from django.db import IntegrityError from django.db import IntegrityError
from django.db.models.fields import Field from django.db.models.fields import Field
@@ -16,3 +18,4 @@ class ProtectedError(IntegrityError): ...
class Collector: class Collector:
def __init__(self, using: str) -> None: ... def __init__(self, using: str) -> None: ...
def can_fast_delete(self, objs: Union[Model, Iterable[Model]], from_field: Optional[Field] = ...) -> bool: ...

View File

@@ -1,5 +1,5 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, Iterable
from django.db.models.lookups import Lookup from django.db.models.lookups import Lookup
from django.db.models.sql.compiler import SQLCompiler from django.db.models.sql.compiler import SQLCompiler
@@ -184,10 +184,36 @@ class ExpressionWrapper(Expression):
class Col(Expression): class Col(Expression):
def __init__(self, alias: str, target: str, output_field: Optional[_OutputField] = ...): ... def __init__(self, alias: str, target: str, output_field: Optional[_OutputField] = ...): ...
class SimpleCol(Expression):
contains_column_references: bool = ...
def __init__(self, target: Field, output_field: Optional[_OutputField] = ...): ...
class Ref(Expression):
def __init__(self, refs: str, source: Expression): ...
class ExpressionList(Func): class ExpressionList(Func):
def __init__(self, *expressions: Union[BaseExpression, Combinable], **extra: Any) -> None: ... def __init__(self, *expressions: Union[BaseExpression, Combinable], **extra: Any) -> None: ...
class Random(Expression): ... class Random(Expression): ...
class Ref(Expression): class Window(Expression):
def __init__(self, refs: str, source: Expression): ... template: str = ...
contains_aggregate: bool = ...
contains_over_clause: bool = ...
def __init__(
self,
expression: BaseExpression,
partition_by: Optional[Union[str, Iterable[Union[BaseExpression, F]], F, BaseExpression]] = ...,
order_by: Optional[Union[Sequence[Union[BaseExpression, F]], Union[BaseExpression, F]]] = ...,
frame: Optional[WindowFrame] = ...,
output_field: Optional[_OutputField] = ...,
) -> None: ...
class WindowFrame(Expression):
template: str = ...
frame_type: str = ...
def __init__(self, start: Optional[int] = ..., end: Optional[int] = ...) -> None: ...
def window_frame_start_end(self, connection: Any, start: Optional[int], end: Optional[int]) -> Tuple[int, int]: ...
class RowRange(WindowFrame): ...
class ValueRange(WindowFrame): ...

View File

@@ -1,7 +1,7 @@
import decimal import decimal
import uuid import uuid
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from typing import Any, Callable, Dict, Generic, Iterable, Optional, Tuple, Type, TypeVar, Union from typing import Any, Callable, Dict, Generic, Iterable, Optional, Tuple, Type, TypeVar, Union, Sequence
from django.db.models import Model from django.db.models import Model
from django.core.exceptions import FieldDoesNotExist as FieldDoesNotExist from django.core.exceptions import FieldDoesNotExist as FieldDoesNotExist
@@ -34,6 +34,10 @@ class Field(RegisterLookupMixin, Generic[_ST, _GT]):
max_length: Optional[int] max_length: Optional[int]
model: Type[Model] model: Type[Model]
name: str name: str
blank: bool = ...
null: bool = ...
editable: bool = ...
choices: Optional[_FieldChoices] = ...
def __init__( def __init__(
self, self,
verbose_name: Optional[Union[str, bytes]] = ..., verbose_name: Optional[Union[str, bytes]] = ...,
@@ -69,6 +73,15 @@ class Field(RegisterLookupMixin, Generic[_ST, _GT]):
def formfield(self, **kwargs) -> FormField: ... def formfield(self, **kwargs) -> FormField: ...
def contribute_to_class(self, cls: Type[Model], name: str, private_only: bool = ...) -> None: ... def contribute_to_class(self, cls: Type[Model], name: str, private_only: bool = ...) -> None: ...
def to_python(self, value: Any) -> Any: ... def to_python(self, value: Any) -> Any: ...
def clean(self, value: Any, model_instance: Optional[Model]) -> Any: ...
def get_choices(
self,
include_blank: bool = ...,
blank_choice: _Choice = ...,
limit_choices_to: Optional[Any] = ...,
ordering: Sequence[str] = ...,
) -> Sequence[Union[_Choice, _ChoiceNamedGroup]]: ...
def get_default(self) -> Any: ...
class IntegerField(Field[_ST, _GT]): class IntegerField(Field[_ST, _GT]):
_pyi_private_set_type: Union[float, int, str, Combinable] _pyi_private_set_type: Union[float, int, str, Combinable]

View File

@@ -62,7 +62,6 @@ class RelatedField(FieldCacheMixin, Field[_ST, _GT]):
def related_model(self) -> Union[Type[Model], str]: ... def related_model(self) -> Union[Type[Model], str]: ...
def check(self, **kwargs: Any) -> List[Any]: ... def check(self, **kwargs: Any) -> List[Any]: ...
opts: Any = ... opts: Any = ...
def deconstruct(self) -> Tuple[Optional[str], str, List[Any], Dict[str, str]]: ...
def get_forward_related_filter(self, obj: Model) -> Dict[str, Union[int, UUID]]: ... def get_forward_related_filter(self, obj: Model) -> Dict[str, Union[int, UUID]]: ...
def get_reverse_related_filter(self, obj: Model) -> Q: ... def get_reverse_related_filter(self, obj: Model) -> Q: ...
@property @property
@@ -76,7 +75,7 @@ class RelatedField(FieldCacheMixin, Field[_ST, _GT]):
@property @property
def target_field(self) -> Field: ... def target_field(self) -> Field: ...
class ForeignObject(RelatedField): class ForeignObject(RelatedField[_ST, _GT]):
def __init__( def __init__(
self, self,
to: Union[Type[Model], str], to: Union[Type[Model], str],
@@ -109,7 +108,7 @@ class ForeignObject(RelatedField):
error_messages: Optional[_ErrorMessagesToOverride] = ..., error_messages: Optional[_ErrorMessagesToOverride] = ...,
): ... ): ...
class ForeignKey(RelatedField[_ST, _GT]): class ForeignKey(ForeignObject[_ST, _GT]):
_pyi_private_set_type: Union[Any, Combinable] _pyi_private_set_type: Union[Any, Combinable]
_pyi_private_get_type: Any _pyi_private_get_type: Any
def __init__( def __init__(
@@ -185,10 +184,6 @@ class ManyToManyField(RelatedField[_ST, _GT]):
_pyi_private_set_type: Sequence[Any] _pyi_private_set_type: Sequence[Any]
_pyi_private_get_type: RelatedManager[Any] _pyi_private_get_type: RelatedManager[Any]
many_to_many: bool = ...
many_to_one: bool = ...
one_to_many: bool = ...
one_to_one: bool = ...
rel_class: Any = ... rel_class: Any = ...
description: Any = ... description: Any = ...
has_null_arg: Any = ... has_null_arg: Any = ...
@@ -228,7 +223,6 @@ class ManyToManyField(RelatedField[_ST, _GT]):
error_messages: Optional[_ErrorMessagesToOverride] = ..., error_messages: Optional[_ErrorMessagesToOverride] = ...,
) -> None: ... ) -> None: ...
def check(self, **kwargs: Any) -> List[Any]: ... def check(self, **kwargs: Any) -> List[Any]: ...
def deconstruct(self) -> Tuple[Optional[str], str, List[Any], Dict[str, str]]: ...
def get_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ... def get_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ...
def get_reverse_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ... def get_reverse_path_info(self, filtered_relation: None = ...) -> List[PathInfo]: ...
m2m_db_table: Any = ... m2m_db_table: Any = ...

View File

@@ -17,6 +17,7 @@ from .text import (
StrIndex as StrIndex, StrIndex as StrIndex,
Replace as Replace, Replace as Replace,
Substr as Substr, Substr as Substr,
Reverse as Reverse,
) )
from .window import ( from .window import (
@@ -44,6 +45,7 @@ from .datetime import (
ExtractWeek as ExtractWeek, ExtractWeek as ExtractWeek,
ExtractWeekDay as ExtractWeekDay, ExtractWeekDay as ExtractWeekDay,
ExtractYear as ExtractYear, ExtractYear as ExtractYear,
ExtractIsoYear as ExtractIsoYear,
Trunc as Trunc, Trunc as Trunc,
TruncDate as TruncDate, TruncDate as TruncDate,
TruncDay as TruncDay, TruncDay as TruncDay,
@@ -58,4 +60,28 @@ from .datetime import (
Now as Now, Now as Now,
) )
from .comparison import Coalesce as Coalesce, Greatest as Greatest, Least as Least, Cast as Cast from .comparison import Coalesce as Coalesce, Greatest as Greatest, Least as Least, Cast as Cast, NullIf as NullIf
from .math import (
Abs as Abs,
ACos as ACos,
ASin as ASin,
ATan as ATan,
ATan2 as ATan2,
Ceil as Ceil,
Cos as Cos,
Cot as Cot,
Degrees as Degrees,
Floor as Floor,
Exp as Exp,
Ln as Ln,
Log as Log,
Mod as Mod,
Pi as Pi,
Power as Power,
Radians as Radians,
Round as Round,
Sin as Sin,
Sqrt as Sqrt,
Tan as Tan,
)

View File

@@ -9,3 +9,4 @@ class Cast(Func):
class Coalesce(Func): ... class Coalesce(Func): ...
class Greatest(Func): ... class Greatest(Func): ...
class Least(Func): ... class Least(Func): ...
class NullIf(Func): ...

View File

@@ -8,6 +8,7 @@ class TimezoneMixin:
class Extract(TimezoneMixin, Transform): ... class Extract(TimezoneMixin, Transform): ...
class ExtractYear(Extract): ... class ExtractYear(Extract): ...
class ExtractIsoYear(Extract): ...
class ExtractMonth(Extract): ... class ExtractMonth(Extract): ...
class ExtractDay(Extract): ... class ExtractDay(Extract): ...
class ExtractWeek(Extract): ... class ExtractWeek(Extract): ...

View File

@@ -0,0 +1,25 @@
from django.db.models.expressions import Func
from django.db.models.functions.mixins import FixDecimalInputMixin, NumericOutputFieldMixin
from django.db.models.lookups import Transform
class Abs(Transform): ...
class ACos(NumericOutputFieldMixin, Transform): ...
class ASin(NumericOutputFieldMixin, Transform): ...
class ATan(NumericOutputFieldMixin, Transform): ...
class ATan2(NumericOutputFieldMixin, Func): ...
class Ceil(Transform): ...
class Cos(NumericOutputFieldMixin, Transform): ...
class Cot(NumericOutputFieldMixin, Transform): ...
class Degrees(NumericOutputFieldMixin, Transform): ...
class Exp(NumericOutputFieldMixin, Transform): ...
class Floor(Transform): ...
class Ln(NumericOutputFieldMixin, Transform): ...
class Log(FixDecimalInputMixin, NumericOutputFieldMixin, Func): ...
class Mod(FixDecimalInputMixin, NumericOutputFieldMixin, Func): ...
class Pi(NumericOutputFieldMixin, Func): ...
class Power(NumericOutputFieldMixin, Func): ...
class Radians(NumericOutputFieldMixin, Transform): ...
class Round(Transform): ...
class Sin(NumericOutputFieldMixin, Transform): ...
class Sqrt(NumericOutputFieldMixin, Transform): ...
class Tan(NumericOutputFieldMixin, Transform): ...

View File

@@ -0,0 +1,3 @@
class FixDecimalInputMixin: ...
class FixDurationInputMixin: ...
class NumericOutputFieldMixin: ...

View File

@@ -54,3 +54,4 @@ class Substr(Func):
class Trim(Transform): ... class Trim(Transform): ...
class Upper(Transform): ... class Upper(Transform): ...
class Reverse(Transform): ...

View File

@@ -105,3 +105,5 @@ class SQLCompiler:
) -> Optional[Any]: ... ) -> Optional[Any]: ...
def as_subquery_condition(self, alias: str, columns: List[str], compiler: SQLCompiler) -> Tuple[str, Tuple]: ... def as_subquery_condition(self, alias: str, columns: List[str], compiler: SQLCompiler) -> Tuple[str, Tuple]: ...
def explain_query(self) -> Iterator[str]: ... def explain_query(self) -> Iterator[str]: ...
def cursor_iter(cursor: Any, sentinel: Any, col_count: Optional[int], itersize: int) -> Iterator[Any]: ...

View File

@@ -9,6 +9,7 @@ from django.db.models.sql.datastructures import BaseTable
from django.db.models.sql.where import WhereNode from django.db.models.sql.where import WhereNode
from django.db.models import Expression, Field, FilteredRelation, Model, Q, QuerySet from django.db.models import Expression, Field, FilteredRelation, Model, Q, QuerySet
from django.db.models.expressions import Combinable
JoinInfo = namedtuple("JoinInfo", ["final_field", "targets", "opts", "joins", "path", "transform_function"]) JoinInfo = namedtuple("JoinInfo", ["final_field", "targets", "opts", "joins", "path", "transform_function"])
@@ -46,6 +47,7 @@ class Query:
used_aliases: Set[str] = ... used_aliases: Set[str] = ...
filter_is_sticky: bool = ... filter_is_sticky: bool = ...
subquery: bool = ... subquery: bool = ...
group_by: Optional[Union[Sequence[Combinable], Sequence[str], bool]] = ...
order_by: Tuple = ... order_by: Tuple = ...
distinct: bool = ... distinct: bool = ...
distinct_fields: Tuple = ... distinct_fields: Tuple = ...
@@ -110,6 +112,7 @@ class Query:
) -> Tuple[WhereNode, List[Any]]: ... ) -> Tuple[WhereNode, List[Any]]: ...
def add_filter(self, filter_clause: Tuple[str, Union[List[int], List[str]]]) -> None: ... def add_filter(self, filter_clause: Tuple[str, Union[List[int], List[str]]]) -> None: ...
def add_q(self, q_object: Q) -> None: ... def add_q(self, q_object: Q) -> None: ...
def build_where(self, q_object: Q) -> Any: ...
def build_filtered_relation_q( def build_filtered_relation_q(
self, q_object: Q, reuse: Set[str], branch_negated: bool = ..., current_negated: bool = ... self, q_object: Q, reuse: Set[str], branch_negated: bool = ..., current_negated: bool = ...
) -> WhereNode: ... ) -> WhereNode: ...

View File

@@ -1,4 +1,5 @@
from typing import Any, Callable, Optional, overload, TypeVar from contextlib import contextmanager
from typing import Any, Callable, Optional, overload, TypeVar, Iterator
from django.db import ProgrammingError from django.db import ProgrammingError
@@ -6,16 +7,18 @@ class TransactionManagementError(ProgrammingError): ...
def get_connection(using: Optional[str] = ...) -> Any: ... def get_connection(using: Optional[str] = ...) -> Any: ...
def get_autocommit(using: Optional[str] = ...) -> bool: ... def get_autocommit(using: Optional[str] = ...) -> bool: ...
def set_autocommit(autocommit: bool, using: None = ...) -> Any: ... def set_autocommit(autocommit: bool, using: Optional[str] = ...) -> Any: ...
def commit(using: None = ...) -> Any: ... def commit(using: Optional[str] = ...) -> Any: ...
def rollback(using: None = ...) -> Any: ... def rollback(using: Optional[str] = ...) -> Any: ...
def savepoint(using: None = ...) -> str: ... def savepoint(using: Optional[str] = ...) -> str: ...
def savepoint_rollback(sid: str, using: None = ...) -> None: ... def savepoint_rollback(sid: str, using: Optional[str] = ...) -> None: ...
def savepoint_commit(sid: Any, using: Optional[Any] = ...) -> None: ... def savepoint_commit(sid: Any, using: Optional[Any] = ...) -> None: ...
def clean_savepoints(using: Optional[Any] = ...) -> None: ... def clean_savepoints(using: Optional[Any] = ...) -> None: ...
def get_rollback(using: None = ...) -> bool: ... def get_rollback(using: Optional[str] = ...) -> bool: ...
def set_rollback(rollback: bool, using: Optional[str] = ...) -> None: ... def set_rollback(rollback: bool, using: Optional[str] = ...) -> None: ...
def on_commit(func: Callable, using: None = ...) -> None: ... @contextmanager
def mark_for_rollback_on_error(using: Optional[str] = ...) -> Iterator[None]: ...
def on_commit(func: Callable, using: Optional[str] = ...) -> None: ...
_C = TypeVar("_C", bound=Callable) # Any callable _C = TypeVar("_C", bound=Callable) # Any callable

View File

@@ -1,4 +1,4 @@
from typing import Any, Dict, List, Optional from typing import Any, Dict, Iterable, List, Optional
DEFAULT_DB_ALIAS: str DEFAULT_DB_ALIAS: str
DJANGO_VERSION_PICKLE_KEY: str DJANGO_VERSION_PICKLE_KEY: str
@@ -28,3 +28,8 @@ class ConnectionHandler:
def __iter__(self): ... def __iter__(self): ...
def all(self) -> List[Any]: ... def all(self) -> List[Any]: ...
def close_all(self) -> None: ... def close_all(self) -> None: ...
class ConnectionRouter:
def __init__(self, routers: Optional[Iterable[Any]] = ...) -> None: ...
@property
def routers(self) -> List[Any]: ...

View File

@@ -1,12 +1,16 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from decimal import Decimal from decimal import Decimal
from typing import Any, Callable, List, Optional, Pattern, Sequence, Type, Union from typing import Any, Callable, List, Optional, Pattern, Sequence, Type, Union, Tuple, Iterable
from django.core.validators import BaseValidator from django.core.validators import BaseValidator
from django.forms.boundfield import BoundField from django.forms.boundfield import BoundField
from django.forms.forms import BaseForm from django.forms.forms import BaseForm
from django.forms.widgets import Widget from django.forms.widgets import Widget
_Choice = Tuple[Any, str]
_ChoiceNamedGroup = Tuple[str, Iterable[_Choice]]
_FieldChoices = Iterable[Union[_Choice, _ChoiceNamedGroup]]
class Field: class Field:
initial: Any initial: Any
label: Optional[str] label: Optional[str]
@@ -23,6 +27,9 @@ class Field:
localize: bool = ... localize: bool = ...
error_messages: Any = ... error_messages: Any = ...
validators: List[BaseValidator] = ... validators: List[BaseValidator] = ...
max_length: Optional[Union[int, str]] = ...
choices: _FieldChoices = ...
base_field: Field
def __init__( def __init__(
self, self,
*, *,
@@ -47,9 +54,9 @@ class Field:
def widget_attrs(self, widget: Widget) -> Any: ... def widget_attrs(self, widget: Widget) -> Any: ...
def has_changed(self, initial: Any, data: Any) -> bool: ... def has_changed(self, initial: Any, data: Any) -> bool: ...
def get_bound_field(self, form: BaseForm, field_name: str) -> BoundField: ... def get_bound_field(self, form: BaseForm, field_name: str) -> BoundField: ...
def deconstruct(self) -> Any: ...
class CharField(Field): class CharField(Field):
max_length: Optional[Union[int, str]] = ...
min_length: Optional[Union[int, str]] = ... min_length: Optional[Union[int, str]] = ...
strip: bool = ... strip: bool = ...
empty_value: Optional[str] = ... empty_value: Optional[str] = ...
@@ -171,7 +178,6 @@ class RegexField(CharField):
class EmailField(CharField): ... class EmailField(CharField): ...
class FileField(Field): class FileField(Field):
max_length: Optional[int] = ...
allow_empty_file: bool = ... allow_empty_file: bool = ...
def __init__( def __init__(
self, self,

View File

@@ -1,9 +1,6 @@
from datetime import datetime
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Type, Union from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Type, Union
from django.core.exceptions import ValidationError as ValidationError from django.core.exceptions import ValidationError as ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models.query import QuerySet
from django.forms.boundfield import BoundField from django.forms.boundfield import BoundField
from django.forms.fields import Field from django.forms.fields import Field
from django.forms.renderers import BaseRenderer from django.forms.renderers import BaseRenderer

View File

@@ -1,8 +1,8 @@
from io import BytesIO from io import BytesIO
from typing import Any, BinaryIO, Dict, Iterable, List, Mapping, Optional, Pattern, Tuple, Union, overload from typing import Any, BinaryIO, Dict, Iterable, List, Mapping, Optional, Pattern, Set, Tuple, Union, overload
from django.contrib.sessions.backends.base import SessionBase from django.contrib.sessions.backends.base import SessionBase
from django.utils.datastructures import ImmutableList, MultiValueDict from django.utils.datastructures import CaseInsensitiveMapping, ImmutableList, MultiValueDict
from django.core.files import uploadedfile, uploadhandler from django.core.files import uploadedfile, uploadhandler
from django.urls import ResolverMatch from django.urls import ResolverMatch
@@ -15,6 +15,13 @@ class RawPostDataException(Exception): ...
UploadHandlerList = Union[List[uploadhandler.FileUploadHandler], ImmutableList[uploadhandler.FileUploadHandler]] UploadHandlerList = Union[List[uploadhandler.FileUploadHandler], ImmutableList[uploadhandler.FileUploadHandler]]
class HttpHeaders(CaseInsensitiveMapping):
HTTP_PREFIX: str = ...
UNPREFIXED_HEADERS: Set[str] = ...
def __init__(self, environ: Mapping[str, Any]) -> None: ...
@classmethod
def parse_header_name(cls, header: str) -> Optional[str]: ...
class HttpRequest(BytesIO): class HttpRequest(BytesIO):
GET: QueryDict = ... GET: QueryDict = ...
POST: QueryDict = ... POST: QueryDict = ...
@@ -48,6 +55,8 @@ class HttpRequest(BytesIO):
self, META: Mapping[str, Any], post_data: BinaryIO self, META: Mapping[str, Any], post_data: BinaryIO
) -> Tuple[QueryDict, MultiValueDict[str, uploadedfile.UploadedFile]]: ... ) -> Tuple[QueryDict, MultiValueDict[str, uploadedfile.UploadedFile]]: ...
@property @property
def headers(self) -> HttpHeaders: ...
@property
def body(self) -> bytes: ... def body(self) -> bytes: ...
def _load_post_and_files(self) -> None: ... def _load_post_and_files(self) -> None: ...

View File

@@ -47,6 +47,7 @@ class SimpleTestCase(unittest.TestCase):
client_class: Any = ... client_class: Any = ...
client: Client client: Client
allow_database_queries: bool = ... allow_database_queries: bool = ...
databases: Set[str] = ...
def __call__(self, result: Optional[unittest.TestResult] = ...) -> None: ... def __call__(self, result: Optional[unittest.TestResult] = ...) -> None: ...
def settings(self, **kwargs: Any) -> Any: ... def settings(self, **kwargs: Any) -> Any: ...
def modify_settings(self, **kwargs: Any) -> Any: ... def modify_settings(self, **kwargs: Any) -> Any: ...
@@ -197,8 +198,10 @@ class LiveServerThread(threading.Thread):
class LiveServerTestCase(TransactionTestCase): class LiveServerTestCase(TransactionTestCase):
host: str = ... host: str = ...
port: int = ... port: int = ...
server_thread_class: Any = ... server_thread_class: Type[Any] = ...
server_thread: Any
static_handler: Any = ... static_handler: Any = ...
@classmethod
def live_server_url(cls): ... def live_server_url(cls): ...
class SerializeMixin: class SerializeMixin:

View File

@@ -7,10 +7,14 @@ from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Ty
from django.apps.registry import Apps from django.apps.registry import Apps
from django.core.checks.registry import CheckRegistry from django.core.checks.registry import CheckRegistry
from django.db.models.lookups import Lookup, Transform
from django.test.runner import DiscoverRunner from django.test.runner import DiscoverRunner
from django.test.testcases import SimpleTestCase from django.test.testcases import SimpleTestCase
from django.conf import LazySettings, Settings from django.conf import LazySettings, Settings
from django.db.models.query_utils import RegisterLookupMixin
from django.db.models.fields import Field
_TestClass = Type[SimpleTestCase] _TestClass = Type[SimpleTestCase]
_DecoratedTest = Union[Callable, _TestClass] _DecoratedTest = Union[Callable, _TestClass]
@@ -130,3 +134,7 @@ def teardown_databases(
old_config: Iterable[Tuple[Any, str, bool]], verbosity: int, parallel: int = ..., keepdb: bool = ... old_config: Iterable[Tuple[Any, str, bool]], verbosity: int, parallel: int = ..., keepdb: bool = ...
) -> None: ... ) -> None: ...
def require_jinja2(test_func: Callable) -> Callable: ... def require_jinja2(test_func: Callable) -> Callable: ...
@contextmanager
def register_lookup(
field: Type[RegisterLookupMixin], *lookups: Type[Union[Lookup, Transform]], lookup_name: Optional[str] = ...
) -> Iterator[None]: ...

View File

@@ -13,6 +13,7 @@ class ResolverMatch:
namespaces: List[str] = ... namespaces: List[str] = ...
namespace: str = ... namespace: str = ...
view_name: str = ... view_name: str = ...
route: str = ...
def __init__( def __init__(
self, self,
func: Callable, func: Callable,

View File

@@ -60,3 +60,13 @@ class DictWrapper(Dict[str, _V]):
def __init__(self, data: Mapping[str, _V], func: Callable[[_V], _V], prefix: str) -> None: ... def __init__(self, data: Mapping[str, _V], func: Callable[[_V], _V], prefix: str) -> None: ...
@overload @overload
def __init__(self, data: Iterable[Tuple[str, _V]], func: Callable[[_V], _V], prefix: str) -> None: ... def __init__(self, data: Iterable[Tuple[str, _V]], func: Callable[[_V], _V], prefix: str) -> None: ...
_T = TypeVar("_T", bound="CaseInsensitiveMapping")
class CaseInsensitiveMapping(Mapping):
def __init__(self, data: Any) -> None: ...
def __getitem__(self, key: str) -> Any: ...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[str]: ...
def copy(self: _T) -> _T:
return self

View File

@@ -1,10 +1,10 @@
from typing import Any, Callable, Optional, Type from typing import Any, Callable, Optional, Type
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest from django.http.request import HttpRequest
from django.http.response import HttpResponse from django.http.response import HttpResponse
class RemovedInDjango30Warning(PendingDeprecationWarning): ... class RemovedInDjango30Warning(PendingDeprecationWarning): ...
class RemovedInDjango31Warning(PendingDeprecationWarning): ...
class RemovedInNextVersionWarning(DeprecationWarning): ... class RemovedInNextVersionWarning(DeprecationWarning): ...
class warn_about_renamed_method: class warn_about_renamed_method:

View File

@@ -1,6 +1,6 @@
[mypy] [mypy]
strict_optional = True strict_optional = True
ignore_missing_imports = True ignore_missing_imports = False
check_untyped_defs = True check_untyped_defs = True
warn_no_return = False warn_no_return = False
show_traceback = True show_traceback = True

View File

@@ -30,6 +30,7 @@ IGNORED_ERRORS = {
'Need type annotation for', 'Need type annotation for',
'Invalid value for a to= parameter', 'Invalid value for a to= parameter',
'already defined (possibly by an import)', 'already defined (possibly by an import)',
'already defined on line',
'gets multiple values for keyword argument', 'gets multiple values for keyword argument',
'Cannot assign to a type', 'Cannot assign to a type',
re.compile(r'Cannot assign to class variable "[a-z_]+" via instance'), re.compile(r'Cannot assign to class variable "[a-z_]+" via instance'),
@@ -52,7 +53,7 @@ IGNORED_ERRORS = {
# cookies private attribute # cookies private attribute
'full_clean" of "Model" does not return a value', 'full_clean" of "Model" does not return a value',
# private members # private members
re.compile(r'has no attribute "|\'_[a-z][a-z_]+"|\''), re.compile(r'has no attribute ("|\')_[a-zA-Z_]+("|\')'),
'Invalid base class', 'Invalid base class',
'ValuesIterable', 'ValuesIterable',
'Value of type "Optional[Dict[str, Any]]" is not indexable', 'Value of type "Optional[Dict[str, Any]]" is not indexable',
@@ -61,8 +62,37 @@ IGNORED_ERRORS = {
+ 'expected "Union[str, bytes, bytearray]"', + 'expected "Union[str, bytes, bytearray]"',
'Incompatible types in assignment (expression has type "None", variable has type Module)', 'Incompatible types in assignment (expression has type "None", variable has type Module)',
'note:', 'note:',
'undefined in superclass', '\'Settings\' object has no attribute',
'**Dict' re.compile(r'"Type\[Model\]" has no attribute "[a-zA-Z_]+"'),
re.compile(r'Item "None" of "[a-zA-Z_ ,\[\]]+" has no attribute'),
'Xtemplate',
re.compile(r'has no attribute "get_[a-z_]+_display"'),
re.compile(r'has no attribute "get_next_by_[a-z_]+"'),
re.compile(r'has no attribute "get_previous_by_[a-z_]+"'),
re.compile(r'has no attribute "set_[a-z_]+_order"'),
'psycopg2',
'PIL',
'has no attribute "getvalue"',
'MySQLdb',
'sqlparse',
'selenium',
'oracle',
'mysql',
'sqlite3',
'LogEntry',
'"HttpResponse" has no attribute',
'"HttpResponseBase" has no attribute',
'"object" has no attribute',
'"HttpRequest" has no attribute',
'xml.dom',
'numpy',
'tblib',
# TODO: values().annotate()
'TypedDict',
'namedtuple',
'has no attribute "deconstruct"',
'**Dict',
'undefined in superclass'
], ],
'admin_scripts': [ 'admin_scripts': [
'Incompatible types in assignment (expression has type "Callable[' 'Incompatible types in assignment (expression has type "Callable['
@@ -71,22 +101,36 @@ IGNORED_ERRORS = {
re.compile(r'Argument [0-9] to "lookup_field" has incompatible type'), re.compile(r'Argument [0-9] to "lookup_field" has incompatible type'),
'MockModelAdmin', 'MockModelAdmin',
'Incompatible types in assignment (expression has type "str", variable has type "Callable[..., Any]")', 'Incompatible types in assignment (expression has type "str", variable has type "Callable[..., Any]")',
'"Article" has no attribute "non_field"'
], ],
'admin_views': [ 'admin_views': [
'Argument 1 to "FileWrapper" has incompatible type "StringIO"; expected "IO[bytes]"', 'Argument 1 to "FileWrapper" has incompatible type "StringIO"; expected "IO[bytes]"',
'Incompatible types in assignment', 'Incompatible types in assignment',
'"object" not callable', '"object" not callable',
'"Type[SubscriberAdmin]" has no attribute "overridden"'
],
'admin_ordering': [
'"Band" has no attribute "field"'
], ],
'aggregation': [ 'aggregation': [
'Incompatible type for "contact" of "Book" (got "Optional[Author]", expected "Union[Author, Combinable]")', 'Incompatible type for "contact" of "Book" (got "Optional[Author]", expected "Union[Author, Combinable]")',
'Incompatible type for "publisher" of "Book" (got "Optional[Publisher]", ' 'Incompatible type for "publisher" of "Book" (got "Optional[Publisher]", '
+ 'expected "Union[Publisher, Combinable]")' + 'expected "Union[Publisher, Combinable]")',
'has no attribute'
],
'aggregation_regress': [
'has no attribute'
], ],
'annotations': [ 'annotations': [
'Incompatible type for "store" of "Employee" (got "Optional[Store]", expected "Union[Store, Combinable]")' 'Incompatible type for "store" of "Employee" (got "Optional[Store]", expected "Union[Store, Combinable]")',
'"Book" has no attribute',
'"Employee" has no attribute',
'Item "Book" of',
'Item "Ticket" of'
], ],
'apps': [ 'apps': [
'Incompatible types in assignment (expression has type "str", target has type "type")', 'Incompatible types in assignment (expression has type "str", target has type "type")',
'"Callable[[bool, bool], List[Type[Model]]]" has no attribute "cache_clear"'
], ],
'auth_tests': [ 'auth_tests': [
'"PasswordValidator" has no attribute "min_length"', '"PasswordValidator" has no attribute "min_length"',
@@ -97,11 +141,31 @@ IGNORED_ERRORS = {
], ],
'basic': [ 'basic': [
'Unexpected keyword argument "unknown_kwarg" for "refresh_from_db" of "Model"', 'Unexpected keyword argument "unknown_kwarg" for "refresh_from_db" of "Model"',
'Unexpected attribute "foo" for model "Article"' 'Unexpected attribute "foo" for model "Article"',
'has no attribute'
],
'backends': [
'"DatabaseError" has no attribute "pgcode"'
],
'check_framework': [
'base class "Model" defined the type as "Callable',
'Cannot determine type of \'check\''
],
'constraints': [
'Argument "condition" to "UniqueConstraint" has incompatible type "str"; expected "Optional[Q]"'
],
'contenttypes_tests': [
'Item "Model" of "Union[GenericForeignKey, Model, None]" has no attribute'
], ],
'custom_lookups': [ 'custom_lookups': [
'in base class "SQLFuncMixin"' 'in base class "SQLFuncMixin"'
], ],
'custom_pk': [
'"Employee" has no attribute "id"'
],
'custom_managers': [
'"Type[Book]" has no attribute "objects"'
],
'csrf_tests': [ 'csrf_tests': [
'Incompatible types in assignment (expression has type "property", ' + 'Incompatible types in assignment (expression has type "property", ' +
'base class "HttpRequest" defined the type as "QueryDict")' 'base class "HttpRequest" defined the type as "QueryDict")'
@@ -113,24 +177,67 @@ IGNORED_ERRORS = {
'Too many arguments for "refresh_from_db" of "Model"' 'Too many arguments for "refresh_from_db" of "Model"'
], ],
'dispatch': [ 'dispatch': [
'Argument 1 to "connect" of "Signal" has incompatible type "object"; expected "Callable[..., Any]"' 'Argument 1 to "connect" of "Signal" has incompatible type "object"; expected "Callable[..., Any]"',
'Item "str" of "Union[ValueError, str]" has no attribute "args"'
],
'deprecation': [
'"Manager" has no attribute "old"',
'"Manager" has no attribute "new"'
], ],
'db_functions': [ 'db_functions': [
'for **', 'for **',
'expected "float"', 'expected "float"',
'Incompatible types in assignment (expression has type "Optional[FloatModel]", variable has type "FloatModel")' 'Incompatible types in assignment (expression has type "Optional[FloatModel]", variable has type "FloatModel")',
re.compile(r'Item .* has no attribute'),
'Module has no attribute',
'Module \'datetime\' has no attribute',
'"DTModel" has no attribute',
'"Author" has no attribute',
'"FloatModel" has no attribute',
'"Article" has no attribute'
],
'decorators': [
'DummyRequest',
'DummyUser',
'"Type[object]" has no attribute "method"'
],
'defer_regress': [
'"Base" has no attribute "derived"'
],
'delete': [
'"RChild" has no attribute',
'"Child" has no attribute "parent_ptr"'
],
'expressions': [
'Item "Experiment" of',
'Item "Time" of',
'"Experiment" has no attribute',
'"Time" has no attribute',
],
'expressions_case': [
'"CaseTestModel" has no attribute "selected"'
],
'expressions_window': [
'has incompatible type "str"'
],
'file_uploads': [
'"Iterable[Any]" has no attribute',
'"IO[Any]" has no attribute'
], ],
'file_storage': [ 'file_storage': [
'Incompatible types in assignment (expression has type "Callable[[], Any]"' 'Incompatible types in assignment (expression has type "Callable[[], Any]"'
], ],
'files': [ 'files': [
'"file_move_safe" does not return a value', '"file_move_safe" does not return a value',
'Argument 1 to "unlink" has incompatible type "Optional[str]"; expected "Union[bytes, str, _PathLike[Any]]"', 'Incompatible types in assignment (expression has type "IOBase", variable has type "File")',
'Incompatible types in assignment (expression has type "IOBase", variable has type "File")' 'Module has no attribute "open"'
], ],
'fixtures': [ 'fixtures': [
'Incompatible types in assignment (expression has type "int", target has type "Iterable[str]")' 'Incompatible types in assignment (expression has type "int", target has type "Iterable[str]")'
], ],
'flatpages_tests': [
'"Site" has no attribute "add"',
],
'forms_tests': [ 'forms_tests': [
'List item 0 has incompatible type "Jinja2"; expected "DjangoTemplates"', 'List item 0 has incompatible type "Jinja2"; expected "DjangoTemplates"',
'Not enough arguments for format string', 'Not enough arguments for format string',
@@ -152,6 +259,15 @@ IGNORED_ERRORS = {
'Incompatible types in assignment (expression has type "Type[Textarea]", ' 'Incompatible types in assignment (expression has type "Type[Textarea]", '
+ 'base class "Field" defined the type as "Widget")', + 'base class "Field" defined the type as "Widget")',
'Incompatible types in assignment (expression has type "SimpleUploadedFile", variable has type "BinaryIO")', 'Incompatible types in assignment (expression has type "SimpleUploadedFile", variable has type "BinaryIO")',
'has no attribute',
'Name \'forms.Field\' is not defined'
],
'foreign_object': [
'"Person" has no attribute',
'"SlugPage" has no attribute'
],
'from_db_value': [
'"Cash" has no attribute'
], ],
'get_object_or_404': [ 'get_object_or_404': [
'Argument 1 to "get_object_or_404" has incompatible type "str"; ' 'Argument 1 to "get_object_or_404" has incompatible type "str"; '
@@ -160,11 +276,26 @@ IGNORED_ERRORS = {
+ 'expected "Union[Type[<nothing>], QuerySet[<nothing>, <nothing>]]"', + 'expected "Union[Type[<nothing>], QuerySet[<nothing>, <nothing>]]"',
'CustomClass' 'CustomClass'
], ],
'generic_relations': [
'has no attribute "id"',
'has no attribute "pk"'
],
'generic_relations_regress': [
'"HasLinkThing" has no attribute',
'"Link" has no attribute'
],
'humanize_tests': [ 'humanize_tests': [
'Argument 1 to "append" of "list" has incompatible type "None"; expected "str"' 'Argument 1 to "append" of "list" has incompatible type "None"; expected "str"'
], ],
'inline_formsets': [
'has no attribute "form"'
],
'logging_tests': [
'"Handler" has no attribute "stream"'
],
'lookup': [ 'lookup': [
'Unexpected keyword argument "headline__startswith" for "in_bulk" of "QuerySet"', 'Unexpected keyword argument "headline__startswith" for "in_bulk" of "QuerySet"',
'\'flat\' is not valid when values_list is called with more than one field.'
], ],
'm2o_recursive': [ 'm2o_recursive': [
'Incompatible type for "id" of "Category" (got "None", expected "int")' 'Incompatible type for "id" of "Category" (got "None", expected "int")'
@@ -173,6 +304,9 @@ IGNORED_ERRORS = {
'Incompatible type for "parent" of "Child" (got "None", expected "Union[Parent, Combinable]")', 'Incompatible type for "parent" of "Child" (got "None", expected "Union[Parent, Combinable]")',
'Incompatible type for "parent" of "Child" (got "Child", expected "Union[Parent, Combinable]")' 'Incompatible type for "parent" of "Child" (got "Child", expected "Union[Parent, Combinable]")'
], ],
'managers_regress': [
'"Type[AbstractBase3]" has no attribute "objects"'
],
'middleware_exceptions': [ 'middleware_exceptions': [
'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any]"; expected "str"' 'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any]"; expected "str"'
], ],
@@ -188,12 +322,31 @@ IGNORED_ERRORS = {
'Incompatible import of "Person"', 'Incompatible import of "Person"',
'Incompatible types in assignment (expression has type "FloatModel", variable has type ' 'Incompatible types in assignment (expression has type "FloatModel", variable has type '
'"Union[float, int, str, Combinable]")', '"Union[float, int, str, Combinable]")',
'"UUIDGrandchild" has no attribute "uuidchild_ptr_id"',
'"Person" has no attribute',
'"Foo" has no attribute',
],
'model_formsets': [
'has no attribute'
], ],
'model_indexes': [ 'model_indexes': [
'Argument "condition" to "Index" has incompatible type "str"; expected "Optional[Q]"' 'Argument "condition" to "Index" has incompatible type "str"; expected "Optional[Q]"'
], ],
'model_inheritance_regress': [
'"Restaurant" has no attribute',
'"ArticleWithAuthor" has no attribute',
'"Person" has no attribute',
'"MessyBachelorParty" has no attribute',
'"Place" has no attribute',
'"ItalianRestaurant" has no attribute'
],
'model_meta': [
'"Field[Any, Any]" has no attribute "many_to_many"'
],
'model_regress': [ 'model_regress': [
re.compile(r'Incompatible type for "[a-z]+" of "Worker" \(got "int", expected') re.compile(r'Incompatible type for "[a-z]+" of "Worker" \(got "int", expected'),
'"PickledModel" has no attribute',
'"Department" has no attribute'
], ],
'modeladmin': [ 'modeladmin': [
'BandAdmin', 'BandAdmin',
@@ -213,9 +366,23 @@ IGNORED_ERRORS = {
'Dict entry 0 has incompatible type "Any": "Set[Tuple[Any, ...]]"; expected "Any": "str"', 'Dict entry 0 has incompatible type "Any": "Set[Tuple[Any, ...]]"; expected "Any": "str"',
'Argument 1 to "RunPython" has incompatible type "str"; expected "Callable[..., Any]"', 'Argument 1 to "RunPython" has incompatible type "str"; expected "Callable[..., Any]"',
'Argument 1 to "append" of "list" has incompatible type "AddIndex"; expected "CreateModel"', 'Argument 1 to "append" of "list" has incompatible type "AddIndex"; expected "CreateModel"',
'Argument 2 to "register_serializer" of "MigrationWriter" has incompatible type '
+ '"Type[TestModel1]"; expected "Type[BaseSerializer]"',
'Argument 1 to "append" of "list" has incompatible type "AddConstraint"; expected "CreateModel"'
], ],
'multiple_database': [ 'multiple_database': [
'Too many arguments for "create" of "QuerySet"' 'Too many arguments for "create" of "QuerySet"',
'"User" has no attribute "userprofile"',
'Item "GenericForeignKey" of',
'Item "Model" of'
],
'known_related_objects': [
'"Pool" has no attribute'
],
'one_to_one': [
'"Place" has no attribute',
'"Type[Place]" has no attribute',
'"ManualPrimaryKey" has no attribute'
], ],
'postgres_tests': [ 'postgres_tests': [
'DummyArrayField', 'DummyArrayField',
@@ -228,10 +395,27 @@ IGNORED_ERRORS = {
+ 'expected "Union[Sequence[int], Combinable]")', + 'expected "Union[Sequence[int], Combinable]")',
re.compile(r'Incompatible types in assignment \(expression has type "Type\[.+?\]", ' re.compile(r'Incompatible types in assignment \(expression has type "Type\[.+?\]", '
r'base class "(UnaccentTest|TrigramTest)" defined the type as "Type\[CharFieldModel\]"\)'), r'base class "(UnaccentTest|TrigramTest)" defined the type as "Type\[CharFieldModel\]"\)'),
'"Type[PostgreSQLModel]" has no attribute "objects"',
'("None" and "SearchQuery")',
# TODO:
'django.contrib.postgres.forms',
'django.contrib.postgres.aggregates',
], ],
'properties': [ 'properties': [
re.compile('Unexpected attribute "(full_name|full_name_2)" for model "Person"') re.compile('Unexpected attribute "(full_name|full_name_2)" for model "Person"')
], ],
'prefetch_related': [
'Incompatible types in assignment (expression has type "List[Room]", variable has type "QuerySet[Room, Room]")',
'"Person" has no attribute',
'"Author" has no attribute',
'"Book" has no attribute',
'Item "Room" of',
'"AuthorWithAge" has no attribute',
'has no attribute "read_by"'
],
'proxy_model_inheritance': [
'Incompatible import of "ProxyModel"'
],
'queries': [ 'queries': [
'Incompatible types in assignment (expression has type "None", variable has type "str")', 'Incompatible types in assignment (expression has type "None", variable has type "str")',
'Invalid index type "Optional[str]" for "Dict[str, int]"; expected type "str"', 'Invalid index type "Optional[str]" for "Dict[str, int]"; expected type "str"',
@@ -242,12 +426,15 @@ IGNORED_ERRORS = {
'Incompatible types in assignment (expression has type "ObjectC", variable has type "ObjectA")', 'Incompatible types in assignment (expression has type "ObjectC", variable has type "ObjectA")',
'Incompatible type for "objectb" of "ObjectC" (got "ObjectA", expected' 'Incompatible type for "objectb" of "ObjectC" (got "ObjectA", expected'
' "Union[ObjectB, Combinable, None, None]")', ' "Union[ObjectB, Combinable, None, None]")',
'"Note" has no attribute',
'"Ranking" has no attribute',
'"BaseUser" has no attribute',
'"Item" has no attribute',
"'flat' and 'named' can't be used together.",
], ],
'prefetch_related': [ 'queryset_pickle': [
'Incompatible types in assignment (expression has type "List[Room]", variable has type "QuerySet[Room, Room]")', 'RelatedObjectDoesNotExist',
], '"Type[Event]" has no attribute "happening"'
'proxy_model_inheritance': [
'Incompatible import of "ProxyModel"'
], ],
'requests': [ 'requests': [
'Incompatible types in assignment (expression has type "Dict[str, str]", variable has type "QueryDict")' 'Incompatible types in assignment (expression has type "Dict[str, str]", variable has type "QueryDict")'
@@ -267,28 +454,43 @@ IGNORED_ERRORS = {
'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any, Optional[Any], Any]"; ' 'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any, Optional[Any], Any]"; '
+ 'expected "Tuple[Any, Any, Any]"' + 'expected "Tuple[Any, Any, Any]"'
], ],
'sites_tests': [
'Item "RequestSite" of "Union[Site, RequestSite]" has no attribute "id"'
],
'syndication_tests': [ 'syndication_tests': [
'List or tuple expected as variable arguments' 'List or tuple expected as variable arguments'
], ],
'sessions_tests': [ 'sessions_tests': [
'base class "SessionTestsMixin" defined the type as "None")', 'base class "SessionTestsMixin" defined the type as "None")',
'Incompatible types in assignment (expression has type "None", variable has type "int")', 'Incompatible types in assignment (expression has type "None", variable has type "int")',
'"AbstractBaseSession" has no attribute'
],
'select_related': [
'"Species" has no attribute',
'Item "object" of "Union[object, Any]" has no attribute "first"'
], ],
'select_related_onetoone': [ 'select_related_onetoone': [
'Incompatible types in assignment (expression has type "Parent2", variable has type "Parent1")', 'Incompatible types in assignment (expression has type "Parent2", variable has type "Parent1")',
'has no attribute'
], ],
'servers': [ 'servers': [
re.compile('Argument [0-9] to "WSGIRequestHandler"') re.compile('Argument [0-9] to "WSGIRequestHandler"'),
'"HTTPResponse" has no attribute',
'"type" has no attribute',
'"WSGIRequest" has no attribute "makefile"'
], ],
'template_tests': [ 'template_tests': [
re.compile(r'Argument 1 to "[a-zA-Z_]+" has incompatible type "int"; expected "str"'), re.compile(r'Argument 1 to "[a-zA-Z_]+" has incompatible type "int"; expected "str"'),
'TestObject', 'TestObject',
'variable has type "Callable[[Any], Any]', 'variable has type "Callable[[Any], Any]',
'Value of type variable "AnyStr" of "urljoin" cannot be "Optional[str]"' 'Value of type variable "AnyStr" of "urljoin" cannot be "Optional[str]"',
'has no attribute "template_debug"',
"Module 'django.template.base' has no attribute 'TemplateSyntaxError'"
], ],
'template_backends': [ 'template_backends': [
'Incompatible import of "Jinja2" (imported name has type "Type[Jinja2]", local name has type "object")', 'Incompatible import of "Jinja2" (imported name has type "Type[Jinja2]", local name has type "object")',
'TemplateStringsTests', 'TemplateStringsTests',
"Cannot find module named 'DoesNotExist'"
], ],
'test_client': [ 'test_client': [
'Incompatible types in assignment (expression has type "HttpResponse", ' 'Incompatible types in assignment (expression has type "HttpResponse", '
@@ -305,6 +507,8 @@ IGNORED_ERRORS = {
'test_runner': [ 'test_runner': [
'Argument "result" to "run" of "TestCase" has incompatible type "RemoteTestResult"; ' 'Argument "result" to "run" of "TestCase" has incompatible type "RemoteTestResult"; '
+ 'expected "Optional[TestResult]"', + 'expected "Optional[TestResult]"',
'has no attribute "id"',
'MockTestRunner'
], ],
'transactions': [ 'transactions': [
'Incompatible types in assignment (expression has type "Thread", variable has type "Callable[[], Any]")' 'Incompatible types in assignment (expression has type "Thread", variable has type "Callable[[], Any]")'
@@ -313,8 +517,14 @@ IGNORED_ERRORS = {
'"object" not callable' '"object" not callable'
], ],
'user_commands': [ 'user_commands': [
'Incompatible types in assignment (expression has type "Callable[[Any, KwArg(Any)], Any]", variable has type' 'Incompatible types in assignment (expression has type "Callable[[Any, KwArg(Any)], Any]", variable has type',
'Cannot find module named \'user_commands.management.commands\''
], ],
'view_tests': [
'"EmailMessage" has no attribute "alternatives"',
'"Handler" has no attribute "include_html"',
"Module 'django.views.debug' has no attribute 'Path'"
]
} }
# Test folders to typecheck # Test folders to typecheck
TESTS_DIRS = [ TESTS_DIRS = [
@@ -339,6 +549,7 @@ TESTS_DIRS = [
'app_loading', 'app_loading',
'apps', 'apps',
# TODO: 'auth_tests', # TODO: 'auth_tests',
'backends',
'base', 'base',
'bash_completion', 'bash_completion',
'basic', 'basic',
@@ -348,6 +559,7 @@ TESTS_DIRS = [
'check_framework', 'check_framework',
'choices', 'choices',
'conditional_processing', 'conditional_processing',
'constraints',
'contenttypes_tests', 'contenttypes_tests',
'context_processors', 'context_processors',
'csrf_tests', 'csrf_tests',
@@ -459,9 +671,9 @@ TESTS_DIRS = [
'or_lookups', 'or_lookups',
'order_with_respect_to', 'order_with_respect_to',
'ordering', 'ordering',
'prefetch_related',
'pagination', 'pagination',
'postgres_tests', 'postgres_tests',
'prefetch_related',
'project_template', 'project_template',
'properties', 'properties',
'proxy_model_inheritance', 'proxy_model_inheritance',
@@ -515,7 +727,7 @@ TESTS_DIRS = [
'update_only_fields', 'update_only_fields',
'urlpatterns', 'urlpatterns',
# not annotatable without annotation in test # not annotatable without annotation in test
# TODO: 'urlpatterns_reverse', # 'urlpatterns_reverse',
'user_commands', 'user_commands',
# TODO: 'utils_tests', # TODO: 'utils_tests',
'validation', 'validation',