1
0
mirror of https://github.com/SpaceVim/SpaceVim.git synced 2025-04-13 22:59:15 +08:00

chore(jedi): use bundle deoplete_jedi

arty/typeshed/tests/stubtest_whitelists/py36.txt
This commit is contained in:
wsdjeg 2022-10-23 16:00:31 +08:00
parent a3bd1d31c7
commit 459d676373
1925 changed files with 111333 additions and 1 deletions

View File

@ -101,7 +101,7 @@ function! SpaceVim#layers#lang#python#plugins() abort
\ && !SpaceVim#layers#lsp#check_server('pyright')
\ && !SpaceVim#layers#lsp#check_server('pylsp')
if has('nvim')
call add(plugins, ['zchee/deoplete-jedi', { 'on_ft' : 'python'}])
call add(plugins, [g:_spacevim_root_dir . 'bundle/deoplete-jedi', { 'on_ft' : 'python'}])
" in neovim, we can use deoplete-jedi together with jedi-vim,
" but we need to disable the completions of jedi-vim.
let g:jedi#completions_enabled = 0

0
bundle/deoplete-jedi/.flake8 vendored Normal file
View File

View File

@ -0,0 +1,44 @@
# Problem summary
## Expected
## Environment Information
* OS:
* Neovim version:
## Provide a minimal init.vim with less than 50 lines (required)
```vim
" Use the following as a template.
set runtimepath+=~/path/to/deoplete.nvim/
set runtimepath+=~/path/to/deoplete-jedi/
let g:deoplete#enable_at_startup = 1
call deoplete#custom#source('jedi', 'is_debug_enabled', 1)
call deoplete#enable_logging('DEBUG', '/tmp/deoplete.log')
```
## Generate logfiles if appropriate
1. export NVIM_PYTHON_LOG_FILE=/tmp/nvim-log
2. export NVIM_PYTHON_LOG_LEVEL=DEBUG
3. nvim -u minimal.vimrc
Then look at and attach the files `/tmp/nvim-log_{PID}` and
`/tmp/deoplete.log` here.
## Steps to reproduce the issue after starting Neovim (required)
1.
2.
3.
## Screen shot (if possible)
## Upload the logfile(s)

66
bundle/deoplete-jedi/.gitignore vendored Normal file
View File

@ -0,0 +1,66 @@
### https://raw.github.com/github/gitignore//Python.gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#Ipython Notebook
.ipynb_checkpoints
.-rplugin~

20
bundle/deoplete-jedi/.travis.yml vendored Normal file
View File

@ -0,0 +1,20 @@
dist: xenial
language: python
python:
- '3.7'
cache: pip
install:
- pip3 install -q -U -r ./tests/requirements.txt
script:
- make test
notifications:
email: false
slack:
rooms:
secure: Kjl0kgnF4qcnW/wjk++HnmLGD0FeQLHeaFHAlmeN1Iql7z+I7cBaW35I4P0W0sgZPzF4y6LSReGlxtmEFlqNmmYll6SPw4n2BvNv2Ir+sSl6r61plQdTQsh6RlnW4lRQMZ8JSgP/E6jci3cuchCFWnN7miYP08vmJmKTh3MlW5TjksPpNx6B+zC0zr0JqjXNXZwaSXpQYrA0hwKt0pZOQbgPxEeRnUYEAqiJxR30GmSTZ8OxWHNupNWKtSxaYV1e8/6vcaq3iae6fsP6qceVmNZzPc/IUVXA8NNmu+TKZUaQEQAKWkIm8QJVY7cnHMBdfG56L/NgX7lwmv3cRq+1mDOxEGWtOfnQwQIeV3wRKK8yactQ5cCD32WE2cioAUnvwryjOjRG5Vt8aBuFINoxdz7KTcQye1JqrjDU14ob6JAQnLafClLDhTXht+/W6/UeUr9ZOAX1nVWuuLvIJsU1SP1Uvv/PvuLk+XDrBCunDZwWssRwn1q8pBnEubhe6vbOO134hAeF0/SMnWXKuL/knTL5aqICLQOhj+ooNpb+hU3D3phlHIddhufz8cAWSxR/eqnwQ4LkKfZa2L4DMW02dou8HMl973ft/g/DCdFXFGz53VYqD7V8Mpb2DQ7nkvqmsokSDNNs99cMIDV9LVI3QJGW8OR88wUgIlONl+795a0=

14
bundle/deoplete-jedi/Dockerfile vendored Normal file
View File

@ -0,0 +1,14 @@
FROM zchee/neovim:python
MAINTAINER zchee <zchee.io@gmail.com>
RUN pip3 install jedi \
&& git clone https://github.com/Shougo/deoplete.nvim /src/deoplete.nvim \
\
&& echo 'set rtp+=/src/deoplete.nvim' >> /root/.config/nvim/init.vim \
&& echo 'set rtp+=/src/deoplete-jedi' >> /root/.config/nvim/init.vim \
&& echo 'let g:deoplete#enable_at_startup = 1' >> /root/.config/nvim/init.vim \
&& echo 'let g:deoplete#auto_completion_start_length = 1' >> /root/.config/nvim/init.vim
COPY . /src/deoplete-jedi
RUN /src/run.sh

21
bundle/deoplete-jedi/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Koichi Shiraishi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

10
bundle/deoplete-jedi/Makefile vendored Normal file
View File

@ -0,0 +1,10 @@
RPLUGIN_PATH := ./rplugin/python3/deoplete/sources
all: test
test: flake8
flake8:
flake8 rplugin tests
.PHONY: test flake8

112
bundle/deoplete-jedi/README.md vendored Normal file
View File

@ -0,0 +1,112 @@
# deoplete-jedi
[deoplete.nvim](https://github.com/Shougo/deoplete.nvim) source for [jedi](https://github.com/davidhalter/jedi).
|| **Status** |
|:---:|:---:|
| **Travis CI** |[![Build Status](https://travis-ci.org/zchee/deoplete-jedi.svg?branch=master)](https://travis-ci.org/zchee/deoplete-jedi)|
| **Gitter** |[![Join the chat at https://gitter.im/zchee/deoplete-jedi](https://badges.gitter.im/zchee/deoplete-jedi.svg)](https://gitter.im/zchee/deoplete-jedi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)|
## Required
- Neovim and neovim/python-client
- https://github.com/neovim/neovim
- https://github.com/neovim/python-client
- deoplete.nvim
- https://github.com/Shougo/deoplete.nvim
- jedi (the latest is recommended)
- https://github.com/davidhalter/jedi
## Install
```sh
pip3 install --user jedi --upgrade
```
And
```vim
NeoBundle 'deoplete-plugins/deoplete-jedi'
# or
Plug 'deoplete-plugins/deoplete-jedi'
```
**Note:** If you don't want to use a plugin manager, you will need to clone
this repo recursively:
```
git clone --recursive https://github.com/deoplete-plugins/deoplete-jedi
```
When updating the plugin, you will want to be sure that the Jedi submodule is
kept up to date with:
```
git submodule update --init
```
## Options
- `g:deoplete#sources#jedi#statement_length`: Sets the maximum length of
completion description text. If this is exceeded, a simple description is
used instead.
Default: `50`
- `g:deoplete#sources#jedi#enable_typeinfo`: Enables type information of
completions. If you disable it, you will get the faster results.
Default: `1`
- `g:deoplete#sources#jedi#enable_short_types`: Enables short completion types.
Default: `0`
- `g:deoplete#sources#jedi#short_types_map`: Short types mapping dictionary.
Default: `{
'import': 'imprt',
'function': 'def',
'globalstmt': 'var',
'instance': 'var',
'statement': 'var',
'keyword': 'keywd',
'module': 'mod',
'param': 'arg',
'property': 'prop',
'bytes': 'byte',
'complex': 'cmplx',
'object': 'obj',
'mappingproxy': 'dict',
'member_descriptor': 'cattr',
'getset_descriptor': 'cprop',
'method_descriptor': 'cdef',
}`
- `g:deoplete#sources#jedi#show_docstring`: Shows docstring in preview window.
Default: `0`
- `g:deoplete#sources#jedi#python_path`: Set the Python interpreter path to use
for the completion server. It defaults to "python", i.e. the first available
`python` in `$PATH`.
**Note**: This is different from Neovim's Python (`:python`) in general.
- `g:deoplete#sources#jedi#extra_path`: A list of extra paths to add to
`sys.path` when performing completions.
- `g:deoplete#sources#jedi#ignore_errors`: Ignore jedi errors for completions.
Default: `0`
- `g:deoplete#sources#jedi#ignore_private_members`: Ignore private members from
completions.
Default: `0`
## Virtual Environments
If you are using virtualenv, it is recommended that you create environments
specifically for Neovim. This way, you will not need to install the neovim
package in each virtualenv. Once you have created them, add the following to
your vimrc file:
```vim
let g:python_host_prog = '/full/path/to/neovim2/bin/python'
let g:python3_host_prog = '/full/path/to/neovim3/bin/python'
```
Deoplete only requires Python 3. See `:help provider-python` for more
information.

10
bundle/deoplete-jedi/mk/color.mk vendored Normal file
View File

@ -0,0 +1,10 @@
# Colorable output
CRESET := \x1b[0m
CBLACK := \x1b[30;01m
CRED := \x1b[31;01m
CGREEN := \x1b[32;01m
CYELLOW := \x1b[33;01m
CBLUE := \x1b[34;01m
CMAGENTA := \x1b[35;01m
CCYAN := \x1b[36;01m
CWHITE := \x1b[37;01m

13
bundle/deoplete-jedi/mk/debug_code.mk vendored Normal file
View File

@ -0,0 +1,13 @@
IMPORT_LOGGER := from logging import getLogger\nlogger = getLogger(__name__)
IMPORT_TIMEIT := from profiler import timeit
IMPORT_PYVMMONITOR := import sys\nsys.path.append("\/Applications\/PyVmMonitor.app\/Contents\/MacOS\/public_api")\nimport pyvmmonitor
SET_DEBUG_PREFIX := jedi_settings.cache_directory \= os.path.join\(cache_home, 'jedi'\)
SET_DEBUG := try:\n from helper import set_debug\n if self.vim.vars["deoplete\#enable_debug"]:\n log_file \= self.vim.vars["deoplete\#sources\#jedi\#debug\#log_file"]\n set_debug(logger, os.path.expanduser(log_file))\n except Exception:\n pass\n
TIMEIT_PREFIX := @timeit(logger,
TIMEIT_SUFFIX := )
TIMEIT_GET_COMPLETE_POSITION := ${TIMEIT_PREFIX}"simple", [0.00003000, 0.00015000]${TIMEIT_SUFFIX}
TIMEIT_GATHER_CANDIDATES := ${TIMEIT_PREFIX}"simple", [0.10000000, 0.20000000]${TIMEIT_SUFFIX}
PYVMMONITOR_DECORATOR := @pyvmmonitor.profile_method()

View File

@ -0,0 +1,338 @@
import copy
import logging
import os
import re
from importlib.util import find_spec
from deoplete.base.source import Base
from deoplete.util import bytepos2charpos, getlines, load_external_module
load_external_module(__file__, 'sources')
from deoplete_jedi import profiler # isort:skip # noqa: E402
# Type mapping. Empty values will use the key value instead.
# Keep them 5 characters max to minimize required space to display.
_types = {
'import': 'imprt',
'class': '',
'function': 'def',
'globalstmt': 'var',
'instance': 'var',
'statement': 'var',
'keyword': 'keywd',
'module': 'mod',
'param': 'arg',
'property': 'prop',
'bool': '',
'bytes': 'byte',
'complex': 'cmplx',
'dict': '',
'list': '',
'float': '',
'int': '',
'object': 'obj',
'set': '',
'slice': '',
'str': '',
'tuple': '',
'mappingproxy': 'dict', # cls.__dict__
'member_descriptor': 'cattr',
'getset_descriptor': 'cprop',
'method_descriptor': 'cdef',
}
def sort_key(item):
w = item.get('name')
z = len(w) - len(w.lstrip('_'))
return (('z' * z) + w.lower()[z:], len(w))
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'jedi'
self.mark = '[jedi]'
self.rank = 500
self.filetypes = ['python', 'cython', 'pyrex']
self.input_pattern = (r'[\w\)\]\}\'\"]+\.\w*$|'
r'^\s*@\w*$|'
r'^\s*from\s+[\w\.]*(?:\s+import\s+(?:\w*(?:,\s*)?)*)?|'
r'^\s*import\s+(?:[\w\.]*(?:,\s*)?)*')
self._async_keys = set()
self.workers_started = False
self._jedi = None
def on_init(self, context):
vars = context['vars']
self.statement_length = 50
if 'deoplete#sources#jedi#statement_length' in vars:
self.statement_length = vars[
'deoplete#sources#jedi#statement_length']
self.enable_typeinfo = True
if 'deoplete#sources#jedi#enable_typeinfo' in vars:
self.enable_typeinfo = vars[
'deoplete#sources#jedi#enable_typeinfo']
self.enable_short_types = False
if 'deoplete#sources#jedi#enable_short_types' in vars:
self.enable_short_types = vars[
'deoplete#sources#jedi#enable_short_types']
self.short_types_map = copy.copy(_types)
if 'deoplete#sources#jedi#short_types_map' in vars:
self.short_types_map.update(vars[
'deoplete#sources#jedi#short_types_map'])
self.show_docstring = False
if 'deoplete#sources#jedi#show_docstring' in vars:
self.show_docstring = vars[
'deoplete#sources#jedi#show_docstring']
self.ignore_errors = False
if 'deoplete#sources#jedi#ignore_errors' in vars:
self.ignore_errors = vars[
'deoplete#sources#jedi#ignore_errors']
self.ignore_private_members = False
if 'deoplete#sources#jedi#ignore_private_members' in vars:
self.ignore_private_members = vars[
'deoplete#sources#jedi#ignore_private_members']
# TODO(blueyed)
self.extra_path = ''
if 'deoplete#sources#jedi#extra_path' in vars:
self.extra_path = vars[
'deoplete#sources#jedi#extra_path']
if not self.is_debug_enabled:
root_log = logging.getLogger('deoplete')
child_log = root_log.getChild('jedi')
child_log.propagate = False
self._python_path = None
"""Current Python executable."""
self._env = None
"""Current Jedi Environment."""
self._envs = {}
"""Cache for Jedi Environments."""
if find_spec('jedi'):
import jedi # noqa: E402
self._jedi = jedi
else:
self.print_error(
'jedi module is not found. You need to install it.')
@profiler.profile
def set_env(self, python_path):
if not python_path:
import shutil
python_path = shutil.which('python')
self._python_path = python_path
try:
self._env = self._envs[python_path]
except KeyError:
self._env = self._jedi.api.environment.Environment(
python_path, env_vars={'PYTHONPATH': str(self.extra_path)})
self.debug('Using Jedi environment: %r', self._env)
@profiler.profile
def get_script(self, source, filename, environment):
return self._jedi.Script(code=source, path=filename, environment=self._env)
@profiler.profile
def get_completions(self, script, line, col):
return script.complete(line, col)
@profiler.profile
def finalize_completions(self, completions):
out = []
tmp_filecache = {}
for c in completions:
out.append(self.parse_completion(c, tmp_filecache))
if self.ignore_private_members:
out = [x for x in out if not x['name'].startswith('__')]
# partly from old finalized_cached
out = [self.finalize(x) for x in sorted(out, key=sort_key)]
return out
@profiler.profile
def gather_candidates(self, context):
if not self._jedi:
return []
python_path = None
if 'deoplete#sources#jedi#python_path' in context['vars']:
python_path = context['vars'][
'deoplete#sources#jedi#python_path']
if python_path != self._python_path or self.extra_path:
self.set_env(python_path)
line = context['position'][1]
col = bytepos2charpos(
context['encoding'], context['input'],
context['complete_position'])
buf = self.vim.current.buffer
filename = str(buf.name)
# Only use source if buffer is modified, to skip transferring, joining,
# and splitting the buffer lines unnecessarily.
modified = buf.options['modified']
if not modified and os.path.exists(filename):
source = None
else:
source = '\n'.join(getlines(self.vim))
if (line != self.vim.call('line', '.')
or context['complete_position'] >= self.vim.call('col', '$')):
return []
self.debug('Line: %r, Col: %r, Filename: %r, modified: %r',
line, col, filename, modified)
script = self.get_script(source, filename, environment=self._env)
try:
completions = self.get_completions(script, line, col)
except BaseException:
if not self.ignore_errors:
raise
return []
return self.finalize_completions(completions)
def get_complete_position(self, context):
if not self._jedi:
return -1
pattern = r'\w*$'
if context['input'].lstrip().startswith(('from ', 'import ')):
m = re.search(r'[,\s]$', context['input'])
if m:
return m.end()
m = re.search(pattern, context['input'])
return m.start() if m else -1
def mix_boilerplate(self, completions):
seen = set()
for item in self.boilerplate + completions:
if item['name'] in seen:
continue
seen.add(item['name'])
yield item
def finalize(self, item):
abbr = item['name']
desc = item['doc']
if item['params']:
sig = '{}({})'.format(item['name'], ', '.join(item['params']))
sig_len = len(sig)
desc = sig + '\n\n' + desc
if self.statement_length > 0 and sig_len > self.statement_length:
params = []
length = len(item['name']) + 2
for p in item['params']:
p = p.split('=', 1)[0]
length += len(p)
params.append(p)
length += 2 * (len(params) - 1)
# +5 for the ellipsis and separator
while length + 5 > self.statement_length and len(params):
length -= len(params[-1]) + 2
params = params[:-1]
if len(item['params']) > len(params):
params.append('...')
sig = '{}({})'.format(item['name'], ', '.join(params))
abbr = sig
if self.enable_short_types:
kind = item['short_type'] or item['type']
else:
kind = item['type']
return {
'word': item['name'],
'abbr': abbr,
'kind': kind,
'info': desc.strip(),
'dup': 1,
}
def completion_dict(self, name, type_, comp):
"""Final construction of the completion dict."""
doc = ''
if self.show_docstring:
try:
doc = comp.docstring()
except BaseException:
if not self.ignore_errors:
raise
i = doc.find('\n\n')
if i != -1:
doc = doc[i:]
params = None
try:
if type_ in ('function', 'class'):
params = []
for i, p in enumerate(comp.params):
desc = p.description.strip()
if i == 0 and desc == 'self':
continue
if '\\n' in desc:
desc = desc.replace('\\n', '\\x0A')
# Note: Hack for jedi param bugs
if desc.startswith('param ') or desc == 'param':
desc = desc[5:].strip()
if desc:
params.append(desc)
except Exception:
params = None
return {
'name': name,
'type': type_,
'short_type': self.short_types_map.get(type_),
'doc': doc.strip(),
'params': params,
}
def parse_completion(self, comp, cache):
"""Return a tuple describing the completion.
Returns (name, type, description, abbreviated)
"""
name = comp.name
if self.enable_typeinfo:
type_ = comp.type
else:
type_ = ''
if self.show_docstring:
desc = comp.description
else:
desc = ''
if type_ == 'instance' and desc.startswith(('builtins.', 'posix.')):
# Simple description
builtin_type = desc.rsplit('.', 1)[-1]
if builtin_type in _types:
return self.completion_dict(name, builtin_type, comp)
return self.completion_dict(name, type_, comp)

View File

@ -0,0 +1,9 @@
def set_debug(logger, path):
from logging import FileHandler, Formatter, DEBUG
hdlr = FileHandler(path)
logger.addHandler(hdlr)
datefmt = '%Y/%m/%d %H:%M:%S'
fmt = Formatter(
"%(levelname)s %(asctime)s %(message)s", datefmt=datefmt)
hdlr.setFormatter(fmt)
logger.setLevel(DEBUG)

View File

@ -0,0 +1,63 @@
import functools
import queue
try:
import statistics
stdev = statistics.stdev
mean = statistics.mean
except ImportError:
stdev = None
def mean(li):
return sum(li) / len(li)
try:
import time
clock = time.perf_counter
except Exception:
import timeit
clock = timeit.default_timer
class tfloat(float):
color = 39
def __str__(self):
n = self * 1000
return '\x1b[%dm%f\x1b[mms' % (self.color, n)
def profile(func):
name = func.__name__
samples = queue.deque(maxlen=5)
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_debug_enabled:
return func(self, *args, **kwargs)
start = clock()
ret = func(self, *args, **kwargs)
n = tfloat(clock() - start)
if len(samples) < 2:
m = 0
d = 0
n.color = 36
else:
m = mean(samples)
if stdev:
d = tfloat(stdev(samples))
else:
d = 0
if n <= m + d:
n.color = 32
elif n > m + d * 2:
n.color = 31
else:
n.color = 33
samples.append(n)
self.info('\x1b[34m%s\x1b[m t = %s, \u00b5 = %s, \u03c3 = %s)',
name, n, m, d)
return ret
return wrapper

View File

@ -0,0 +1,90 @@
import os
import re
import sys
def file_mtime(filename):
"""Get file modification time
Return 0 if the file does not exist
"""
if not os.path.exists(filename):
return 0
return int(os.path.getmtime(filename))
def module_file(dirname, suffix, base):
"""Find a script that matches the suffix path."""
search = os.path.abspath(os.path.join(dirname, suffix))
# dirname = os.path.dirname(dirname)
found = ''
while True:
p = os.path.join(search, '__init__.py')
if os.path.isfile(p):
found = p
break
p = search + '.py'
if os.path.isfile(p):
found = p
break
if os.path.basename(search) == base or search == dirname:
break
search = os.path.dirname(search)
return found
def module_search(module, paths):
"""Search paths for a file matching the module."""
if not module:
return ''
base = re.sub(r'\.+', '.', module).strip('.').split('.')[0]
module_path = os.path.normpath(re.sub(r'(\.+)', r'/\1/', module).strip('/'))
for p in paths:
found = module_file(p, module_path, base)
if found:
return found
return ''
def rplugin_runtime_paths(context):
"""Adds Neovim runtime paths.
Additional paths are added only if a `rplugin/python*` exists.
"""
paths = []
if context and 'cwd' in context:
cwd = context.get('cwd')
rplugins = ('rplugin/python{}'.format(sys.version_info[0]),
'rplugin/pythonx')
paths.extend(filter(os.path.exists,
(os.path.join(cwd, x)
for x in rplugins)))
if paths:
for rtp in context.get('runtimepath', '').split(','):
if not rtp:
continue
paths.extend(filter(os.path.exists,
(os.path.join(rtp, x)
for x in rplugins)))
return paths
def jedi_walk(completions, depth=0, max_depth=5):
"""Walk through Jedi objects
The purpose for this is to help find an object with a specific name. Once
found, the walking will stop.
"""
for c in completions:
yield c
if hasattr(c, 'description') and c.type == 'import':
d = c.description
if d.startswith('from ') and d.endswith('*') and depth < max_depth:
# Haven't determined the lowest Python 3 version required.
# If we determine 3.3, we can use `yield from`
for sub in jedi_walk(c.defined_names(), depth + 1, max_depth):
yield sub

14
bundle/deoplete-jedi/setup.cfg vendored Normal file
View File

@ -0,0 +1,14 @@
[flake8]
exclude = .svn,CVS,.bzr,.hg,.git,__pycache__,tests/*,rplugin/python3/deoplete/vendored
filename = *.py
ignore =
# W503 line break before binary operator
W503,
# H301: one import per line
H301,
# H304: No relative imports
H304,
# H306: imports not in alphabetical order - conflicts with isort ordering
H306
max-line-length = 99
max-complexity = 20

20
bundle/deoplete-jedi/tests/README.md vendored Normal file
View File

@ -0,0 +1,20 @@
# For deoplete-jedi test files
```bash
$ nvim -u ./tests/jedi-deoplete.vim tests/test-jedi.py
```
in nvim,
```vim
:UpdateRemotePlugins
:quit
```
again,
```bash
$ nvim -u ./tests/jedi-deoplete.vim tests/test-jedi.py
```
test it.

View File

@ -0,0 +1,31 @@
" Tiny init.vim for deoplete-jedi
" NeoBundle
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/deoplete-jedi
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/neco-syntax
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/neoinclude.vim
" vim-plug
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/deoplete-jedi
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/neco-syntax
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/neoinclude.vim
set completeopt+=noinsert,noselect
set completeopt-=preview
hi Pmenu gui=NONE guifg=#c5c8c6 guibg=#373b41
hi PmenuSel gui=reverse guifg=#c5c8c6 guibg=#373b41
let g:deoplete#enable_at_startup = 1
let g:deoplete#auto_completion_start_length = 1
" let g:deoplete#ignore_sources = {}
" let g:deoplete#ignore_sources.python = ['omni']
" let g:deoplete#ignore_sources.python += ['buffer']
" let g:deoplete#ignore_sources.python += ['tag']
" let g:deoplete#ignore_sources.python += ['ns']
" let g:deoplete#ignore_sources.python += ['member']
filetype plugin indent on

View File

@ -0,0 +1,21 @@
" Tiny init.vim for deoplete-jedi
" NeoBundle
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/deoplete-jedi
" vim-plug
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/deoplete-jedi
set completeopt+=noinsert,noselect
set completeopt-=preview
hi Pmenu gui=NONE guifg=#c5c8c6 guibg=#373b41
hi PmenuSel gui=reverse guifg=#c5c8c6 guibg=#373b41
let g:deoplete#enable_at_startup = 1
let g:deoplete#auto_completion_start_length = 1
" let g:deoplete#ignore_sources = {}
" let g:deoplete#ignore_sources.python = ['omni']
filetype plugin indent on

View File

@ -0,0 +1,29 @@
" Tiny init.vim for jedi-vim omnifunc
" NeoBundle
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/bundle/jedi-vim
" vim-plug
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/deoplete.nvim
set runtimepath+=$XDG_CONFIG_HOME/nvim/plugged/jedi-vim
set completeopt+=noinsert,noselect
set completeopt-=preview
hi Pmenu gui=NONE guifg=#c5c8c6 guibg=#373b41
hi PmenuSel gui=reverse guifg=#c5c8c6 guibg=#373b41
let g:deoplete#enable_at_startup = 1
let g:deoplete#auto_completion_start_length = 1
set omnifunc=jedi#completions
let g:jedi#auto_initialization = 1
let g:jedi#auto_vim_configuration = 0
let g:jedi#popup_select_first = 0
let g:jedi#completions_enabled = 0
let g:jedi#force_py_version = 3
let g:jedi#smart_auto_mappings = 0
let g:jedi#show_call_signatures = 0
let g:jedi#max_doc_height = 100
filetype plugin indent on

View File

@ -0,0 +1,3 @@
flake8>=2.5.4
flake8-import-order>=0.6.1
hacking>=0.10.2

View File

@ -0,0 +1,3 @@
import jedi
jedi

View File

@ -0,0 +1,10 @@
# Check http://editorconfig.org for more information
# This is the main config file for this project:
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
trim_trailing_whitespace = true

View File

@ -0,0 +1,35 @@
---
name: Bug
about: Create a report of something is not working
labels: 'bug'
---
# Bug report
<!--
Hi, thanks for submitting a bug. We appreciate that.
But, we will need some information about what's wrong to help you.
-->
## What's wrong
<!--
Describe what is not working.
Please, attach a traceback.
We would also appreciate a failing test case.
That is EXTREMELY helpful!
-->
## How is that should be
<!-- Describe how it should work. -->
## System information
- OS:
- `python` version:
- `django` version:
- `mypy` version:
- `django-stubs` version:

View File

@ -0,0 +1,29 @@
# I have made things!
<!--
Hi, thanks for submitting a Pull Request. We appreciate it.
Please, fill in all the required information
to make our review and merging processes easier.
Cheers!
-->
## Related issues
<!--
Mark what issues this Pull Request closes or references.
Format is:
- Closes #issue-number
- Refs #issue-number
Example. Refs #0
Documentation: https://blog.github.com/2013-05-14-closing-issues-via-pull-requests/
-->
<!--
If you have any feedback, just write it here.
It can be whatever you want!
-->

View File

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

View File

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

View File

@ -0,0 +1,111 @@
# How to contribute
## Tutorials
If you want to start working on this project,
you will need to get familiar with these projects:
- [Django docs](https://docs.djangoproject.com/en/dev/)
- [Typing in Python](https://inventwithpython.com/blog/2019/11/24/type-hints-for-busy-python-programmers/)
- [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
It is also recommended to take a look at these resources:
- [Awesome Python Typing](https://github.com/typeddjango/awesome-python-typing)
## Dev documentation
TODO
## Dependencies
We use `pip` to manage the dependencies.
To install them you would need to activate your `virtualenv` and run `install` command:
```bash
pip install -r ./dev-requirements.txt
```
## Tests and linters
We use `mypy`, `pytest`, `flake8`, and `black` for quality control.
Here's [how we run our CI](https://github.com/typeddjango/django-stubs/blob/master/.travis.yml).
### Typechecking
To run typechecking use:
```bash
mypy ./mypy_django_plugin
```
### Testing
There are unit tests and type-related tests.
To run unit tests:
```bash
pytest
```
Type-related tests ensure that different Django versions do work correctly.
To run type-related tests:
```bash
python ./scripts/typecheck_tests.py --django_version=2.2
python ./scripts/typecheck_tests.py --django_version=3.0
```
Currently we only support two Django versions.
### Linting
To run auto-formatting:
```bash
isort -rc .
black django-stubs/
```
To run linting:
```bash
flake8
flake8 --config flake8-pyi.ini
```
## Submitting your code
We use [trunk based](https://trunkbaseddevelopment.com/)
development (we also sometimes call it `wemake-git-flow`).
What the point of this method?
1. We use protected `master` branch,
so the only way to push your code is via pull request
2. We use issue branches: to implement a new feature or to fix a bug
create a new branch named `issue-$TASKNUMBER`
3. Then create a pull request to `master` branch
4. We use `git tag`s to make releases, so we can track what has changed
since the latest release
So, this way we achieve an easy and scalable development process
which frees us from merging hell and long-living branches.
In this method, the latest version of the app is always in the `master` branch.
## Other help
You can contribute by spreading a word about this library.
It would also be a huge contribution to write
a short article on how you are using this project.
You can also share your best practices with us.

View File

@ -0,0 +1,8 @@
Copyright (c) Maxim Kurnikov.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,120 @@
<img src="http://mypy-lang.org/static/mypy_light.svg" alt="mypy logo" width="300px"/>
# Typesafe Django Framework
[![Build Status](https://travis-ci.com/typeddjango/django-stubs.svg?branch=master)](https://travis-ci.com/typeddjango/django-stubs)
[![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](https://www.python.org/dev/peps/pep-0561/) and a custom mypy plugin to provide more precise static types and type inference for Django framework. Django uses some Python "magic" that makes having precise types for some code patterns problematic. This is why we need this project. The final goal is to be able to get precise types for most common patterns.
## Installation
```bash
pip install django-stubs
```
See [Configuration](#configuration) section to get started.
## Configuration
To make `mypy` happy, you will need to add:
```ini
[mypy]
plugins =
mypy_django_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = "myproject.settings"
```
in your `mypy.ini` or `setup.cfg` [file](https://mypy.readthedocs.io/en/latest/config_file.html).
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.5.0 | 0.780 | 2.2.x \|\| 3.x | ^3.6
| 1.4.0 | 0.770 | 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 indendepent 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 show your support by linking 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]` or `Manager[MyModel]`.
This happens because Django classes do not support [`__class_getitem__`](https://www.python.org/dev/peps/pep-0560/#class-getitem) magic method.
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.
Currently we [are working](https://github.com/django/django/pull/12405) on providing `__class_getitem__` to the classes where we need them.
### How can I use HttpRequest with custom user model?
You can subclass standard request like so:
```python
from django.http import HttpRequest
from my_user_app.models import MyUser
class MyRequest(HttpRequest):
user: MyUser
```
And then use `MyRequest` instead of standard `HttpRequest` inside your project.
## 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.
## 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.

View File

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

View File

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

View File

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

View File

@ -0,0 +1,23 @@
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
class AppConfig:
name: str = ...
module: Optional[Any] = ...
apps: Optional[Apps] = ...
label: str = ...
verbose_name: str = ...
path: str = ...
models_module: Optional[str] = ...
models: Dict[str, Type[Model]] = ...
def __init__(self, app_name: str, app_module: Optional[Any]) -> None: ...
@classmethod
def create(cls, entry: str) -> AppConfig: ...
def get_model(self, model_name: str, require_ready: bool = ...) -> Type[Model]: ...
def get_models(self, include_auto_created: bool = ..., include_swapped: bool = ...) -> Iterator[Type[Model]]: ...
def import_models(self) -> None: ...
def ready(self) -> None: ...

View File

@ -0,0 +1,40 @@
import threading
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from django.db.models.base import Model
from .config import AppConfig
class Apps:
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: Dict[Tuple[str, str], List]
models_ready: bool = ...
ready: bool = ...
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]: ...
def get_app_config(self, app_label: str) -> AppConfig: ...
# it's not possible to support it in plugin properly now
def get_models(self, include_auto_created: bool = ..., include_swapped: bool = ...) -> List[Type[Model]]: ...
def get_model(self, app_label: str, model_name: Optional[str] = ..., require_ready: bool = ...) -> Type[Any]: ...
def register_model(self, app_label: str, model: Type[Model]) -> None: ...
def is_installed(self, app_name: str) -> bool: ...
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: Iterable[str]) -> None: ...
def unset_available_apps(self) -> 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: ...
def do_pending_operations(self, model: Type[Model]) -> None: ...
apps: Apps

View File

@ -0,0 +1,29 @@
from typing import Any
from django.utils.functional import LazyObject
# explicit dependency on standard settings to make it loaded
from . import global_settings
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
class _DjangoConfLazyObject(LazyObject):
def __getattr__(self, item: Any) -> Any: ...
class LazySettings(_DjangoConfLazyObject):
configured: bool
def configure(self, default_settings: Any = ..., **options: Any) -> Any: ...
settings: LazySettings = ...
class Settings:
def __init__(self, settings_module: str): ...
def is_overridden(self, setting: str) -> bool: ...
class UserSettingsHolder: ...
class SettingsReference(str):
def __init__(self, value: str, setting_name: str) -> None: ...

View File

@ -0,0 +1,504 @@
"""
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
"""
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
from typing import Any, Dict, List, Optional, Pattern, Protocol, Sequence, Tuple, Union
####################
# CORE #
####################
DEBUG: bool = ...
# Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing situations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS: bool = ...
# People who get code error notifications.
# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS: List[Tuple[str, str]] = ...
# List of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS: List[str] = ...
# Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS: List[str] = ...
# Local time zone for this installation. All choices can be found here:
# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE: str = ...
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ: bool = ...
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE: str = ...
# Languages we provide translations for, out of the box.
LANGUAGES: List[Tuple[str, str]] = ...
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI: List[str] = ...
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N: bool = ...
LOCALE_PATHS: List[str] = ...
# Settings for language cookie
LANGUAGE_COOKIE_NAME: str = ...
LANGUAGE_COOKIE_AGE: Optional[int] = ...
LANGUAGE_COOKIE_DOMAIN: Optional[str] = ...
LANGUAGE_COOKIE_PATH: str = ...
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N: bool = ...
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE: str = ...
DEFAULT_CHARSET: str = ...
# Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET: str = ...
# Email address that error messages come from.
SERVER_EMAIL: str = ...
# Database connection info. If left empty, will default to the dummy backend.
DATABASES: Dict[str, Dict[str, Any]] = ...
# Classes used to implement DB routing behavior.
class Router(Protocol):
def allow_migrate(self, db, app_label, **hints): ...
DATABASE_ROUTERS: List[Union[str, Router]] = ...
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND: str = ...
# Host for sending email.
EMAIL_HOST: str = ...
# Port for sending email.
EMAIL_PORT: int = ...
# Whether to send SMTP 'Date' header in the local time zone or in UTC.
EMAIL_USE_LOCALTIME: bool = ...
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER: str = ...
EMAIL_HOST_PASSWORD: str = ...
EMAIL_USE_TLS: bool = ...
EMAIL_USE_SSL: bool = ...
EMAIL_SSL_CERTFILE: Optional[str] = ...
EMAIL_SSL_KEYFILE: Optional[str] = ...
EMAIL_TIMEOUT: Optional[int] = ...
# List of strings representing installed apps.
INSTALLED_APPS: List[str] = ...
TEMPLATES: List[Dict[str, Any]] = ...
# Default form rendering class.
FORM_RENDERER: str = ...
# Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL: str = ...
# Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers. Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX: str = ...
# Whether to append trailing slashes to URLs.
APPEND_SLASH: bool = ...
# Whether to prepend the "www." subdomain to URLs that don't have it.
PREPEND_WWW: bool = ...
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = [
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search'),
# ]
DISALLOWED_USER_AGENTS: List[Pattern] = ...
ABSOLUTE_URL_OVERRIDES: Dict[str, Any] = ...
# List of compiled regular expression objects representing URLs that need not
# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:
# import re
# IGNORABLE_404_URLS = [
# re.compile(r'^/apple-touch-icon.*\.png$'),
# re.compile(r'^/favicon.ico$'),
# re.compile(r'^/robots.txt$'),
# re.compile(r'^/phpmyadmin/'),
# re.compile(r'\.(cgi|php|pl)$'),
# ]
IGNORABLE_404_URLS: List[Pattern] = ...
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY: str = ...
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE: str = ...
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT: str = ...
# URL that handles the media served from MEDIA_ROOT.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL: str = ...
# Absolute path to the directory static files should be collected to.
# Example: "/var/www/example.com/static/"
STATIC_ROOT: Optional[str] = ...
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL: Optional[str] = ...
# List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS: List[str] = ...
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE: int = ... # i.e. 2.5 MB
# Maximum size in bytes of request data (excluding file uploads) that will be
# read before a SuspiciousOperation (RequestDataTooBig) is raised.
DATA_UPLOAD_MAX_MEMORY_SIZE: int = ... # i.e. 2.5 MB
# Maximum number of GET/POST parameters that will be read before a
# SuspiciousOperation (TooManyFieldsSent) is raised.
DATA_UPLOAD_MAX_NUMBER_FIELDS: int = ...
# Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
# (i.e. "/tmp" on *nix systems).
FILE_UPLOAD_TEMP_DIR: Optional[str] = ...
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_PERMISSIONS = None
# The numeric mode to assign to newly-created directories, when uploading files.
# The value should be a mode as you'd pass to os.chmod;
# see https://docs.python.org/library/os.html#files-and-directories.
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
# Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
# named as the locales, containing a formats.py file
# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
FORMAT_MODULE_PATH: Optional[str] = ...
# Default formatting for date objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT: str = ...
# Default formatting for datetime objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATETIME_FORMAT: str = ...
# Default formatting for time objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
TIME_FORMAT: str = ...
# Default formatting for date objects when only the year and month are relevant.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
YEAR_MONTH_FORMAT: str = ...
# Default formatting for date objects when only the month and day are relevant.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MONTH_DAY_FORMAT: str = ...
# Default short formatting for date objects. See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATE_FORMAT: str = ...
# Default short formatting for datetime objects.
# See all available format strings here:
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATETIME_FORMAT: str = ...
# Default formats to be used when parsing dates from input boxes, in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATE_INPUT_FORMATS: List[str] = ...
# Default formats to be used when parsing times from input boxes, in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
TIME_INPUT_FORMATS: List[str] = ... # '14:30:59' # '14:30:59.000200' # '14:30'
# Default formats to be used when parsing dates and times from input boxes,
# in order
# See all available format string here:
# https://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATETIME_INPUT_FORMATS: List[str] = ...
# First day of week, to be used on calendars
# 0 means Sunday, 1 means Monday...
FIRST_DAY_OF_WEEK: int = ...
# Decimal separator symbol
DECIMAL_SEPARATOR: str = ...
# Boolean that sets whether to add thousand separator when formatting numbers
USE_THOUSAND_SEPARATOR: bool = ...
# Number of digits that will be together, when splitting them by
# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...
NUMBER_GROUPING: int = ...
# Thousand separator symbol
THOUSAND_SEPARATOR: str = ...
# The tablespaces to use for each model when not specified otherwise.
DEFAULT_TABLESPACE: str = ...
DEFAULT_INDEX_TABLESPACE: str = ...
# Default X-Frame-Options header value
X_FRAME_OPTIONS: str = ...
USE_X_FORWARDED_HOST: bool = ...
USE_X_FORWARDED_PORT: bool = ...
# The Python dotted path to the WSGI application that Django's internal server
# (runserver) will use. If `None`, the return value of
# 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same
# behavior as previous versions of Django. Otherwise this should point to an
# actual WSGI application object.
WSGI_APPLICATION: Optional[str] = ...
# If your Django app is behind a proxy that sets a header to specify secure
# connections, AND that proxy ensures that user-submitted headers with the
# same name are ignored (so that people can't spoof it), set this value to
# a tuple of (header_name, header_value). For any requests that come in with
# that header/value, request.is_secure() will return True.
# WARNING! Only set this if you fully understand what you're doing. Otherwise,
# you may be opening yourself up to a security risk.
SECURE_PROXY_SSL_HEADER: Optional[Tuple[str, str]] = ...
##############
# MIDDLEWARE #
##############
# List of middleware to use. Order is important; in the request phase, these
# middleware will be applied in the order given, and in the response
# phase the middleware will be applied in reverse order.
MIDDLEWARE: List[str] = ...
############
# SESSIONS #
############
# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = "default"
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = "sessionid"
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN: Optional[str] = ...
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = "/"
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
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: 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.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# The module to store session data
SESSION_ENGINE = "django.contrib.sessions.backends.db"
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH: Optional[str] = ...
# class to serialize session data
SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
#########
# CACHE #
#########
# The cache backends to use.
CACHES: Dict[str, Dict[str, Any]] = ...
CACHE_MIDDLEWARE_KEY_PREFIX = ""
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = "default"
##################
# AUTHENTICATION #
##################
AUTH_USER_MODEL: str = ...
AUTHENTICATION_BACKENDS: Sequence[str] = ...
LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL: str = ...
LOGOUT_REDIRECT_URL: Optional[str] = ...
# The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3
# the first hasher in this list is the preferred algorithm. any
# password using different algorithms will be converted automatically
# upon login
PASSWORD_HASHERS: List[str] = ...
AUTH_PASSWORD_VALIDATORS: List[Dict[str, str]] = ...
###########
# SIGNING #
###########
SIGNING_BACKEND = "django.core.signing.TimestampSigner"
########
# CSRF #
########
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure"
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = "csrftoken"
CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = "/"
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE: Optional[str] = ...
CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN"
CSRF_TRUSTED_ORIGINS: List[str] = ...
CSRF_USE_SESSIONS = False
############
# MESSAGES #
############
# Class to use as messages backend
MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage"
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
###########
# LOGGING #
###########
# The callable to use to configure logging
LOGGING_CONFIG = "logging.config.dictConfig"
# Custom logging configuration.
LOGGING: Dict[str, Any] = ...
# Default exception reporter filter class used in case none has been
# specifically assigned to the HttpRequest instance.
DEFAULT_EXCEPTION_REPORTER_FILTER = "django.views.debug.SafeExceptionReporterFilter"
###########
# TESTING #
###########
# The name of the class to use to run the test suite
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# Apps that don't need to be serialized at test database creation time
# (only apps with migrations are to start with)
TEST_NON_SERIALIZED_APPS: List[str] = ...
############
# FIXTURES #
############
# The list of directories to search for fixtures
FIXTURE_DIRS: List[str] = ...
###############
# STATICFILES #
###############
# A list of locations of additional static files
STATICFILES_DIRS: List[str] = ...
# The default file storage backend used during the build process
STATICFILES_STORAGE: str = ...
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS: List[str] = ...
##############
# MIGRATIONS #
##############
# Migration module overrides for apps, by app label.
MIGRATION_MODULES: Dict[str, str] = ...
#################
# SYSTEM CHECKS #
#################
# List of all issues generated by system checks that should be silenced. Light
# issues like warnings, infos or debugs will not generate a message. Silencing
# serious issues like errors and criticals does not result in hiding the
# message, but Django will not stop you from e.g. running server.
SILENCED_SYSTEM_CHECKS: List[str] = ...
#######################
# SECURITY MIDDLEWARE #
#######################
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT: List[str] = ...
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False

View File

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

View File

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

View File

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

View File

@ -0,0 +1,5 @@
from typing import Any, Callable, List
from django.urls.resolvers import URLPattern
def static(prefix: str, view: Callable = ..., **kwargs: Any) -> List[URLPattern]: ...

View File

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

View File

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

View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class SimpleAdminConfig(AppConfig):
default_site: str = ...
class AdminConfig(SimpleAdminConfig): ...

View File

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

View File

@ -0,0 +1,5 @@
from typing import Any, Callable, Optional, Type
from django.db.models.base import Model
def register(*models: Type[Model], site: Optional[Any] = ...) -> Callable: ...

View File

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

View File

@ -0,0 +1,7 @@
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
class AdminAuthenticationForm(AuthenticationForm):
required_css_class: str = ...
class AdminPasswordChangeForm(PasswordChangeForm):
required_css_class: str = ...

View File

@ -0,0 +1,155 @@
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union, Iterable
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
from django import forms
from django.db.models.fields import AutoField
ACTION_CHECKBOX_NAME: str
class ActionForm(forms.Form):
action: Any = ...
select_across: Any = ...
checkbox: Any
class AdminForm:
prepopulated_fields: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
def __init__(
self,
form: BaseForm,
fieldsets: List[Tuple[None, Dict[str, List[str]]]],
prepopulated_fields: Dict[Any, Any],
readonly_fields: Optional[Iterable[Any]] = ...,
model_admin: Any = ...,
) -> None: ...
def __iter__(self) -> Iterator[Fieldset]: ...
@property
def errors(self) -> ErrorDict: ...
@property
def non_field_errors(self) -> Callable: ...
@property
def media(self) -> Media: ...
class Fieldset:
form: Any = ...
classes: Any = ...
description: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
def __init__(
self,
form: Any,
name: Optional[Any] = ...,
readonly_fields: Optional[Iterable[Any]] = ...,
fields: Any = ...,
classes: Any = ...,
description: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
) -> None: ...
@property
def media(self) -> Media: ...
def __iter__(self) -> Iterator[Fieldline]: ...
class Fieldline:
form: Any = ...
fields: Any = ...
has_visible_field: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
def __init__(
self, form: Any, field: Any, readonly_fields: Optional[Iterable[Any]] = ..., model_admin: Optional[Any] = ...
) -> None: ...
def __iter__(self) -> Iterator[Union[AdminField, AdminReadonlyField]]: ...
def errors(self) -> SafeText: ...
class AdminField:
field: BoundField = ...
is_first: bool = ...
is_checkbox: bool = ...
is_readonly: bool = ...
def __init__(self, form: Any, field: Any, is_first: Any) -> None: ...
def label_tag(self) -> SafeText: ...
def errors(self) -> SafeText: ...
class AdminReadonlyField:
field: Any = ...
form: Any = ...
model_admin: Any = ...
is_first: Any = ...
is_checkbox: bool = ...
is_readonly: bool = ...
empty_value_display: Any = ...
def __init__(self, form: Any, field: Any, is_first: Any, model_admin: Optional[Any] = ...) -> None: ...
def label_tag(self) -> SafeText: ...
def contents(self) -> SafeText: ...
class InlineAdminFormSet:
opts: Any = ...
formset: Any = ...
fieldsets: Any = ...
model_admin: Any = ...
readonly_fields: Any = ...
prepopulated_fields: Any = ...
classes: Any = ...
has_add_permission: Any = ...
has_change_permission: Any = ...
has_delete_permission: Any = ...
has_view_permission: Any = ...
def __init__(
self,
inline: Any,
formset: Any,
fieldsets: Any,
prepopulated_fields: Optional[Any] = ...,
readonly_fields: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
has_add_permission: bool = ...,
has_change_permission: bool = ...,
has_delete_permission: bool = ...,
has_view_permission: bool = ...,
) -> None: ...
def __iter__(self) -> Iterator[InlineAdminForm]: ...
def fields(self) -> Iterator[Dict[str, Union[Dict[str, bool], bool, Widget, str]]]: ...
def inline_formset_data(self) -> str: ...
@property
def forms(self): ...
@property
def non_form_errors(self) -> Callable: ...
@property
def media(self) -> Media: ...
class InlineAdminForm(AdminForm):
formset: Any = ...
original: Any = ...
show_url: Any = ...
absolute_url: Any = ...
def __init__(
self,
formset: Any,
form: Any,
fieldsets: Any,
prepopulated_fields: Any,
original: Any,
readonly_fields: Optional[Any] = ...,
model_admin: Optional[Any] = ...,
view_on_site_url: Optional[Any] = ...,
) -> None: ...
def needs_explicit_pk_field(self) -> Union[bool, AutoField]: ...
def pk_field(self) -> AdminField: ...
def fk_field(self) -> AdminField: ...
def deletion_field(self) -> AdminField: ...
def ordering_field(self): ...
class InlineFieldset(Fieldset):
formset: Any = ...
def __init__(self, formset: Any, *args: Any, **kwargs: Any) -> None: ...
class AdminErrorList(forms.utils.ErrorList):
def __init__(self, form: Any, inline_formsets: Any) -> None: ...

View File

@ -0,0 +1,39 @@
from typing import Any, Optional, Union
from uuid import UUID
from django.contrib.contenttypes.models import ContentType
from django.db.models.base import Model
from django.db import models
ADDITION: int
CHANGE: int
DELETION: int
ACTION_FLAG_CHOICES: Any
class LogEntryManager(models.Manager["LogEntry"]):
def log_action(
self,
user_id: int,
content_type_id: int,
object_id: Union[int, str, UUID],
object_repr: str,
action_flag: int,
change_message: Any = ...,
) -> LogEntry: ...
class LogEntry(models.Model):
action_time: models.DateTimeField = ...
user: models.ForeignKey = ...
content_type: models.ForeignKey = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id: models.TextField = ...
object_repr: models.CharField = ...
action_flag: models.PositiveSmallIntegerField = ...
change_message: models.TextField = ...
objects: LogEntryManager = ...
def is_addition(self) -> bool: ...
def is_change(self) -> bool: ...
def is_deletion(self) -> bool: ...
def get_change_message(self) -> str: ...
def get_edited_object(self) -> Model: ...
def get_admin_url(self) -> Optional[str]: ...

View File

@ -0,0 +1,275 @@
from collections import OrderedDict
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, Union, Mapping, TypeVar
from django.forms.forms import BaseForm
from django.forms.formsets import BaseFormSet
from typing_extensions import Literal, TypedDict
from django.contrib.admin.filters import ListFilter
from django.contrib.admin.models import LogEntry
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.contrib.contenttypes.models import ContentType
from django.core.checks.messages import Error
from django.core.paginator import Paginator
from django.db.models.base import Model
from django.db.models.fields.related import ForeignKey, ManyToManyField, RelatedField
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.fields import TypedChoiceField
from django.forms.models import ModelChoiceField, ModelMultipleChoiceField
from django.forms.widgets import Media
from django.http.request import HttpRequest
from django.http.response import HttpResponse, HttpResponseBase, HttpResponseRedirect, JsonResponse
from django.template.response import TemplateResponse
from django.urls.resolvers import URLPattern
from django.utils.safestring import SafeText
from django.db.models.fields import Field
IS_POPUP_VAR: str
TO_FIELD_VAR: str
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: ...
class IncorrectLookupParameters(Exception): ...
FORMFIELD_FOR_DBFIELD_DEFAULTS: Any
csrf_protect_m: 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]]
class BaseModelAdmin:
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[[Model], 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 formfield_for_dbfield(
self, db_field: Field, request: Optional[HttpRequest], **kwargs: Any
) -> Optional[Field]: ...
def formfield_for_choice_field(
self, db_field: Field, request: Optional[HttpRequest], **kwargs: Any
) -> TypedChoiceField: ...
def get_field_queryset(
self, db: None, db_field: RelatedField, request: Optional[HttpRequest]
) -> Optional[QuerySet]: ...
def formfield_for_foreignkey(
self, db_field: ForeignKey, request: Optional[HttpRequest], **kwargs: Any
) -> Optional[ModelChoiceField]: ...
def formfield_for_manytomany(
self, db_field: ManyToManyField, request: Optional[HttpRequest], **kwargs: Any
) -> ModelMultipleChoiceField: ...
def get_autocomplete_fields(self, request: HttpRequest) -> Tuple: ...
def get_view_on_site_url(self, obj: Optional[Model] = ...) -> Optional[str]: ...
def get_empty_value_display(self) -> SafeText: ...
def get_exclude(self, request: HttpRequest, obj: Optional[Model] = ...) -> Any: ...
def get_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Sequence[Union[Callable, str]]: ...
def get_fieldsets(
self, request: HttpRequest, obj: Optional[Model] = ...
) -> List[Tuple[Optional[str], Dict[str, Any]]]: ...
def get_ordering(self, request: HttpRequest) -> Union[List[str], Tuple]: ...
def get_readonly_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Union[List[str], Tuple]: ...
def get_prepopulated_fields(self, request: HttpRequest, obj: Optional[Model] = ...) -> Dict[str, Tuple[str]]: ...
def get_queryset(self, request: HttpRequest) -> QuerySet: ...
def get_sortable_by(self, request: HttpRequest) -> Union[List[Callable], List[str], Tuple]: ...
def lookup_allowed(self, lookup: str, value: str) -> bool: ...
def to_field_allowed(self, request: HttpRequest, to_field: str) -> bool: ...
def has_add_permission(self, request: HttpRequest) -> bool: ...
def has_change_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_delete_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_view_permission(self, request: HttpRequest, obj: Optional[Model] = ...) -> bool: ...
def has_module_permission(self, request: HttpRequest) -> bool: ...
class ModelAdmin(BaseModelAdmin):
list_display: Sequence[Union[str, Callable[[Model], 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]] = ...
list_per_page: int = ...
list_max_show_all: int = ...
list_editable: Sequence[str] = ...
search_fields: Sequence[str] = ...
date_hierarchy: Optional[str] = ...
save_as: bool = ...
save_as_continue: bool = ...
save_on_top: bool = ...
paginator: Type = ...
preserve_filters: bool = ...
inlines: Sequence[Type[InlineModelAdmin]] = ...
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: Sequence[Callable[[ModelAdmin, HttpRequest, QuerySet], None]] = ...
action_form: Any = ...
actions_on_top: bool = ...
actions_on_bottom: bool = ...
actions_selection_counter: bool = ...
model: Type[Model] = ...
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 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_changelist(self, request: HttpRequest, **kwargs: Any) -> Type[ChangeList]: ...
def get_changelist_instance(self, request: HttpRequest) -> ChangeList: ...
def get_object(self, request: HttpRequest, object_id: str, from_field: None = ...) -> Optional[Model]: ...
def get_changelist_form(self, request: Any, **kwargs: Any): ...
def get_changelist_formset(self, request: Any, **kwargs: Any): ...
def get_formsets_with_inlines(self, request: HttpRequest, obj: Optional[Model] = ...) -> Iterator[Any]: ...
def get_paginator(
self,
request: HttpRequest,
queryset: QuerySet,
per_page: int,
orphans: int = ...,
allow_empty_first_page: bool = ...,
) -> Paginator: ...
def log_addition(self, request: HttpRequest, object: Model, message: Any) -> LogEntry: ...
def log_change(self, request: HttpRequest, object: Model, message: Any) -> LogEntry: ...
def log_deletion(self, request: HttpRequest, object: Model, object_repr: str) -> LogEntry: ...
def action_checkbox(self, obj: Model) -> SafeText: ...
def get_actions(self, request: HttpRequest) -> OrderedDict: ...
def get_action_choices(
self, request: HttpRequest, default_choices: List[Tuple[str, str]] = ...
) -> List[Tuple[str, str]]: ...
def get_action(self, action: Union[Callable, str]) -> Tuple[Callable, str, str]: ...
def get_list_display(self, request: HttpRequest) -> Sequence[str]: ...
def get_list_display_links(self, request: HttpRequest, list_display: Sequence[str]) -> Optional[Sequence[str]]: ...
def get_list_filter(self, request: HttpRequest) -> Sequence[str]: ...
def get_list_select_related(self, request: HttpRequest) -> Sequence[str]: ...
def get_search_fields(self, request: HttpRequest) -> List[str]: ...
def get_search_results(
self, request: HttpRequest, queryset: QuerySet, search_term: str
) -> Tuple[QuerySet, bool]: ...
def get_preserved_filters(self, request: HttpRequest) -> str: ...
def _get_edited_object_pks(self, request: HttpRequest, prefix: str) -> List[str]: ...
def _get_list_editable_queryset(self, request: HttpRequest, prefix: str) -> QuerySet: ...
def construct_change_message(
self, request: HttpRequest, form: AdminPasswordChangeForm, formsets: None, add: bool = ...
) -> List[Dict[str, Dict[str, List[str]]]]: ...
def message_user(
self,
request: HttpRequest,
message: str,
level: Union[int, str] = ...,
extra_tags: str = ...,
fail_silently: bool = ...,
) -> None: ...
def save_form(self, request: Any, form: Any, change: Any): ...
def save_model(self, request: Any, obj: Any, form: Any, change: Any) -> None: ...
def delete_model(self, request: HttpRequest, obj: Model) -> None: ...
def delete_queryset(self, request: HttpRequest, queryset: QuerySet) -> None: ...
def save_formset(self, request: Any, form: Any, formset: Any, change: Any) -> None: ...
def save_related(self, request: Any, form: Any, formsets: Any, change: Any) -> None: ...
def render_change_form(
self,
request: Any,
context: Any,
add: bool = ...,
change: bool = ...,
form_url: str = ...,
obj: Optional[Any] = ...,
): ...
def response_add(
self, request: HttpRequest, obj: Model, 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_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] = ...
) -> List[Any]: ...
def get_changeform_initial_data(self, request: HttpRequest) -> Dict[str, str]: ...
def changeform_view(
self,
request: HttpRequest,
object_id: Optional[str] = ...,
form_url: str = ...,
extra_context: Optional[Dict[str, bool]] = ...,
) -> Any: ...
def autocomplete_view(self, request: HttpRequest) -> JsonResponse: ...
def add_view(self, request: HttpRequest, form_url: str = ..., extra_context: None = ...) -> HttpResponse: ...
def change_view(
self, request: HttpRequest, object_id: str, form_url: str = ..., extra_context: Optional[Dict[str, bool]] = ...
) -> HttpResponse: ...
def changelist_view(
self, request: HttpRequest, extra_context: Optional[Dict[str, str]] = ...
) -> TemplateResponse: ...
def get_deleted_objects(
self, objs: QuerySet, request: HttpRequest
) -> Tuple[List[Any], Dict[Any, Any], Set[Any], List[Any]]: ...
def delete_view(self, request: HttpRequest, object_id: str, extra_context: None = ...) -> Any: ...
def history_view(self, request: HttpRequest, object_id: str, extra_context: None = ...) -> HttpResponse: ...
class InlineModelAdmin(BaseModelAdmin):
model: Type[Model] = ...
fk_name: str = ...
formset: BaseFormSet = ...
extra: int = ...
min_num: Optional[int] = ...
max_num: Optional[int] = ...
template: str = ...
verbose_name: Optional[str] = ...
verbose_name_plural: Optional[str] = ...
can_delete: bool = ...
show_change_link: bool = ...
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: ...
@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): ...
class StackedInline(InlineModelAdmin): ...
class TabularInline(InlineModelAdmin): ...

View File

@ -0,0 +1,75 @@
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from django.contrib.admin.options import ModelAdmin
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
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.apps.config import AppConfig
all_sites: Any
class AlreadyRegistered(Exception): ...
class NotRegistered(Exception): ...
class AdminSite:
site_title: Any = ...
site_header: Any = ...
index_title: Any = ...
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 = ...
name: str = ...
_registry: Dict[Type[Model], ModelAdmin]
def __init__(self, name: str = ...) -> None: ...
def check(self, app_configs: Optional[Iterable[AppConfig]]) -> List[Any]: ...
def register(
self,
model_or_iterable: Union[Type[Model], Iterable[Type[Model]]],
admin_class: Optional[Type[ModelAdmin]] = ...,
**options: Any
) -> None: ...
def unregister(self, model_or_iterable: Union[Type[Model], Iterable[Type[Model]]]) -> None: ...
def is_registered(self, model: Type[Model]) -> bool: ...
def add_action(self, action: Callable, name: Optional[str] = ...) -> None: ...
def disable_action(self, name: str) -> None: ...
def get_action(self, name: str) -> Callable: ...
@property
def actions(self): ...
@property
def empty_value_display(self): ...
@empty_value_display.setter
def empty_value_display(self, empty_value_display: Any) -> None: ...
def has_permission(self, request: WSGIRequest) -> bool: ...
def 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: 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[Any, Any]] = ...) -> HttpResponse: ...
def logout(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> TemplateResponse: ...
def login(self, request: WSGIRequest, extra_context: Optional[Dict[str, Any]] = ...) -> HttpResponse: ...
def _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, Any]] = ...) -> TemplateResponse: ...
def app_index(
self, request: WSGIRequest, app_label: str, extra_context: Optional[Dict[str, Any]] = ...
) -> TemplateResponse: ...
class DefaultAdminSite(LazyObject): ...
site: Any

View File

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

View File

@ -0,0 +1,16 @@
from typing import Any
from django.contrib.admin.helpers import InlineAdminForm
from django.template.base import Parser, Token
from django.template.context import Context, RequestContext
from .base import InclusionAdminNode
register: Any
def prepopulated_fields_js(context: RequestContext) -> RequestContext: ...
def prepopulated_fields_js_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def submit_row(context: RequestContext) -> Context: ...
def submit_row_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def change_form_object_tools_tag(parser: Parser, token: Token) -> InclusionAdminNode: ...
def cell_count(inline_admin_form: InlineAdminForm) -> int: ...

View File

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

View File

@ -0,0 +1,17 @@
from typing import Any, Dict, Optional, Union
from uuid import UUID
from django.db.models.options import Options
from django.template.context import RequestContext
from django.utils.safestring import SafeText
register: Any
def admin_urlname(value: Options, arg: SafeText) -> str: ...
def admin_urlquote(value: Union[int, str, UUID]) -> Union[int, str, UUID]: ...
def add_preserved_filters(
context: Union[Dict[str, Union[Options, str]], RequestContext],
url: str,
popup: bool = ...,
to_field: Optional[str] = ...,
) -> str: ...

View File

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

View File

@ -0,0 +1,16 @@
from typing import Any, Optional
from django import template
from django.template.base import Parser, Token
from django.template.context import Context
register: Any
class AdminLogNode(template.Node):
limit: str
user: str
varname: str
def __init__(self, limit: str, varname: str, user: Optional[str]) -> None: ...
def render(self, context: Context) -> str: ...
def get_admin_log(parser: Parser, token: Token) -> AdminLogNode: ...

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

@ -0,0 +1,68 @@
import collections
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, Union
from uuid import UUID
from django.contrib.admin.options import BaseModelAdmin
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.db.models.deletion import Collector
from django.db.models.fields.reverse_related import ManyToOneRel
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.forms import BaseForm
from django.db.models.fields import Field, reverse_related
class FieldIsAForeignKeyColumnName(Exception): ...
def lookup_needs_distinct(opts: Options, lookup_path: str) -> bool: ...
def prepare_lookup_value(key: str, value: Union[datetime, str]) -> Union[bool, datetime, str]: ...
def quote(s: Union[int, str, UUID]) -> str: ...
def unquote(s: str) -> str: ...
def flatten(fields: Any) -> List[Union[Callable, str]]: ...
def flatten_fieldsets(fieldsets: Any) -> List[Union[Callable, str]]: ...
def get_deleted_objects(
objs: Sequence[Optional[Model]], request: WSGIRequest, admin_site: AdminSite
) -> Tuple[List[Any], Dict[Any, Any], Set[Any], List[Any]]: ...
class NestedObjects(Collector):
data: collections.OrderedDict
dependencies: Dict[Any, Any]
fast_deletes: List[Any]
field_updates: Dict[Any, Any]
using: str
edges: Any = ...
protected: Any = ...
model_objs: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def add_edge(self, source: Optional[Model], target: Model) -> None: ...
def related_objects(self, related: ManyToOneRel, objs: Sequence[Optional[Model]]) -> QuerySet: ...
def 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], Any, Any]: ...
def label_for_field(
name: Union[Callable, str],
model: Type[Model],
model_admin: Optional[BaseModelAdmin] = ...,
return_attr: bool = ...,
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: 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[Field]: ...
def construct_change_message(
form: AdminPasswordChangeForm, formsets: None, add: bool
) -> List[Dict[str, Dict[str, List[str]]]]: ...

View File

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

View File

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

View File

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

View File

@ -0,0 +1,102 @@
from typing import Any, Dict, Optional, Tuple, Union
from uuid import UUID
from django.contrib.admin.sites import AdminSite
from django.db.models.fields.reverse_related import ForeignObjectRel, ManyToOneRel
from django.forms.models import ModelChoiceIterator
from django.forms.widgets import Media
from django import forms
class FilteredSelectMultiple(forms.SelectMultiple):
@property
def media(self) -> Media: ...
verbose_name: Any = ...
is_stacked: Any = ...
def __init__(self, verbose_name: str, is_stacked: bool, attrs: None = ..., choices: Tuple = ...) -> None: ...
class AdminDateWidget(forms.DateInput):
@property
def media(self) -> Media: ...
class AdminTimeWidget(forms.TimeInput):
@property
def media(self) -> Media: ...
class AdminSplitDateTime(forms.SplitDateTimeWidget): ...
class AdminRadioSelect(forms.RadioSelect): ...
class AdminFileWidget(forms.ClearableFileInput): ...
def url_params_from_lookup_dict(lookups: Any) -> Dict[str, str]: ...
class ForeignKeyRawIdWidget(forms.TextInput):
rel: ManyToOneRel = ...
admin_site: AdminSite = ...
db: None = ...
def __init__(self, rel: ForeignObjectRel, admin_site: AdminSite, attrs: None = ..., using: None = ...) -> None: ...
def base_url_parameters(self) -> Dict[str, str]: ...
def url_parameters(self) -> Dict[str, str]: ...
def label_and_url_for_value(self, value: Union[int, str, UUID]) -> Tuple[str, str]: ...
class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): ...
class RelatedFieldWidgetWrapper(forms.Widget):
template_name: str = ...
choices: ModelChoiceIterator = ...
widget: forms.Widget = ...
rel: ManyToOneRel = ...
can_add_related: bool = ...
can_change_related: bool = ...
can_delete_related: bool = ...
can_view_related: bool = ...
admin_site: AdminSite = ...
def __init__(
self,
widget: forms.Widget,
rel: ForeignObjectRel,
admin_site: AdminSite,
can_add_related: Optional[bool] = ...,
can_change_related: bool = ...,
can_delete_related: bool = ...,
can_view_related: bool = ...,
) -> None: ...
@property
def media(self) -> Media: ...
def get_related_url(self, info: Tuple[str, str], action: str, *args: Any) -> str: ...
class AdminTextareaWidget(forms.Textarea): ...
class AdminTextInputWidget(forms.TextInput): ...
class AdminEmailInputWidget(forms.EmailInput): ...
class AdminURLFieldWidget(forms.URLInput): ...
class AdminIntegerFieldWidget(forms.NumberInput):
class_name: str = ...
class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): ...
class AdminUUIDInputWidget(forms.TextInput):
def __init__(self, attrs: Optional[Dict[str, str]] = ...) -> None: ...
SELECT2_TRANSLATIONS: Any
class AutocompleteMixin:
url_name: str = ...
rel: Any = ...
admin_site: Any = ...
db: Any = ...
choices: Any = ...
attrs: Any = ...
def __init__(
self,
rel: ForeignObjectRel,
admin_site: AdminSite,
attrs: Optional[Dict[str, str]] = ...,
choices: Tuple = ...,
using: None = ...,
) -> None: ...
def get_url(self) -> str: ...
@property
def media(self) -> Media: ...
class AutocompleteSelect(AutocompleteMixin, forms.Select): ...
class AutocompleteSelectMultiple(AutocompleteMixin, forms.SelectMultiple): ...

View File

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

View File

@ -0,0 +1,3 @@
from typing import Any, List
urlpatterns: List[Any] = ...

View File

@ -0,0 +1,27 @@
from typing import Any, Callable, Optional
docutils_is_available: bool
def get_view_name(view_func: Callable) -> str: ...
def trim_docstring(docstring: Any): ...
def parse_docstring(docstring: Any): ...
def parse_rst(text: Any, default_reference_context: Any, thing_being_parsed: Optional[Any] = ...): ...
ROLES: Any
def create_reference_role(rolename: Any, urlbase: Any): ...
def default_reference_role(
name: Any,
rawtext: Any,
text: Any,
lineno: Any,
inliner: Any,
options: Optional[Any] = ...,
content: Optional[Any] = ...,
): ...
named_group_matcher: Any
unnamed_group_matcher: Any
def replace_named_groups(pattern: str) -> str: ...
def replace_unnamed_groups(pattern: str) -> str: ...

View File

@ -0,0 +1,21 @@
from typing import Any, Optional, Union
from django.db.models.fields import Field
from django.views.generic import TemplateView
MODEL_METHODS_EXCLUDE: Any
class BaseAdminDocsView(TemplateView): ...
class BookmarkletsView(BaseAdminDocsView): ...
class TemplateTagIndexView(BaseAdminDocsView): ...
class TemplateFilterIndexView(BaseAdminDocsView): ...
class ViewIndexView(BaseAdminDocsView): ...
class ViewDetailView(BaseAdminDocsView): ...
class ModelIndexView(BaseAdminDocsView): ...
class ModelDetailView(BaseAdminDocsView): ...
class TemplateDetailView(BaseAdminDocsView): ...
def get_return_data_type(func_name: Any): ...
def get_readable_field_data_type(field: Union[Field, str]) -> str: ...
def extract_views_from_urlpatterns(urlpatterns: Any, base: str = ..., namespace: Optional[Any] = ...): ...
def simplify_regex(pattern: str) -> str: ...

View File

@ -0,0 +1,34 @@
from typing import Any, List, Optional, Type, Union
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.core.handlers.wsgi import WSGIRequest
from django.db.models.base import Model
from django.db.models.options import Options
from django.http.request import HttpRequest
from .signals import (
user_logged_in as user_logged_in,
user_logged_out as user_logged_out,
user_login_failed as user_login_failed,
)
SESSION_KEY: str
BACKEND_SESSION_KEY: str
HASH_SESSION_KEY: str
REDIRECT_FIELD_NAME: str
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]] = ...
) -> None: ...
def logout(request: HttpRequest) -> None: ...
def get_user_model() -> Type[Model]: ...
def get_user(request: HttpRequest) -> Union[AbstractBaseUser, AnonymousUser]: ...
def get_permission_codename(action: str, opts: Options) -> str: ...
def update_session_auth_hash(request: WSGIRequest, user: AbstractUser) -> None: ...
default_app_config: str

View File

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

View File

@ -0,0 +1,3 @@
from django.apps import AppConfig
class AuthConfig(AppConfig): ...

View File

@ -0,0 +1,40 @@
from typing import Any, Optional, Set, Union
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser, User, Permission
from django.db.models.base import Model
_AnyUser = Union[Model, AnonymousUser]
UserModel: Any
class BaseBackend:
def authenticate(
self, request: Any, username: Optional[str] = ..., password: Optional[str] = ..., **kwargs: Any
) -> Optional[AbstractBaseUser]: ...
def get_user(self, user_id: int) -> Optional[AbstractBaseUser]: ...
def get_user_permissions(self, user_obj: _AnyUser, obj: Optional[Model] = ...) -> Set[str]: ...
def get_group_permissions(self, user_obj: _AnyUser, obj: Optional[Model] = ...) -> Set[str]: ...
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: ...
class AllowAllUsersRemoteUserBackend(RemoteUserBackend): ...

View File

@ -0,0 +1,44 @@
import sys
from typing import Any, Optional, Tuple, List, overload, TypeVar
from django.db.models.base import Model
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]):
@classmethod
def normalize_email(cls, email: Optional[str]) -> str: ...
def make_random_password(self, length: int = ..., allowed_chars: str = ...) -> str: ...
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)
def get_username(self) -> str: ...
def natural_key(self) -> Tuple[str]: ...
@property
def is_anonymous(self) -> Literal[False]: ...
@property
def is_authenticated(self) -> Literal[True]: ...
def set_password(self, raw_password: Optional[str]) -> None: ...
def check_password(self, raw_password: str) -> bool: ...
def set_unusable_password(self) -> None: ...
def has_usable_password(self) -> bool: ...
def get_session_auth_hash(self) -> str: ...
@classmethod
def get_email_field_name(cls) -> str: ...
@classmethod
@overload
def normalize_username(cls, username: str) -> str: ...
@classmethod
@overload
def normalize_username(cls, username: Any) -> Any: ...

View File

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

View File

@ -0,0 +1,20 @@
from typing import Any, Dict
from django.http.request import HttpRequest
class PermLookupDict:
app_label: str
user: Any
def __init__(self, user: Any, app_label: str) -> None: ...
def __getitem__(self, perm_name: str) -> bool: ...
def __iter__(self) -> Any: ...
def __bool__(self) -> bool: ...
class PermWrapper:
user: Any = ...
def __init__(self, user: Any) -> None: ...
def __getitem__(self, app_label: str) -> PermLookupDict: ...
def __iter__(self) -> Any: ...
def __contains__(self, perm_name: Any) -> bool: ...
def auth(request: HttpRequest) -> Dict[str, Any]: ...

View File

@ -0,0 +1,21 @@
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[[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[[_VIEW], _VIEW]: ...

View File

@ -0,0 +1,91 @@
from typing import Any, Dict, Iterator, Optional
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AbstractUser, User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
from django import forms
UserModel: Any
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name: str = ...
class ReadOnlyPasswordHashField(forms.Field):
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
class UsernameField(forms.CharField): ...
class UserCreationForm(forms.ModelForm):
error_messages: Any = ...
password1: Any = ...
password2: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def clean_password2(self) -> str: ...
class UserChangeForm(forms.ModelForm):
password: Any = ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def clean_password(self) -> str: ...
class AuthenticationForm(forms.Form):
username: Any = ...
password: Any = ...
error_messages: Any = ...
request: WSGIRequest = ...
user_cache: None = ...
username_field: Any = ...
def __init__(self, request: Any = ..., *args: Any, **kwargs: Any) -> None: ...
def confirm_login_allowed(self, user: AbstractBaseUser) -> None: ...
def get_user(self) -> User: ...
def get_invalid_login_error(self) -> ValidationError: ...
class PasswordResetForm(forms.Form):
email: Any = ...
def send_mail(
self,
subject_template_name: str,
email_template_name: str,
context: Dict[str, Any],
from_email: Optional[str],
to_email: str,
html_email_template_name: Optional[str] = ...,
) -> None: ...
def get_users(self, email: str) -> Iterator[Any]: ...
def save(
self,
domain_override: Optional[str] = ...,
subject_template_name: str = ...,
email_template_name: str = ...,
use_https: bool = ...,
token_generator: PasswordResetTokenGenerator = ...,
from_email: Optional[str] = ...,
request: Optional[WSGIRequest] = ...,
html_email_template_name: Optional[str] = ...,
extra_email_context: Optional[Dict[str, str]] = ...,
) -> None: ...
class SetPasswordForm(forms.Form):
error_messages: Any = ...
new_password1: Any = ...
new_password2: Any = ...
user: User = ...
def __init__(self, user: Optional[AbstractBaseUser], *args: Any, **kwargs: Any) -> None: ...
def clean_new_password2(self) -> str: ...
def save(self, commit: bool = ...) -> AbstractBaseUser: ...
class PasswordChangeForm(SetPasswordForm):
old_password: Any = ...
def clean_old_password(self) -> str: ...
class AdminPasswordChangeForm(forms.Form):
error_messages: Any = ...
required_css_class: str = ...
password1: Any = ...
password2: Any = ...
user: User = ...
def __init__(self, user: AbstractUser, *args: Any, **kwargs: Any) -> None: ...
def clean_password2(self) -> str: ...
def save(self, commit: bool = ...) -> AbstractUser: ...

View File

@ -0,0 +1,6 @@
from typing import Any, Dict
UserModel: Any
def check_password(environ: Dict[Any, Any], username: str, password: str) -> Any: ...
def groups_for_user(environ: Dict[Any, Any], username: str) -> Any: ...

View File

@ -0,0 +1,45 @@
from typing import Any, Callable, Dict, List, Optional
UNUSABLE_PASSWORD_PREFIX: str
UNUSABLE_PASSWORD_SUFFIX_LENGTH: int
def is_password_usable(encoded: Optional[str]) -> bool: ...
def check_password(
password: Optional[str], encoded: str, setter: Optional[Callable] = ..., preferred: str = ...
) -> bool: ...
def make_password(password: Optional[str], salt: Optional[str] = ..., hasher: str = ...) -> str: ...
def get_hashers() -> List[BasePasswordHasher]: ...
def get_hashers_by_algorithm() -> Dict[str, BasePasswordHasher]: ...
def reset_hashers(**kwargs: Any) -> None: ...
def get_hasher(algorithm: str = ...) -> BasePasswordHasher: ...
def identify_hasher(encoded: str) -> BasePasswordHasher: ...
def mask_hash(hash: str, show: int = ..., char: str = ...) -> str: ...
class BasePasswordHasher:
algorithm: str = ...
library: str = ...
rounds: int = ...
time_cost: int = ...
memory_cost: int = ...
parallelism: int = ...
digest: Any = ...
iterations: int = ...
def salt(self) -> str: ...
def verify(self, password: str, encoded: str) -> bool: ...
def encode(self, password: str, salt: str) -> Any: ...
def safe_summary(self, encoded: str) -> Any: ...
def must_update(self, encoded: str) -> bool: ...
def harden_runtime(self, password: str, encoded: str) -> None: ...
class PBKDF2PasswordHasher(BasePasswordHasher):
def encode(self, password: str, salt: str, iterations: Optional[int] = ...) -> str: ...
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): ...
class Argon2PasswordHasher(BasePasswordHasher): ...
class BCryptSHA256PasswordHasher(BasePasswordHasher): ...
class BCryptPasswordHasher(BCryptSHA256PasswordHasher): ...
class SHA1PasswordHasher(BasePasswordHasher): ...
class MD5PasswordHasher(BasePasswordHasher): ...
class UnsaltedSHA1PasswordHasher(BasePasswordHasher): ...
class UnsaltedMD5PasswordHasher(BasePasswordHasher): ...
class CryptPasswordHasher(BasePasswordHasher): ...

View File

@ -0,0 +1,15 @@
from typing import Any
from django.apps.config import AppConfig
from django.apps.registry import Apps
def create_permissions(
app_config: AppConfig,
verbosity: int = ...,
interactive: bool = ...,
using: str = ...,
apps: Apps = ...,
**kwargs: Any
) -> None: ...
def get_system_username() -> str: ...
def get_default_username(check_db: bool = ...) -> str: ...

View File

@ -0,0 +1,7 @@
from typing import Any
from django.core.management.base import BaseCommand
UserModel: Any
class Command(BaseCommand): ...

View File

@ -0,0 +1,9 @@
import getpass as getpass # noqa: F401
from typing import Any
from django.core.management.base import BaseCommand
class NotRunningInTTYException(Exception): ...
class Command(BaseCommand):
stdin: Any

View File

@ -0,0 +1,20 @@
from typing import Union
from django.contrib.auth.models import AnonymousUser, User
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.utils.deprecation import MiddlewareMixin
def get_user(request: WSGIRequest) -> Union[AnonymousUser, User]: ...
class AuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request: HttpRequest) -> None: ...
class RemoteUserMiddleware(MiddlewareMixin):
header: str = ...
force_logout_if_no_header: bool = ...
def process_request(self, request: HttpRequest) -> None: ...
def clean_username(self, username: str, request: HttpRequest) -> str: ...
class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
force_logout_if_no_header: bool = ...

View File

@ -0,0 +1,28 @@
from typing import Any, Callable, List, Optional
from django import http
from django.http.response import HttpResponse, HttpResponseRedirect
class AccessMixin:
login_url: Any = ...
permission_denied_message: str = ...
raise_exception: bool = ...
redirect_field_name: Any = ...
def get_login_url(self) -> str: ...
def get_permission_denied_message(self) -> str: ...
def get_redirect_field_name(self) -> str: ...
def handle_no_permission(self) -> HttpResponseRedirect: ...
class LoginRequiredMixin(AccessMixin):
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
class PermissionRequiredMixin(AccessMixin):
permission_required: Any = ...
def get_permission_required(self) -> List[str]: ...
def has_permission(self) -> bool: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...
class UserPassesTestMixin(AccessMixin):
def test_func(self) -> Optional[bool]: ...
def get_test_func(self) -> Callable: ...
def dispatch(self, request: http.HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: ...

View File

@ -0,0 +1,117 @@
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
from django.db.models.base import Model
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["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["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): ...
_T = TypeVar("_T", bound=Model)
class UserManager(BaseUserManager[_T]):
def create_user(
self, username: str, email: Optional[str] = ..., password: Optional[str] = ..., **extra_fields: Any
) -> _T: ...
def create_superuser(
self, username: str, email: Optional[str], password: Optional[str], **extra_fields: Any
) -> _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(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
username_validator: UnicodeUsernameValidator = ...
username = models.CharField(max_length=150)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=150, blank=True)
email = models.EmailField(blank=True)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
EMAIL_FIELD: str = ...
USERNAME_FIELD: str = ...
def get_full_name(self) -> str: ...
def get_short_name(self) -> str: ...
def email_user(self, subject: str, message: str, from_email: str = ..., **kwargs: Any) -> None: ...
class User(AbstractUser): ...
class AnonymousUser:
id: Any = ...
pk: Any = ...
username: str = ...
is_staff: bool = ...
is_active: bool = ...
is_superuser: bool = ...
def save(self) -> Any: ...
def delete(self) -> Any: ...
def set_password(self, raw_password: str) -> Any: ...
def check_password(self, raw_password: str) -> Any: ...
@property
def groups(self) -> EmptyManager: ...
@property
def user_permissions(self) -> EmptyManager: ...
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) -> Literal[True]: ...
@property
def is_authenticated(self) -> Literal[False]: ...
def get_username(self) -> str: ...

View File

@ -0,0 +1,46 @@
from pathlib import Path, PosixPath
from typing import Any, List, Mapping, Optional, Protocol, Sequence, Set, Union
from django.db.models.base import Model
_UserModel = Model
class PasswordValidator(Protocol):
def password_changed(self, password: str, user: Optional[_UserModel] = ...): ...
def get_default_password_validators() -> List[PasswordValidator]: ...
def get_password_validators(validator_config: Sequence[Mapping[str, Any]]) -> List[PasswordValidator]: ...
def validate_password(
password: str, user: Optional[_UserModel] = ..., password_validators: Optional[Sequence[PasswordValidator]] = ...
) -> None: ...
def password_changed(
password: str, user: Optional[_UserModel] = ..., password_validators: Optional[Sequence[PasswordValidator]] = ...
) -> None: ...
def password_validators_help_texts(password_validators: Optional[Sequence[PasswordValidator]] = ...) -> List[str]: ...
password_validators_help_text_html: Any
class MinimumLengthValidator:
min_length: int = ...
def __init__(self, min_length: int = ...) -> None: ...
def validate(self, password: str, user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...
class UserAttributeSimilarityValidator:
DEFAULT_USER_ATTRIBUTES: Sequence[str] = ...
user_attributes: Sequence[str] = ...
max_similarity: float = ...
def __init__(self, user_attributes: Sequence[str] = ..., max_similarity: float = ...) -> None: ...
def validate(self, password: str, user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...
class CommonPasswordValidator:
DEFAULT_PASSWORD_LIST_PATH: Path = ...
passwords: Set[str] = ...
def __init__(self, password_list_path: Union[PosixPath, str] = ...) -> None: ...
def validate(self, password: str, user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...
class NumericPasswordValidator:
def validate(self, password: str, user: Optional[_UserModel] = ...) -> None: ...
def get_help_text(self) -> str: ...

View File

@ -0,0 +1,5 @@
from django.dispatch.dispatcher import Signal
user_logged_in: Signal
user_login_failed: Signal
user_logged_out: Signal

View File

@ -0,0 +1,11 @@
from typing import Any, Optional
from django.contrib.auth.base_user import AbstractBaseUser
class PasswordResetTokenGenerator:
key_salt: str = ...
secret: Any = ...
def make_token(self, user: AbstractBaseUser) -> str: ...
def check_token(self, user: Optional[AbstractBaseUser], token: Optional[str]) -> bool: ...
default_token_generator: Any

View File

@ -0,0 +1,3 @@
from typing import Any, List
urlpatterns: List[Any] = ...

View File

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

View File

@ -0,0 +1,72 @@
from typing import Any, Optional, Set
from django.contrib.auth.base_user import AbstractBaseUser
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
UserModel: Any
class SuccessURLAllowedHostsMixin:
success_url_allowed_hosts: Any = ...
def get_success_url_allowed_hosts(self) -> Set[str]: ...
class LoginView(SuccessURLAllowedHostsMixin, FormView):
authentication_form: Any = ...
redirect_field_name: Any = ...
redirect_authenticated_user: bool = ...
extra_context: Any = ...
def get_redirect_url(self) -> str: ...
class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
next_page: Any = ...
redirect_field_name: Any = ...
extra_context: Any = ...
def post(self, request: WSGIRequest, *args: Any, **kwargs: Any) -> TemplateResponse: ...
def get_next_page(self) -> Optional[str]: ...
def logout_then_login(request: HttpRequest, login_url: Optional[str] = ...) -> HttpResponseRedirect: ...
def redirect_to_login(
next: str, login_url: Optional[str] = ..., redirect_field_name: Optional[str] = ...
) -> HttpResponseRedirect: ...
class PasswordContextMixin:
extra_context: Any = ...
def get_context_data(self, **kwargs: Any): ...
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name: str = ...
extra_email_context: Any = ...
from_email: Any = ...
html_email_template_name: Any = ...
subject_template_name: str = ...
title: Any = ...
token_generator: Any = ...
INTERNAL_RESET_URL_TOKEN: str
INTERNAL_RESET_SESSION_TOKEN: str
class PasswordResetDoneView(PasswordContextMixin, TemplateView):
title: Any = ...
class PasswordResetConfirmView(PasswordContextMixin, FormView):
post_reset_login: bool = ...
post_reset_login_backend: Any = ...
reset_url_token: str = ...
title: Any = ...
token_generator: Any = ...
validlink: bool = ...
user: Any = ...
def get_user(self, uidb64: str) -> Optional[AbstractBaseUser]: ...
class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
title: Any = ...
class PasswordChangeView(PasswordContextMixin, FormView):
title: Any = ...
class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
title: Any = ...

View File

@ -0,0 +1,14 @@
from typing import Any, List, Type
from django.contrib.admin.options import InlineModelAdmin
from django.db.models.base import Model
class GenericInlineModelAdminChecks:
def _check_exclude_of_parent_model(self, obj: GenericInlineModelAdmin, parent_model: Type[Model]) -> List[Any]: ...
def _check_relation(self, obj: GenericInlineModelAdmin, parent_model: Type[Model]) -> List[Any]: ...
class GenericInlineModelAdmin(InlineModelAdmin):
template: str = ...
class GenericStackedInline(GenericInlineModelAdmin): ...
class GenericTabularInline(GenericInlineModelAdmin): ...

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