# fast deletes             for qs in self.fast_deletes:                 count = qs._raw_delete(using=self.using)                deleted_counter[qs.model._meta.label] += count                if count:                    deleted_counter[qs.model._meta.label] += count              # update fields             for model, instances_for_fieldvalues in self.field_updates.items():


query = sql.DeleteQuery(model)                 pk_list = [obj.pk for obj in instances]                 count = query.delete_batch(pk_list, self.using)                deleted_counter[model._meta.label] += count                if count:                    deleted_counter[model._meta.label] += count                  if not model._meta.auto_created:                     for obj in instances:


if isinstance(base, str) and "." in base:                     base_app_label, base_name = base.split(".", 1)                     dependencies.append((base_app_label, base_name, None, True))<ins>                    # Depend on the removal of base fields if the new model has                    # a field with the same name.                    old_base_model_state = self.from_state.models.get((base_app_label, base_name))                    new_base_model_state = self.to_state.models.get((base_app_label, base_name))                    if old_base_model_state and new_base_model_state:                        removed_base_fields = set(old_base_model_state.fields).difference(                            new_base_model_state.fields,                        ).intersection(model_state.fields)                        for removed_base_field in removed_base_fields:                            dependencies.append((base_app_label, base_name, removed_base_field, False))</ins>             # Depend on the other end of the primary key if it's a relation             if primary_key_rel:                 dependencies.append((


"""         assert not self.query.is_sliced, \             "Cannot use 'limit' or 'offset' with in_bulk"        if field_name != 'pk' and not self.model._meta.get_field(field_name).unique:        opts = self.model._meta        unique_fields = [            constraint.fields[0]            for constraint in opts.total_unique_constraints            if len(constraint.fields) == 1        ]        if (            field_name != 'pk' and            not opts.get_field(field_name).unique and            field_name not in unique_fields        ):             raise ValueError("in_bulk()'s field_name must be a unique field but %r isn't." % field_name)         if id_list is not None:             if not id_list:


import os import sys<ins>import warnings</ins> from itertools import takewhile  from django.apps import apps


from django.core.management.base import (     BaseCommand, CommandError, no_translations, )from django.db import DEFAULT_DB_ALIAS, connections, routerfrom django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader


for app_label in consistency_check_labels                     for model in apps.get_app_config(app_label).get_models()             )):                loader.check_consistent_history(connection)                try:                    loader.check_consistent_history(connection)                except OperationalError as error:                    warnings.warn(                        "Got an error checking a consistent migration history "                        "performed for database connection '%s': %s."                        % (alias, error),                        RuntimeWarning,                    )         # Before anything else, see if there's conflicting apps and drop out         # hard if there are any and they don't want to merge         conflicts = loader.detect_conflicts()


content.close()         path, filename = os.path.split(clean_name)         root, ext = os.path.splitext(filename)        if file_hash is not None:            file_hash = ".%s" % file_hash        file_hash = ('.%s' % file_hash) if file_hash else ''         hashed_name = os.path.join(path, "%s%s%s" %                                    (root, file_hash, ext))         unparsed_name = list(parsed_name)


#!/usr/bin/env pythonimport argparseimport subprocessimport sysfrom pathlib import Pathjs_path = Path(__file__).parents[1] / 'static' / 'admin' / 'js'def main():    description = """With no file paths given this script will automaticallycompress files of the admin app. Requires the Google Closure Compiler libraryand Java version 7 or later."""    parser = argparse.ArgumentParser(description=description)    parser.add_argument('file', nargs='*')    parser.add_argument("-v", "--verbose", action="store_true", dest="verbose")    parser.add_argument("-q", "--quiet", action="store_false", dest="verbose")    options = parser.parse_args()    if not options.file:        if options.verbose:            sys.stdout.write("No filenames given; defaulting to admin scripts\n")        files = [            js_path / f            for f in ["actions.js", "collapse.js", "inlines.js", "prepopulate.js"]        ]    else:        files = [Path(f) for f in options.file]    for file_path in files:        to_compress = file_path.expanduser()        if to_compress.exists():            to_compress_min = to_compress.with_suffix('.min.js')            cmd = ['npx']            if not options.verbose:                cmd.append('-q')            cmd.extend([                'google-closure-compiler',                '--language_out=ECMASCRIPT_2015',                '--rewrite_polyfills=false',                '--js', str(to_compress),                '--js_output_file', str(to_compress_min),            ])            if options.verbose:                sys.stdout.write("Running: %s\n" % ' '.join(cmd))            subprocess.run(cmd)        else:            sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress)if __name__ == '__main__':    main()diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py-- a/django/contrib/admin/helpers.py++ b/django/contrib/admin/helpers.py


import json  from django import forms<del>from django.conf import settings</del> from django.contrib.admin.utils import (     display_for_field, flatten_fieldsets, help_text_for_field, label_for_field,     lookup_field,


@property     def media(self):         if 'collapse' in self.classes:            extra = '' if settings.DEBUG else '.min'            return forms.Media(js=['admin/js/collapse%s.js' % extra])            return forms.Media(js=['admin/js/collapse.js'])         return forms.Media()      def __iter__(self):diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py-- a/django/contrib/admin/options.py++ b/django/contrib/admin/options.py


'jquery.init.js',             'core.js',             'admin/RelatedObjectLookups.js',            'actions%s.js' % extra,            'actions.js',             'urlify.js',            'prepopulate%s.js' % extra,            'prepopulate.js',             'vendor/xregexp/xregexp%s.js' % extra,         ]         return forms.Media(js=['admin/js/%s' % url for url in js])


@property     def media(self):         extra = '' if settings.DEBUG else '.min'        js = ['vendor/jquery/jquery%s.js' % extra, 'jquery.init.js',              'inlines%s.js' % extra]        js = ['vendor/jquery/jquery%s.js' % extra, 'jquery.init.js', 'inlines.js']         if self.filter_vertical or self.filter_horizontal:             js.extend(['SelectBox.js', 'SelectFilter2.js'])         if self.classes and 'collapse' in self.classes:            js.append('collapse%s.js' % extra)            js.append('collapse.js')         return forms.Media(js=['admin/js/%s' % url for url in js])      def get_extra(self, request, obj=None, **kwargs):


def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,                     can_delete=False, max_num=None, validate_max=False,                    min_num=None, validate_min=False):                    min_num=None, validate_min=False, absolute_max=None):     """Return a FormSet for the given form class."""     if min_num is None:         min_num = DEFAULT_MIN_NUM     if max_num is None:         max_num = DEFAULT_MAX_NUM    # hard limit on forms instantiated, to prevent memory-exhaustion attacks    # limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM    # if max_num is None in the first place)    absolute_max = max_num + DEFAULT_MAX_NUM    # absolute_max is a hard limit on forms instantiated, to prevent    # memory-exhaustion attacks. Default to max_num + DEFAULT_MAX_NUM    # (which is 2 * DEFAULT_MAX_NUM if max_num is None in the first place).    if absolute_max is None:        absolute_max = max_num + DEFAULT_MAX_NUM    if max_num > absolute_max:        raise ValueError(            "'absolute_max' must be greater or equal to 'max_num'."        )     attrs = {         'form': form,         'extra': extra,diff --git a/django/forms/models.py b/django/forms/models.py-- a/django/forms/models.py++ b/django/forms/models.py


can_order=False, max_num=None, fields=None, exclude=None,                          widgets=None, validate_max=False, localized_fields=None,                          labels=None, help_texts=None, error_messages=None,                         min_num=None, validate_min=False, field_classes=None):                         min_num=None, validate_min=False, field_classes=None,                         absolute_max=None):     """Return a FormSet class for the given Django model class."""     meta = getattr(form, 'Meta', None)     if (getattr(meta, 'fields', fields) is None and


error_messages=error_messages, field_classes=field_classes)     FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num,                               can_order=can_order, can_delete=can_delete,                              validate_min=validate_min, validate_max=validate_max)                              validate_min=validate_min, validate_max=validate_max,                              absolute_max=absolute_max)     FormSet.model = model     return FormSet


can_delete=True, max_num=None, formfield_callback=None,                           widgets=None, validate_max=False, localized_fields=None,                           labels=None, help_texts=None, error_messages=None,                          min_num=None, validate_min=False, field_classes=None):                          min_num=None, validate_min=False, field_classes=None,                          absolute_max=None):     """     Return an ``InlineFormSet`` for the given kwargs.


'help_texts': help_texts,         'error_messages': error_messages,         'field_classes': field_classes,<ins>        'absolute_max': absolute_max,</ins>     }     FormSet = modelformset_factory(model, **kwargs)     FormSet.fk = fk


from django.conf import settings from django.utils import timezone<ins>from django.utils.deprecation import RemovedInDjango40Warning</ins> from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe


class IfEqualNode(Node):<ins>    # RemovedInDjango40Warning.</ins>     child_nodelists = ('nodelist_true', 'nodelist_false')      def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):


def do_ifequal(parser, token, negate):<ins>    # RemovedInDjango40Warning.</ins>     bits = list(token.split_contents())     if len(bits) != 3:         raise TemplateSyntaxError("%r takes two arguments" % bits[0])


...         {% endifnotequal %}     """<ins>    warnings.warn(        'The {% ifequal %} template tag is deprecated in favor of {% if %}.',        RemovedInDjango40Warning,    )</ins>     return do_ifequal(parser, token, False)


Output the contents of the block if the two arguments are not equal.     See ifequal.     """<ins>    warnings.warn(        'The {% ifnotequal %} template tag is deprecated in favor of '        '{% if %}.',        RemovedInDjango40Warning,    )</ins>     return do_ifequal(parser, token, True)


import warnings from django.urls import include, re_pathfrom django.utils.deprecation import RemovedInDjango40Warning from django.views import defaults  __all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include', 'url']


def url(regex, view, kwargs=None, name=None):    warnings.warn(        'django.conf.urls.url() is deprecated in favor of '        'django.urls.re_path().',        RemovedInDjango40Warning,    )     return re_path(regex, view, kwargs, name)diff --git a/django/views/i18n.py b/django/views/i18n.py-- a/django/views/i18n.py++ b/django/views/i18n.py


Return the selected language catalog as a JavaScript library.      Receive the list of packages to check for translations in the `packages`    kwarg either from the extra dictionary passed to the url() function or as a    plus-sign delimited string from the request. Default is 'django.conf'.    kwarg either from the extra dictionary passed to the path() function or as    a plus-sign delimited string from the request. Default is 'django.conf'.      You can override the gettext domain for this view, but usually you don't     want to do that as JavaScript messages go to the djangojs domain. This


id='models.W038',                     )                 )<ins>            fields = (                field                for constraint in cls._meta.constraints if isinstance(constraint, UniqueConstraint)                for field in constraint.fields            )            errors.extend(cls._check_local_fields(fields, 'constraints'))</ins>         return errors


else:                         _cls = None                 except (FieldDoesNotExist, AttributeError):                    if fld is None or fld.get_transform(part) is None:                    if fld is None or (                        fld.get_transform(part) is None and fld.get_lookup(part) is None                    ):                         errors.append(                             checks.Error(                                 "'ordering' refers to the nonexistent field, "


ignore_patterns = ['CVS', '.*', '*~']      def ready(self):        checks.register(check_finders, 'staticfiles')        checks.register(check_finders, checks.Tags.staticfiles)diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py-- a/django/contrib/staticfiles/management/commands/collectstatic.py++ b/django/contrib/staticfiles/management/commands/collectstatic.py


from django.apps import apps from django.contrib.staticfiles.finders import get_finders from django.contrib.staticfiles.storage import staticfiles_storage<ins>from django.core.checks import Tags</ins> from django.core.files.storage import FileSystemStorage from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style


return True      def add_arguments(self, parser):<ins>        parser.add_argument(            '--skip-checks', action='store_true',            help='Skip system checks.',        )</ins>         parser.add_argument(             '--noinput', '--no-input', action='store_false', dest='interactive',             help="Do NOT prompt the user for input of any kind.",


def handle(self, **options):         self.set_options(**options)        if not options['skip_checks']:            self.check(tags=[Tags.staticfiles])          message = ['\n']         if self.dry_run:diff --git a/django/core/checks/registry.py b/django/core/checks/registry.py-- a/django/core/checks/registry.py++ b/django/core/checks/registry.py


models = 'models'     security = 'security'     signals = 'signals'<ins>    staticfiles = 'staticfiles'</ins>     templates = 'templates'     translation = 'translation'     urls = 'urls'


"""     Check that the admin's dependencies are correctly installed.     """<ins>    from django.contrib.admin.sites import all_sites</ins>     if not apps.is_installed('django.contrib.admin'):         return []     errors = []


"the admin application.",                 id='admin.E404',             ))<ins>        sidebar_enabled = any(site.enable_nav_sidebar for site in all_sites)        if (sidebar_enabled and 'django.template.context_processors.request'                not in django_templates_instance.context_processors):            errors.append(checks.Warning(                "'django.template.context_processors.request' must be enabled "                "in DjangoTemplates (TEMPLATES) in order to use the admin "                "navigation sidebar.",                id='admin.W411',            ))</ins>      if not _contains_subclass('django.contrib.auth.middleware.AuthenticationMiddleware', settings.MIDDLEWARE):         errors.append(checks.Error(


"""         Return a new QuerySet instance that will select only distinct results.         """<ins>        self._not_support_combined_queries('distinct')</ins>         assert not self.query.is_sliced, \             "Cannot create distinct fields once a slice has been taken."         obj = self._chain()


else:                 # Reuse aliases of expressions already selected in subquery.                 for col_alias, selected_annotation in self.annotation_select.items():                    if selected_annotation == expr:                    if selected_annotation is expr:                         new_expr = Ref(col_alias, expr)                         break                 else:


from urllib.parse import urlparse from urllib.request import url2pathname <ins>from asgiref.sync import sync_to_async</ins> from django.conf import settings from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve


except Http404 as e:             return response_for_exception(request, e) <ins>    async def get_response_async(self, request):        try:            return await sync_to_async(self.serve)(request)        except Http404 as e:            return await sync_to_async(response_for_exception)(request, e)</ins>  class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler):     """


# Library management from .library import Library                                            # NOQA isort:skip # Import the .autoreload module to trigger the registrations of signals.from . import autoreload                                                # NOQA isort:skip  __all__ += ('Template', 'Context', 'RequestContext')diff --git a/django/template/autoreload.py b/django/template/autoreload.pynew file mode 100644-- /dev/null++ b/django/template/autoreload.py


from django.dispatch import receiverfrom django.template import enginesfrom django.template.backends.django import DjangoTemplatesfrom django.utils.autoreload import (    autoreload_started, file_changed, is_django_path,)def get_template_directories():    # Iterate through each template backend and find    # any template_loader that has a 'get_dirs' method.    # Collect the directories, filtering out Django templates.    items = set()    for backend in engines.all():        if not isinstance(backend, DjangoTemplates):            continue        items.update(backend.engine.dirs)        for loader in backend.engine.template_loaders:            if not hasattr(loader, 'get_dirs'):                continue            items.update(                directory                for directory in loader.get_dirs()                if not is_django_path(directory)            )    return itemsdef reset_loaders():    for backend in engines.all():        if not isinstance(backend, DjangoTemplates):            continue        for loader in backend.engine.template_loaders:            loader.reset()@receiver(autoreload_started, dispatch_uid='template_loaders_watch_changes')def watch_for_template_changes(sender, **kwargs):    for directory in get_template_directories():        sender.watch_dir(directory, '**/*')@receiver(file_changed, dispatch_uid='template_loaders_file_changed')def template_changed(sender, file_path, **kwargs):    for template_dir in get_template_directories():        if template_dir in file_path.parents:            reset_loaders()            return Truediff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py-- a/django/template/loaders/cached.py++ b/django/template/loaders/cached.py


self.loaders = engine.get_template_loaders(loaders)         super().__init__(engine)     def get_dirs(self):        for loader in self.loaders:            if hasattr(loader, "get_dirs"):                yield from loader.get_dirs()     def get_contents(self, origin):         return origin.loader.get_contents(origin) diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py-- a/django/utils/autoreload.py++ b/django/utils/autoreload.py


from types import ModuleType from zipimport import zipimporter <ins>import django</ins> from django.apps import apps from django.core.signals import request_finished from django.dispatch import Signal


pywatchman = None  <ins>def is_django_module(module):    """Return True if the given module is nested under Django."""    return module.__name__.startswith('django.')def is_django_path(path):    """Return True if the given file path is nested under Django."""    return Path(django.__file__).parent in Path(path).parents</ins> def check_errors(fn):     @functools.wraps(fn)     def wrapper(*args, **kwargs):


def _subscribe(self, directory, name, expression):         root, rel_path = self._watch_root(directory)        # Only receive notifications of files changing, filtering out other types        # like special files: https://facebook.github.io/watchman/docs/type        only_files_expression = [            'allof',            ['anyof', ['type', 'f'], ['type', 'l']],            expression        ]         query = {            'expression': expression,            'expression': only_files_expression,             'fields': ['name'],             'since': self._get_clock(root),             'dedup_results': True,diff --git a/django/utils/translation/reloader.py b/django/utils/translation/reloader.py-- a/django/utils/translation/reloader.py++ b/django/utils/translation/reloader.py


from asgiref.local import Local  from django.apps import appsdef _is_django_module(module):    """Return True if the given module is nested under Django."""    return module.__name__.startswith('django.')from django.utils.autoreload import is_django_module   def watch_for_translation_changes(sender, **kwargs):


directories.extend(             Path(config.path) / 'locale'             for config in apps.get_app_configs()            if not _is_django_module(config.module)            if not is_django_module(config.module)         )         directories.extend(Path(p) for p in settings.LOCALE_PATHS)         for path in directories:


from importlib import import_module  from django.conf import settingsfrom django.core.management.base import BaseCommandfrom django.core.management.base import BaseCommand, CommandError   class Command(BaseCommand):


try:             engine.SessionStore.clear_expired()         except NotImplementedError:            self.stderr.write(            raise CommandError(                 "Session engine '%s' doesn't support clearing expired "                 "sessions." % settings.SESSION_ENGINE             )


def __init__(self, queryset, output_field=None, **extra):         self.query = queryset.query         self.extra = extra        # Prevent the QuerySet from being evaluated.        self.queryset = queryset._chain(_result_cache=[], prefetch_done=True)         super().__init__(output_field)      def __getstate__(self):         state = super().__getstate__()        state.pop('_constructor_args', None)        args, kwargs = state['_constructor_args']        if args:            args = (self.queryset, *args[1:])        else:            kwargs['queryset'] = self.queryset        state['_constructor_args'] = args, kwargs         return state      def get_source_expressions(self):


conditional = False      def __init__(self, condition=None, then=None, **lookups):        if lookups and condition is None:            condition, lookups = Q(**lookups), None        if lookups:            if condition is None:                condition, lookups = Q(**lookups), None            elif getattr(condition, 'conditional', False):                condition, lookups = Q(condition, **lookups), None         if condition is None or not getattr(condition, 'conditional', False) or lookups:             raise TypeError(                 'When() supports a Q object, a boolean expression, or lookups '


from django.db.models.functions import Coalesce from django.db.models.manager import Manager from django.db.models.options import Optionsfrom django.db.models.query import Qfrom django.db.models.query import F, Q from django.db.models.signals import (     class_prepared, post_init, post_save, pre_init, pre_save, )


return errors <ins>    @classmethod    def _get_expr_references(cls, expr):        if isinstance(expr, Q):            for child in expr.children:                if isinstance(child, tuple):                    lookup, value = child                    yield tuple(lookup.split(LOOKUP_SEP))                    yield from cls._get_expr_references(value)                else:                    yield from cls._get_expr_references(child)        elif isinstance(expr, F):            yield tuple(expr.name.split(LOOKUP_SEP))        elif hasattr(expr, 'get_source_expressions'):            for src_expr in expr.get_source_expressions():                yield from cls._get_expr_references(src_expr)</ins>     @classmethod     def _check_constraints(cls, databases):         errors = []


id='models.W039',                     )                 )            fields = chain.from_iterable(            fields = set(chain.from_iterable(                 (*constraint.fields, *constraint.include)                 for constraint in cls._meta.constraints if isinstance(constraint, UniqueConstraint)            )            ))            references = set()            for constraint in cls._meta.constraints:                if isinstance(constraint, UniqueConstraint):                    if (                        connection.features.supports_partial_indexes or                        'supports_partial_indexes' not in cls._meta.required_db_features                    ) and isinstance(constraint.condition, Q):                        references.update(cls._get_expr_references(constraint.condition))                elif isinstance(constraint, CheckConstraint):                    if (                        connection.features.supports_table_check_constraints or                        'supports_table_check_constraints' not in cls._meta.required_db_features                    ) and isinstance(constraint.check, Q):                        references.update(cls._get_expr_references(constraint.check))            for field_name, *lookups in references:                # pk is an alias that won't be found by opts.get_field.                if field_name != 'pk':                    fields.add(field_name)                if not lookups:                    # If it has no lookups it cannot result in a JOIN.                    continue                try:                    if field_name == 'pk':                        field = cls._meta.pk                    else:                        field = cls._meta.get_field(field_name)                    if not field.is_relation or field.many_to_many or field.one_to_many:                        continue                except FieldDoesNotExist:                    continue                # JOIN must happen at the first lookup.                first_lookup = lookups[0]                if (                    field.get_transform(first_lookup) is None and                    field.get_lookup(first_lookup) is None                ):                    errors.append(                        checks.Error(                            "'constraints' refers to the joined field '%s'."                            % LOOKUP_SEP.join([field_name] + lookups),                            obj=cls,                            id='models.E041',                        )                    )             errors.extend(cls._check_local_fields(fields, 'constraints'))         return errors


elif isinstance(value, bool):  # Make sure booleans don't get treated as numbers         return str(value)     elif isinstance(value, (decimal.Decimal, float, int)):<ins>        if use_l10n is False:            return str(value)</ins>         return number_format(value, use_l10n=use_l10n)     elif isinstance(value, datetime.datetime):         return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)


from django.core.exceptions import EmptyResultSet, FieldError from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEPfrom django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Valuefrom django.db.models.expressions import F, OrderBy, Random, RawSQL, Ref, Value from django.db.models.functions import Cast from django.db.models.query_utils import Q, select_related_descend from django.db.models.sql.constants import (


resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)             if self.query.combinator:                 src = resolved.get_source_expressions()[0]                expr_src = expr.get_source_expressions()[0]                 # Relabel order by columns to raw numbers if this is a combined                 # query; necessary since the columns can't be referenced by the                 # fully qualified name and the simple column names may collide.                 for idx, (sel_expr, _, col_alias) in enumerate(self.select):                     if is_ref and col_alias == src.refs:                         src = src.source                    elif col_alias:                    elif col_alias and not (                        isinstance(expr_src, F) and col_alias == expr_src.name                    ):                         continue                     if src == sel_expr:                         resolved.set_source_expressions([RawSQL('%d' % (idx + 1), ())])


class SQLDeleteCompiler(SQLCompiler):     @cached_property     def single_alias(self):<ins>        # Ensure base table is in aliases.        self.query.get_initial_alias()</ins>         return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1      def _as_sql(self, query):


errors.append(checks.Error(             "'django.contrib.sessions.middleware.SessionMiddleware' must "             "be in MIDDLEWARE in order to use the admin application.",<ins>            hint=(                "Insert "                "'django.contrib.sessions.middleware.SessionMiddleware' "                "before "                "'django.contrib.auth.middleware.AuthenticationMiddleware'."            ),</ins>             id='admin.E410',         ))     return errors


@keep_lazy_text def slugify(value, allow_unicode=False):     """    Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.    Remove characters that aren't alphanumerics, underscores, or hyphens.    Convert to lowercase. Also strip leading and trailing whitespace.    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated    dashes to single dashes. Remove characters that aren't alphanumerics,    underscores, or hyphens. Convert to lowercase. Also strip leading and    trailing whitespace, dashes, and underscores.     """     value = str(value)     if allow_unicode:         value = unicodedata.normalize('NFKC', value)     else:         value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')    value = re.sub(r'[^\w\s-]', '', value.lower()).strip()    return re.sub(r'[-\s]+', '-', value)    value = re.sub(r'[^\w\s-]', '', value.lower())    return re.sub(r'[-\s]+', '-', value).strip('-_')   def camel_case_to_spaces(value):


def get_source_expressions(self):         return [self.expression] <ins>    def get_group_by_cols(self, alias=None):        return self.expression.get_group_by_cols(alias=alias)</ins>     def as_sql(self, compiler, connection):         return self.expression.as_sql(compiler, connection)


if ord(char) < 33 or ord(char) == 127:             yield (                 'Cache key contains characters that will cause errors if '                'used with memcached: %r' % key, CacheKeyWarning                'used with memcached: %r' % key             )             break


return self.context.create_decimal_from_float(value)         try:             return decimal.Decimal(value)        except decimal.InvalidOperation:        except (decimal.InvalidOperation, TypeError, ValueError):             raise exceptions.ValidationError(                 self.error_messages['invalid'],                 code='invalid',


def check_filterable(self, expression):         """Raise an error if expression cannot be used in a WHERE clause."""        if not getattr(expression, 'filterable', True):        if (            hasattr(expression, 'resolve_expression') and            not getattr(expression, 'filterable', True)        ):             raise NotSupportedError(                 expression.__class__.__name__ + ' is disallowed in the filter '                 'clause.'


)          if self.rhs_is_direct_value():            # Remove None from the list as NULL is never equal to anything.             try:                 rhs = OrderedSet(self.rhs)                rhs.discard(None)             except TypeError:  # Unhashable items in self.rhs                rhs = self.rhs                rhs = [r for r in self.rhs if r is not None]              if not rhs:                 raise EmptyResultSet


except OperationalError as error:                     warnings.warn(                         "Got an error checking a consistent migration history "                        "performed for database connection '%s': %s."                        "performed for database connection '%s': %s"                         % (alias, error),                         RuntimeWarning,                     )


# If we get to this point and the field is a relation to another model,         # append the default ordering for that model unless it is the pk         # shortcut or the attribute name of the field that is specified.        if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk':        if (            field.is_relation and            opts.ordering and            getattr(field, 'attname', None) != pieces[-1] and            name != 'pk'        ):             # Firstly, avoid infinite loops.             already_seen = already_seen or set()             join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)


library = 'argon2'      time_cost = 2    memory_cost = 512    parallelism = 2    memory_cost = 102400    parallelism = 8      def encode(self, password, salt):         argon2 = self._load_library()        params = self.params()         data = argon2.low_level.hash_secret(             password.encode(),             salt.encode(),            time_cost=self.time_cost,            memory_cost=self.memory_cost,            parallelism=self.parallelism,            hash_len=argon2.DEFAULT_HASH_LENGTH,            type=argon2.low_level.Type.I,            time_cost=params.time_cost,            memory_cost=params.memory_cost,            parallelism=params.parallelism,            hash_len=params.hash_len,            type=params.type,         )         return self.algorithm + data.decode('ascii')


algorithm, rest = encoded.split('$', 1)         assert algorithm == self.algorithm         try:            return argon2.low_level.verify_secret(                ('$' + rest).encode('ascii'),                password.encode(),                type=argon2.low_level.Type.I,            )            return argon2.PasswordHasher().verify('$' + rest, password)         except argon2.exceptions.VerificationError:             return False


}      def must_update(self, encoded):        (algorithm, variety, version, time_cost, memory_cost, parallelism,            salt, data) = self._decode(encoded)        algorithm, rest = encoded.split('$', 1)         assert algorithm == self.algorithm         argon2 = self._load_library()        return (            argon2.low_level.ARGON2_VERSION != version or            self.time_cost != time_cost or            self.memory_cost != memory_cost or            self.parallelism != parallelism        )        current_params = argon2.extract_parameters('$' + rest)        new_params = self.params()        # Set salt_len to the salt_len of the current parameters because salt        # is explicitly passed to argon2.        new_params.salt_len = current_params.salt_len        return current_params != new_params      def harden_runtime(self, password, encoded):         # The runtime for Argon2 is too complicated to implement a sensible         # hardening algorithm.         pass     def params(self):        argon2 = self._load_library()        # salt_len is a noop, because we provide our own salt.        return argon2.Parameters(            type=argon2.low_level.Type.ID,            version=argon2.low_level.ARGON2_VERSION,            salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH,            hash_len=argon2.DEFAULT_HASH_LENGTH,            time_cost=self.time_cost,            memory_cost=self.memory_cost,            parallelism=self.parallelism,        )     def _decode(self, encoded):         """         Split an encoded hash and return: (


parallelism, salt, data,         ).         """        bits = encoded.split('$')        if len(bits) == 5:            # Argon2 < 1.3            algorithm, variety, raw_params, salt, data = bits            version = 0x10        else:            assert len(bits) == 6            algorithm, variety, raw_version, raw_params, salt, data = bits            assert raw_version.startswith('v=')            version = int(raw_version[len('v='):])        params = dict(bit.split('=', 1) for bit in raw_params.split(','))        assert len(params) == 3 and all(x in params for x in ('t', 'm', 'p'))        time_cost = int(params['t'])        memory_cost = int(params['m'])        parallelism = int(params['p'])        argon2 = self._load_library()        algorithm, rest = encoded.split('$', 1)        params = argon2.extract_parameters('$' + rest)        variety, *_, salt, data = rest.split('$')         return (            algorithm, variety, version, time_cost, memory_cost, parallelism,            salt, data,            algorithm, variety, params.version, params.time_cost,            params.memory_cost, params.parallelism, salt, data,         )


on reloading.     """     import django.__main__    django_main_path = Path(django.__main__.__file__)    py_script = Path(sys.argv[0])      args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]    if sys.argv[0] == django.__main__.__file__:    if py_script == django_main_path:         # The server was started with `python -m django runserver`.         args += ['-m', 'django']         args += sys.argv[1:]    elif not py_script.exists():        # sys.argv[0] may not exist for several reasons on Windows.        # It may exist with a .exe extension or have a -script.py suffix.        exe_entrypoint = py_script.with_suffix('.exe')        if exe_entrypoint.exists():            # Should be executed directly, ignoring sys.executable.            return [exe_entrypoint, *sys.argv[1:]]        script_entrypoint = py_script.with_name('%s-script.py' % py_script.name)        if script_entrypoint.exists():            # Should be executed as usual.            return [*args, script_entrypoint, *sys.argv[1:]]        raise RuntimeError('Script %s does not exist.' % py_script)     else:         args += sys.argv     return args


import concurrent.futures import glob import os<ins>from pathlib import Path</ins>  from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import (


def has_bom(fn):    with open(fn, 'rb') as f:    with fn.open('rb') as f:         sample = f.read(4)     return sample.startswith((codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))


with concurrent.futures.ThreadPoolExecutor() as executor:             futures = []             for i, (dirpath, f) in enumerate(locations):                po_path = Path(dirpath) / f                mo_path = po_path.with_suffix('.mo')                try:                    if mo_path.stat().st_mtime >= po_path.stat().st_mtime:                        if self.verbosity > 0:                            self.stdout.write(                                'File “%s” is already compiled and up to date.'                                % po_path                            )                        continue                except FileNotFoundError:                    pass                 if self.verbosity > 0:                     self.stdout.write('processing file %s in %s' % (f, dirpath))                po_path = os.path.join(dirpath, f)                 if has_bom(po_path):                     self.stderr.write(                         'The %s file has a BOM (Byte Order Mark). Django only '


)                     self.has_errors = True                     continue                base_path = os.path.splitext(po_path)[0]                  # Check writability on first location                if i == 0 and not is_writable(base_path + '.mo'):                if i == 0 and not is_writable(mo_path):                     self.stderr.write(                         'The po files under %s are in a seemingly not writable location. '                         'mo files will not be updated/created.' % dirpath


self.has_errors = True                     return                 args = [self.program] + self.program_options + [                    '-o', base_path + '.mo', base_path + '.po'                ]                args = [self.program, *self.program_options, '-o', mo_path, po_path]                 futures.append(executor.submit(popen_wrapper, args))              for future in concurrent.futures.as_completed(futures):


cursor.execute(                     connection.ops.cache_key_culling_sql() % table,                     [cull_num])                cursor.execute("DELETE FROM %s "                               "WHERE cache_key < %%s" % table,                               [cursor.fetchone()[0]])                last_cache_key = cursor.fetchone()                if last_cache_key:                    cursor.execute(                        'DELETE FROM %s WHERE cache_key < %%s' % table,                        [last_cache_key[0]],                    )      def clear(self):         db = router.db_for_write(self.cache_model_class)


def add_fields(self, form, index):         """A hook for adding extra fields on to each form instance."""        initial_form_count = self.initial_form_count()         if self.can_order:             # Only pre-fill the ordering field for initial forms.            if index is not None and index < self.initial_form_count():            if index is not None and index < initial_form_count:                 form.fields[ORDERING_FIELD_NAME] = IntegerField(                     label=_('Order'),                     initial=index + 1,


required=False,                     widget=self.get_ordering_widget(),                 )        if self.can_delete:        if self.can_delete and (self.can_delete_extra or index < initial_form_count):             form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False)      def add_prefix(self, index):


def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,                     can_delete=False, max_num=None, validate_max=False,                    min_num=None, validate_min=False, absolute_max=None):                    min_num=None, validate_min=False, absolute_max=None,                    can_delete_extra=True):     """Return a FormSet for the given form class."""     if min_num is None:         min_num = DEFAULT_MIN_NUM


'extra': extra,         'can_order': can_order,         'can_delete': can_delete,        'can_delete_extra': can_delete_extra,         'min_num': min_num,         'max_num': max_num,         'absolute_max': absolute_max,diff --git a/django/forms/models.py b/django/forms/models.py-- a/django/forms/models.py++ b/django/forms/models.py


widgets=None, validate_max=False, localized_fields=None,                          labels=None, help_texts=None, error_messages=None,                          min_num=None, validate_min=False, field_classes=None,                         absolute_max=None):                         absolute_max=None, can_delete_extra=True):     """Return a FormSet class for the given Django model class."""     meta = getattr(form, 'Meta', None)     if (getattr(meta, 'fields', fields) is None and


FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num,                               can_order=can_order, can_delete=can_delete,                               validate_min=validate_min, validate_max=validate_max,                              absolute_max=absolute_max)                              absolute_max=absolute_max, can_delete_extra=can_delete_extra)     FormSet.model = model     return FormSet


widgets=None, validate_max=False, localized_fields=None,                           labels=None, help_texts=None, error_messages=None,                           min_num=None, validate_min=False, field_classes=None,                          absolute_max=None):                          absolute_max=None, can_delete_extra=True):     """     Return an ``InlineFormSet`` for the given kwargs.


'error_messages': error_messages,         'field_classes': field_classes,         'absolute_max': absolute_max,<ins>        'can_delete_extra': can_delete_extra,</ins>     }     FormSet = modelformset_factory(model, **kwargs)     FormSet.fk = fk


return          using = router.db_for_read(self.remote_field.model, instance=model_instance)        qs = self.remote_field.model._default_manager.using(using).filter(        qs = self.remote_field.model._base_manager.using(using).filter(             **{self.remote_field.field_name: value}         )         qs = qs.complex_filter(self.get_limit_choices_to())


The first day according to the week format is 0 and the last day is 6.         """         week_format = self.get_week_format()        if week_format == '%W':                 # week starts on Monday        if week_format in {'%W', '%V'}:         # week starts on Monday             return date.weekday()         elif week_format == '%U':               # week starts on Sunday             return (date.weekday() + 1) % 7


date_field = self.get_date_field()         week_format = self.get_week_format()        week_choices = {'%W': '1', '%U': '0'}        week_choices = {'%W': '1', '%U': '0', '%V': '1'}         try:             week_start = week_choices[week_format]         except KeyError:


week_format,                 ', '.join(sorted(week_choices)),             ))        date = _date_from_string(year, self.get_year_format(),                                 week_start, '%w',                                 week, week_format)        year_format = self.get_year_format()        if week_format == '%V' and year_format != '%G':            raise ValueError(                "ISO week directive '%s' is incompatible with the year "                "directive '%s'. Use the ISO year '%%G' instead." % (                    week_format, year_format,                )            )        date = _date_from_string(year, year_format, week_start, '%w', week, week_format)         since = self._make_date_lookup_arg(date)         until = self._make_date_lookup_arg(self._get_next_week(date))         lookup_kwargs = {


if self.remote_field.parent_link:             kwargs['parent_link'] = self.remote_field.parent_link         if isinstance(self.remote_field.model, str):            kwargs['to'] = self.remote_field.model.lower()            if '.' in self.remote_field.model:                app_label, model_name = self.remote_field.model.split('.')                kwargs['to'] = '%s.%s' % (app_label, model_name.lower())            else:                kwargs['to'] = self.remote_field.model.lower()         else:             kwargs['to'] = self.remote_field.model._meta.label_lower         # If swappable is True, then see if we're actually pointing to the target


raise ValueError(                 'UniqueConstraint with conditions cannot be deferred.'             )<ins>        if include and deferrable:            raise ValueError(                'UniqueConstraint with include fields cannot be deferred.'            )        if opclasses and deferrable:            raise ValueError(                'UniqueConstraint with opclasses cannot be deferred.'            )</ins>         if not isinstance(deferrable, (type(None), Deferrable)):             raise ValueError(                 'UniqueConstraint.deferrable must be a Deferrable instance.'


require_outer = lookup_type == 'isnull' and condition.rhs is True and not current_negated         if current_negated and (lookup_type != 'isnull' or condition.rhs is False) and condition.rhs is not None:             require_outer = True            if (lookup_type != 'isnull' and (                    self.is_nullable(targets[0]) or                    self.alias_map[join_list[-1]].join_type == LOUTER)):            if lookup_type != 'isnull':                 # The condition added here will be SQL like this:                 # NOT (col IS NOT NULL), where the first NOT is added in                 # upper layers of code. The reason for addition is that if col


# (col IS NULL OR col != someval)                 #   <=>                 # NOT (col IS NOT NULL AND col = someval).                lookup_class = targets[0].get_lookup('isnull')                col = self._get_col(targets[0], join_info.targets[0], alias)                clause.add(lookup_class(col, False), AND)                if (                    self.is_nullable(targets[0]) or                    self.alias_map[join_list[-1]].join_type == LOUTER                ):                    lookup_class = targets[0].get_lookup('isnull')                    col = self._get_col(targets[0], join_info.targets[0], alias)                    clause.add(lookup_class(col, False), AND)                # If someval is a nullable column, someval IS NOT NULL is                # added.                if isinstance(value, Col) and self.is_nullable(value.target):                    lookup_class = value.target.get_lookup('isnull')                    clause.add(lookup_class(value, False), AND)         return clause, used_joins if not require_outer else ()      def add_filter(self, filter_clause):


"""         raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_extract_sql() method')     def date_interval_sql(self, timedelta):        """        Implement the date interval functionality for expressions.        """        raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_interval_sql() method')     def date_trunc_sql(self, lookup_type, field_name):         """         Given a lookup_type of 'year', 'month', or 'day', return the SQL thatdiff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py-- a/django/db/backends/mysql/operations.py++ b/django/db/backends/mysql/operations.py


from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.utils import timezone<del>from django.utils.duration import duration_microseconds</del> from django.utils.encoding import force_str


else:             return "TIME(%s)" % (field_name)     def date_interval_sql(self, timedelta):        return 'INTERVAL %s MICROSECOND' % duration_microseconds(timedelta)     def fetch_returned_insert_rows(self, cursor):         """         Given a cursor object that has just performed an INSERT...RETURNINGdiff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py-- a/django/db/backends/sqlite3/operations.py++ b/django/db/backends/sqlite3/operations.py


from django.db.models.expressions import Col from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time<del>from django.utils.duration import duration_microseconds</del> from django.utils.functional import cached_property


"""         return "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name)     def date_interval_sql(self, timedelta):        return str(duration_microseconds(timedelta))     def format_for_duration_arithmetic(self, sql):         """Do nothing since formatting is handled in the custom function."""         return sqldiff --git a/django/db/models/expressions.py b/django/db/models/expressions.py-- a/django/db/models/expressions.py++ b/django/db/models/expressions.py


def _combine(self, other, connector, reversed):         if not hasattr(other, 'resolve_expression'):             # everything must be resolvable to an expression            if isinstance(other, datetime.timedelta):                other = DurationValue(other, output_field=fields.DurationField())            else:                other = Value(other)            output_field = (                fields.DurationField()                if isinstance(other, datetime.timedelta) else                None            )            other = Value(other, output_field=output_field)          if reversed:             return CombinedExpression(other, connector, self)


def as_sql(self, compiler, connection):         try:            lhs_output = self.lhs.output_field            lhs_type = self.lhs.output_field.get_internal_type()         except FieldError:            lhs_output = None            lhs_type = None         try:            rhs_output = self.rhs.output_field            rhs_type = self.rhs.output_field.get_internal_type()         except FieldError:            rhs_output = None        if (not connection.features.has_native_duration_field and                ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or                 (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):            rhs_type = None        if (            not connection.features.has_native_duration_field and            'DurationField' in {lhs_type, rhs_type} and            lhs_type != rhs_type        ):             return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)        if (lhs_output and rhs_output and self.connector == self.SUB and            lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and                lhs_output.get_internal_type() == rhs_output.get_internal_type()):        datetime_fields = {'DateField', 'DateTimeField', 'TimeField'}        if self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type:             return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)         expressions = []         expression_params = []


class DurationExpression(CombinedExpression):     def compile(self, side, compiler, connection):        if not isinstance(side, DurationValue):            try:                output = side.output_field            except FieldError:                pass            else:                if output.get_internal_type() == 'DurationField':                    sql, params = compiler.compile(side)                    return connection.ops.format_for_duration_arithmetic(sql), params        try:            output = side.output_field        except FieldError:            pass        else:            if output.get_internal_type() == 'DurationField':                sql, params = compiler.compile(side)                return connection.ops.format_for_duration_arithmetic(sql), params         return compiler.compile(side)      def as_sql(self, compiler, connection):


return []  <del>class DurationValue(Value):    def as_sql(self, compiler, connection):        connection.ops.check_expression_support(self)        if connection.features.has_native_duration_field:            return super().as_sql(compiler, connection)        return connection.ops.date_interval_sql(self.value), []</del> class RawSQL(Expression):     def __init__(self, sql, params, output_field=None):         if output_field is None:


self.lhs, self.rhs = exprs      def as_sql(self, compiler, connection):<del>        try:            lhs_type = self.lhs.output_field.get_internal_type()        except FieldError:            lhs_type = None        try:            rhs_type = self.rhs.output_field.get_internal_type()        except FieldError:            rhs_type = None        if (            not connection.features.has_native_duration_field and            'DurationField' in {lhs_type, rhs_type} and            lhs_type != rhs_type        ):            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)        datetime_fields = {'DateField', 'DateTimeField', 'TimeField'}        if self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type:            return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)</del>         expressions = []         expression_params = []         sql, params = compiler.compile(self.lhs)


return expression_wrapper % sql, expression_params      def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):        lhs = self.lhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)        rhs = self.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)        if not isinstance(self, (DurationExpression, TemporalSubtraction)):            try:                lhs_type = lhs.output_field.get_internal_type()            except (AttributeError, FieldError):                lhs_type = None            try:                rhs_type = rhs.output_field.get_internal_type()            except (AttributeError, FieldError):                rhs_type = None            if 'DurationField' in {lhs_type, rhs_type} and lhs_type != rhs_type:                return DurationExpression(self.lhs, self.connector, self.rhs).resolve_expression(                    query, allow_joins, reuse, summarize, for_save,                )            datetime_fields = {'DateField', 'DateTimeField', 'TimeField'}            if self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type:                return TemporalSubtraction(self.lhs, self.rhs).resolve_expression(                    query, allow_joins, reuse, summarize, for_save,                )         c = self.copy()         c.is_summary = summarize        c.lhs = c.lhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)        c.rhs = c.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)        c.lhs = lhs        c.rhs = rhs         return c


return compiler.compile(side)      def as_sql(self, compiler, connection):<ins>        if connection.features.has_native_duration_field:            return super().as_sql(compiler, connection)</ins>         connection.ops.check_expression_support(self)         expressions = []         expression_params = []


)  def timesince(d, now=None, reversed=False, time_strings=None):def timesince(d, now=None, reversed=False, time_strings=None, depth=2):     """     Take two datetime objects and return the time between d and now as a nicely     formatted string, e.g. "10 minutes". If d occurs after now, return     "0 minutes".      Units used are years, months, weeks, days, hours, and minutes.    Seconds and microseconds are ignored.  Up to two adjacent units will be    Seconds and microseconds are ignored. Up to `depth` adjacent units will be     displayed.  For example, "2 weeks, 3 days" and "1 year, 3 months" are     possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.      `time_strings` is an optional dict of strings to replace the default     TIME_STRINGS dict.     `depth` is an optional integer to control the number of adjacent time    units returned.     Adapted from     https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since     """     if time_strings is None:         time_strings = TIME_STRINGS    if depth <= 0:        raise ValueError('depth must be greater than 0.')     # Convert datetime.date to datetime.datetime for comparison.     if not isinstance(d, datetime.datetime):         d = datetime.datetime(d.year, d.month, d.day)


count = since // seconds         if count != 0:             break    result = avoid_wrapping(time_strings[name] % count)    if i + 1 < len(TIMESINCE_CHUNKS):        # Now get the second item        seconds2, name2 = TIMESINCE_CHUNKS[i + 1]        count2 = (since - (seconds * count)) // seconds2        if count2 != 0:            result += gettext(', ') + avoid_wrapping(time_strings[name2] % count2)    return result    else:        return avoid_wrapping(time_strings['minute'] % 0)    result = []    current_depth = 0    while i < len(TIMESINCE_CHUNKS) and current_depth < depth:        seconds, name = TIMESINCE_CHUNKS[i]        count = since // seconds        if count == 0:            break        result.append(avoid_wrapping(time_strings[name] % count))        since -= seconds * count        current_depth += 1        i += 1    return gettext(', ').join(result)  def timeuntil(d, now=None, time_strings=None):def timeuntil(d, now=None, time_strings=None, depth=2):     """     Like timesince, but return a string measuring the time until the given time.     """    return timesince(d, now, reversed=True, time_strings=time_strings)    return timesince(d, now, reversed=True, time_strings=time_strings, depth=depth)


obj.annotation_select_mask = None         else:             obj.annotation_select_mask = self.annotation_select_mask.copy()<ins>        obj.combined_queries = tuple(query.clone() for query in self.combined_queries)</ins>         # _annotation_select_cache cannot be copied, as doing so breaks the         # (necessary) state in which both annotations and         # _annotation_select_cache point to the same underlying objects.


def set_empty(self):         self.where.add(NothingNode(), AND)<ins>        for query in self.combined_queries:            query.set_empty()</ins>      def is_empty(self):         return any(isinstance(c, NothingNode) for c in self.where.children)


subclass = type("Migration", (Migration,), {                     "dependencies": [(app_label, migration.name) for migration in merge_migrations],                 })                migration_name = "%04i_%s" % (                    biggest_number + 1,                    self.migration_name or ("merge_%s" % get_migration_name_timestamp())                )                parts = ['%04i' % (biggest_number + 1)]                if self.migration_name:                    parts.append(self.migration_name)                else:                    parts.append('merge')                    leaf_names = '_'.join(sorted(migration.name for migration in merge_migrations))                    if len(leaf_names) > 47:                        parts.append(get_migration_name_timestamp())                    else:                        parts.append(leaf_names)                migration_name = '_'.join(parts)                 new_migration = subclass(migration_name, app_label)                 writer = MigrationWriter(new_migration, self.include_header)


def __init__(self, expression, output_field):         super().__init__(output_field=output_field)<del>        if getattr(expression, '_output_field_or_none', True) is None:            expression = expression.copy()            expression.output_field = output_field</del>         self.expression = expression      def set_source_expressions(self, exprs):


return [self.expression]      def get_group_by_cols(self, alias=None):        return self.expression.get_group_by_cols(alias=alias)        expression = self.expression.copy()        expression.output_field = self.output_field        return expression.get_group_by_cols(alias=alias)      def as_sql(self, compiler, connection):         return self.expression.as_sql(compiler, connection)


def add_filtered_relation(self, filtered_relation, alias):         filtered_relation.alias = alias         lookups = dict(get_children_from_q(filtered_relation.condition))        for lookup in chain((filtered_relation.relation_name,), lookups):            lookup_parts, field_parts, _ = self.solve_lookup_type(lookup)        relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(filtered_relation.relation_name)        if relation_lookup_parts:            raise ValueError(                "FilteredRelation's relation_name cannot contain lookups "                "(got %r)." % filtered_relation.relation_name            )        for lookup in chain(lookups):            lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)             shift = 2 if not lookup_parts else 1            if len(field_parts) > (shift + len(lookup_parts)):                raise ValueError(                    "FilteredRelation's condition doesn't support nested "                    "relations (got %r)." % lookup                )            lookup_field_path = lookup_field_parts[:-shift]            for idx, lookup_field_part in enumerate(lookup_field_path):                if len(relation_field_parts) > idx:                    if relation_field_parts[idx] != lookup_field_part:                        raise ValueError(                            "FilteredRelation's condition doesn't support "                            "relations outside the %r (got %r)."                            % (filtered_relation.relation_name, lookup)                        )                else:                    raise ValueError(                        "FilteredRelation's condition doesn't support nested "                        "relations deeper than the relation_name (got %r for "                        "%r)." % (lookup, filtered_relation.relation_name)                    )         self._filtered_relations[filtered_relation.alias] = filtered_relation      def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):


field = self.annotation_select[name].output_field                 elif name in self._filtered_relations and pos == 0:                     filtered_relation = self._filtered_relations[name]                    field = opts.get_field(filtered_relation.relation_name)                    if LOOKUP_SEP in filtered_relation.relation_name:                        parts = filtered_relation.relation_name.split(LOOKUP_SEP)                        filtered_relation_path, field, _, _ = self.names_to_path(                            parts, opts, allow_many, fail_on_missing,                        )                        path.extend(filtered_relation_path[:-1])                    else:                        field = opts.get_field(filtered_relation.relation_name)             if field is not None:                 # Fields that contain one-to-many relations with a generic                 # model (like a GenericForeignKey) cannot generate reverse


from email.mime.message import MIMEMessage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMETextfrom email.utils import formatdate, getaddresses, make_msgidfrom email.utils import formataddr, formatdate, getaddresses, make_msgid from io import BytesIO, StringIO from pathlib import Path


nm, address = addr         localpart, domain = address.rsplit('@', 1)     nm = Header(nm, encoding).encode()    address_parts = nm + localpart + domain    if '\n' in address_parts or '\r' in address_parts:        raise ValueError('Invalid address; address parts cannot contain newlines.')     # Avoid UTF-8 encode, if it's possible.    try:        nm.encode('ascii')        nm = Header(nm).encode()    except UnicodeEncodeError:        nm = Header(nm, encoding).encode()     try:         localpart.encode('ascii')     except UnicodeEncodeError:         localpart = Header(localpart, encoding).encode()     domain = punycode(domain)     parsed_address = Address(nm, username=localpart, domain=domain)    return str(parsed_address)    parsed_address = Address(username=localpart, domain=domain)    return formataddr((nm, parsed_address.addr_spec))   class MIMEMixin:


samesite=settings.SESSION_COOKIE_SAMESITE,             )         else:            response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)            response.delete_cookie(                self.cookie_name,                domain=settings.SESSION_COOKIE_DOMAIN,                samesite=settings.SESSION_COOKIE_SAMESITE,            )      def _store(self, messages, response, remove_oldest=True, *args, **kwargs):         """diff --git a/django/contrib/sessions/middleware.py b/django/contrib/sessions/middleware.py-- a/django/contrib/sessions/middleware.py++ b/django/contrib/sessions/middleware.py


settings.SESSION_COOKIE_NAME,                 path=settings.SESSION_COOKIE_PATH,                 domain=settings.SESSION_COOKIE_DOMAIN,                samesite=settings.SESSION_COOKIE_SAMESITE,             )             patch_vary_headers(response, ('Cookie',))         else:diff --git a/django/http/response.py b/django/http/response.py-- a/django/http/response.py++ b/django/http/response.py


value = signing.get_cookie_signer(salt=key + salt).sign(value)         return self.set_cookie(key, value, **kwargs)     def delete_cookie(self, key, path='/', domain=None):        # Most browsers ignore the Set-Cookie header if the cookie name starts        # with __Host- or __Secure- and the cookie doesn't use the secure flag.        secure = key.startswith(('__Secure-', '__Host-'))    def delete_cookie(self, key, path='/', domain=None, samesite=None):        # Browsers can ignore the Set-Cookie header if the cookie doesn't use        # the secure flag and:        # - the cookie name starts with "__Host-" or "__Secure-", or        # - the samesite is "none".        secure = (            key.startswith(('__Secure-', '__Host-')) or            (samesite and samesite.lower() == 'none')        )         self.set_cookie(             key, max_age=0, path=path, domain=domain, secure=secure,            expires='Thu, 01 Jan 1970 00:00:00 GMT',            expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite,         )      # Common methods used by subclasses


value = signing.get_cookie_signer(salt=key + salt).sign(value)         return self.set_cookie(key, value, **kwargs)     def delete_cookie(self, key, path='/', domain=None):    def delete_cookie(self, key, path='/', domain=None, samesite=None):         # Most browsers ignore the Set-Cookie header if the cookie name starts         # with __Host- or __Secure- and the cookie doesn't use the secure flag.         secure = key.startswith(('__Secure-', '__Host-'))         self.set_cookie(             key, max_age=0, path=path, domain=domain, secure=secure,            expires='Thu, 01 Jan 1970 00:00:00 GMT',            expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite,         )      # Common methods used by subclasses


continue                 raise             else:<ins>                # Empty directories are namespaces.                # getattr() needed on PY36 and older (replace w/attribute access).                if getattr(module, '__file__', None) is None:                    self.unmigrated_apps.add(app_config.label)                    continue</ins>                 # Module is not a package (e.g. migrations.py).                 if not hasattr(module, '__path__'):                     self.unmigrated_apps.add(app_config.label)


# Force a reload if it's already loaded (tests need this)                 if was_loaded:                     reload(module)            self.migrated_apps.add(app_config.label)             migration_names = {                 name for _, name, is_pkg in pkgutil.iter_modules(module.__path__)                 if not is_pkg and name[0] not in '_~'             }            if migration_names or self.ignore_no_migrations:                self.migrated_apps.add(app_config.label)            else:                self.unmigrated_apps.add(app_config.label)             # Load migrations             for migration_name in migration_names:                 migration_path = '%s.%s' % (module_name, migration_name)


""" Global Django exception and warning classes. """<ins>import operatorfrom django.utils.hashable import make_hashable</ins>   class FieldDoesNotExist(Exception):


def __repr__(self):         return 'ValidationError(%s)' % self <ins>    def __eq__(self, other):        if not isinstance(other, ValidationError):            return NotImplemented        return hash(self) == hash(other)    def __hash__(self):        # Ignore params and messages ordering.        if hasattr(self, 'message'):            return hash((                self.message,                self.code,                tuple(sorted(make_hashable(self.params))) if self.params else None,            ))        if hasattr(self, 'error_dict'):            return hash(tuple(sorted(make_hashable(self.error_dict))))        return hash(tuple(sorted(self.error_list, key=operator.attrgetter('message'))))</ins>  class EmptyResultSet(Exception):     """A database query predicate is impossible."""


author_name=author_name,                 author_email=author_email,                 author_link=author_link,<ins>                comments=self._get_dynamic_attr('item_comments', item),</ins>                 categories=self._get_dynamic_attr('item_categories', item),                 item_copyright=self._get_dynamic_attr('item_copyright', item),                 **self.item_extra_kwargs(item)


file.save(file.name, file.file, save=False)         return file <ins>    def contribute_to_class(self, cls, name, **kwargs):        super().contribute_to_class(cls, name, **kwargs)        setattr(cls, self.attname, self.descriptor_class(self))</ins>     def generate_filename(self, instance, filename):         """         Apply (if callable) or prepend (if a string) upload_to to the filename,


If `strict` is True, raise errors if the old column does not match         `old_field` precisely.         """<ins>        if not self._field_should_be_altered(old_field, new_field):            return</ins>         # Ensure this field is even column-based         old_db_params = old_field.db_parameters(connection=self.connection)         old_type = old_db_params['type']


output.append(self._create_index_sql(model, [field]))         return output     def _field_should_be_altered(self, old_field, new_field):        # Don't alter when changing only a field name.        return (            old_field.column != new_field.column or            old_field.deconstruct()[1:] != new_field.deconstruct()[1:]        )     def _field_should_be_indexed(self, model, field):         return field.db_index and not field.unique diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py-- a/django/db/backends/sqlite3/schema.py++ b/django/db/backends/sqlite3/schema.py


super().alter_db_table(model, old_db_table, new_db_table)      def alter_field(self, model, old_field, new_field, strict=False):<ins>        if not self._field_should_be_altered(old_field, new_field):            return</ins>         old_field_name = old_field.name         table_name = model._meta.db_table         _, old_column_name = old_field.get_attname_column()


return output      def _field_should_be_altered(self, old_field, new_field):        # Don't alter when changing only a field name.        _, old_path, old_args, old_kwargs = old_field.deconstruct()        _, new_path, new_args, new_kwargs = new_field.deconstruct()        # Don't alter when:        # - changing only a field name        # - adding only a db_column and the column name is not changed        old_kwargs.pop('db_column', None)        new_kwargs.pop('db_column', None)         return (             old_field.column != new_field.column or            old_field.deconstruct()[1:] != new_field.deconstruct()[1:]            (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs)         )      def _field_should_be_indexed(self, model, field):


# This is done here for performance reasons so the modified value is cached.         if name in {'MEDIA_URL', 'STATIC_URL'} and val is not None:             val = self._add_script_prefix(val)<ins>        elif name == 'SECRET_KEY' and not val:            raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")</ins>          self.__dict__[name] = val         return val


setattr(self, setting, setting_value)                 self._explicit_settings.add(setting)         if not self.SECRET_KEY:            raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")         if self.is_overridden('PASSWORD_RESET_TIMEOUT_DAYS'):             if self.is_overridden('PASSWORD_RESET_TIMEOUT'):                 raise ImproperlyConfigured(diff --git a/django/contrib/auth/tokens.py b/django/contrib/auth/tokens.py-- a/django/contrib/auth/tokens.py++ b/django/contrib/auth/tokens.py


"""     key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"     algorithm = 'sha256'    secret = settings.SECRET_KEY    secret = None    def __init__(self):        self.secret = self.secret or settings.SECRET_KEY      def make_token(self, user):         """diff --git a/django/core/checks/security/base.py b/django/core/checks/security/base.py-- a/django/core/checks/security/base.py++ b/django/core/checks/security/base.py


from django.conf import settings<ins>from django.core.exceptions import ImproperlyConfigured</ins>  from .. import Error, Tags, Warning, register


@register(Tags.security, deploy=True) def check_secret_key(app_configs, **kwargs):    passed_check = (        getattr(settings, 'SECRET_KEY', None) and        len(set(settings.SECRET_KEY)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and        len(settings.SECRET_KEY) >= SECRET_KEY_MIN_LENGTH    )    try:        secret_key = settings.SECRET_KEY    except (ImproperlyConfigured, AttributeError):        passed_check = False    else:        passed_check = (            len(set(secret_key)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and            len(secret_key) >= SECRET_KEY_MIN_LENGTH        )     return [] if passed_check else [W009]


has_native_json_field = False     # Does the backend use PostgreSQL-style JSON operators like '->'?     has_json_operators = False    # Does the backend support __contains and __contained_by lookups for    # a JSONField?    supports_json_field_contains = True      def __init__(self, connection):         self.connection = connectiondiff --git a/django/db/backends/oracle/features.py b/django/db/backends/oracle/features.py-- a/django/db/backends/oracle/features.py++ b/django/db/backends/oracle/features.py


allows_multiple_constraints_on_same_fields = False     supports_boolean_expr_in_select_clause = False     supports_primitives_in_json_field = False    supports_json_field_contains = False      @cached_property     def introspected_field_types(self):diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py-- a/django/db/backends/sqlite3/base.py++ b/django/db/backends/sqlite3/base.py


import decimal import functools import hashlib<del>import json</del> import math import operator import re


create_deterministic_function('DEGREES', 1, none_guard(math.degrees))         create_deterministic_function('EXP', 1, none_guard(math.exp))         create_deterministic_function('FLOOR', 1, none_guard(math.floor))<del>        create_deterministic_function('JSON_CONTAINS', 2, _sqlite_json_contains)</del>         create_deterministic_function('LN', 1, none_guard(math.log))         create_deterministic_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))         create_deterministic_function('LPAD', 3, _sqlite_lpad)


@none_guard def _sqlite_rpad(text, length, fill_text):     return (text + fill_text * length)[:length]@none_guarddef _sqlite_json_contains(haystack, needle):    target, candidate = json.loads(haystack), json.loads(needle)    if isinstance(target, dict) and isinstance(candidate, dict):        return target.items() >= candidate.items()    return target == candidatediff --git a/django/db/backends/sqlite3/features.py b/django/db/backends/sqlite3/features.py-- a/django/db/backends/sqlite3/features.py++ b/django/db/backends/sqlite3/features.py


supports_aggregate_filter_clause = Database.sqlite_version_info >= (3, 30, 1)     supports_order_by_nulls_modifier = Database.sqlite_version_info >= (3, 30, 0)     order_by_nulls_first = True    supports_json_field_contains = False      @cached_property     def supports_atomic_references_rename(self):diff --git a/django/db/models/fields/json.py b/django/db/models/fields/json.py-- a/django/db/models/fields/json.py++ b/django/db/models/fields/json.py


postgres_operator = '@>'      def as_sql(self, compiler, connection):        if not connection.features.supports_json_field_contains:            raise NotSupportedError(                'contains lookup is not supported on this database backend.'            )         lhs, lhs_params = self.process_lhs(compiler, connection)         rhs, rhs_params = self.process_rhs(compiler, connection)         params = tuple(lhs_params) + tuple(rhs_params)         return 'JSON_CONTAINS(%s, %s)' % (lhs, rhs), params     def as_oracle(self, compiler, connection):        raise NotSupportedError('contains lookup is not supported on Oracle.')  class ContainedBy(PostgresOperatorLookup):     lookup_name = 'contained_by'     postgres_operator = '<@'      def as_sql(self, compiler, connection):        if not connection.features.supports_json_field_contains:            raise NotSupportedError(                'contained_by lookup is not supported on this database backend.'            )         lhs, lhs_params = self.process_lhs(compiler, connection)         rhs, rhs_params = self.process_rhs(compiler, connection)         params = tuple(rhs_params) + tuple(lhs_params)         return 'JSON_CONTAINS(%s, %s)' % (rhs, lhs), params     def as_oracle(self, compiler, connection):        raise NotSupportedError('contained_by lookup is not supported on Oracle.')  class HasKeyLookup(PostgresOperatorLookup):     logical_operator = None


def query(self):         if self._deferred_filter:             negate, args, kwargs = self._deferred_filter            self._filter_or_exclude_inplace(negate, *args, **kwargs)            self._filter_or_exclude_inplace(negate, args, kwargs)             self._deferred_filter = None         return self._query


set.         """         self._not_support_combined_queries('filter')        return self._filter_or_exclude(False, *args, **kwargs)        return self._filter_or_exclude(False, args, kwargs)      def exclude(self, *args, **kwargs):         """


set.         """         self._not_support_combined_queries('exclude')        return self._filter_or_exclude(True, *args, **kwargs)        return self._filter_or_exclude(True, args, kwargs)     def _filter_or_exclude(self, negate, *args, **kwargs):    def _filter_or_exclude(self, negate, args, kwargs):         if args or kwargs:             assert not self.query.is_sliced, \                 "Cannot filter a query once a slice has been taken."


self._defer_next_filter = False             clone._deferred_filter = negate, args, kwargs         else:            clone._filter_or_exclude_inplace(negate, *args, **kwargs)            clone._filter_or_exclude_inplace(negate, args, kwargs)         return clone     def _filter_or_exclude_inplace(self, negate, *args, **kwargs):    def _filter_or_exclude_inplace(self, negate, args, kwargs):         if negate:             self._query.add_q(~Q(*args, **kwargs))         else:


clone.query.add_q(filter_obj)             return clone         else:            return self._filter_or_exclude(False, **filter_obj)            return self._filter_or_exclude(False, args=(), kwargs=filter_obj)      def _combinator_query(self, combinator, *other_qs, all=False):         # Clone the query to inherit the select list and everything


self.generate_removed_fields()         self.generate_added_fields()         self.generate_altered_fields()        self.generate_altered_order_with_respect_to()         self.generate_altered_unique_together()         self.generate_altered_index_together()         self.generate_added_indexes()         self.generate_added_constraints()         self.generate_altered_db_table()        self.generate_altered_order_with_respect_to()          self._sort_migrations()         self._build_migration_list(graph)


dependencies=list(set(dependencies)),                 )             # Generate other opns<ins>            if order_with_respect_to:                self.add_operation(                    app_label,                    operations.AlterOrderWithRespectTo(                        name=model_name,                        order_with_respect_to=order_with_respect_to,                    ),                    dependencies=[                        (app_label, model_name, order_with_respect_to, True),                        (app_label, model_name, None, True),                    ]                )</ins>             related_dependencies = [                 (app_label, model_name, name, True)                 for name in sorted(related_fields)


),                     dependencies=related_dependencies                 )<del>            if order_with_respect_to:                self.add_operation(                    app_label,                    operations.AlterOrderWithRespectTo(                        name=model_name,                        order_with_respect_to=order_with_respect_to,                    ),                    dependencies=[                        (app_label, model_name, order_with_respect_to, True),                        (app_label, model_name, None, True),                    ]                )</del>             # Fix relationships if the model changed from a proxy model to a             # concrete model.             if (app_label, model_name) in self.old_proxy_keys:


opts = self._meta         _setattr = setattr         _DEFERRED = DEFERRED<ins>        if opts.abstract:            raise TypeError('Abstract models cannot be instantiated.')</ins>          pre_init.send(sender=cls, args=args, kwargs=kwargs)


def encode(self, session_dict):         "Return the given session dictionary serialized and encoded as a string."<ins>        # RemovedInDjango40Warning: DEFAULT_HASHING_ALGORITHM will be removed.        if settings.DEFAULT_HASHING_ALGORITHM == 'sha1':            return self._legacy_encode(session_dict)</ins>         return signing.dumps(             session_dict, salt=self.key_salt, serializer=self.serializer,             compress=True,


except Exception:             return self._legacy_decode(session_data) <ins>    def _legacy_encode(self, session_dict):        # RemovedInDjango40Warning.        serialized = self.serializer().dumps(session_dict)        hash = self._hash(serialized)        return base64.b64encode(hash.encode() + b':' + serialized).decode('ascii')</ins>     def _legacy_decode(self, session_data):         # RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.         encoded_data = base64.b64decode(session_data.encode('ascii'))


def __getstate__(self):         """Hook to allow choosing the attributes to pickle."""        return self.__dict__        state = self.__dict__.copy()        state['_state'] = copy.copy(state['_state'])        state['_state'].fields_cache = state['_state'].fields_cache.copy()        return state      def __setstate__(self, state):         pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)


"""         # create() eventually returns app_config_class(app_name, app_module).         app_config_class = None<ins>        app_config_name = None</ins>         app_name = None         app_module = None


)                 else:                     message += (                        "However, Django's automatic detection picked another "                        "configuration, %r. You should move the default "                        "config class to the apps submodule of your "                        "application and, if this module defines several "                        "config classes, mark the default one with default = "                        "True." % app_config_name                        "However, Django's automatic detection %s. You should "                        "move the default config class to the apps submodule "                        "of your application and, if this module defines "                        "several config classes, mark the default one with "                        "default = True." % (                            "picked another configuration, %r" % app_config_name                            if app_config_name                            else "did not find this configuration"                        )                     )                 warnings.warn(message, RemovedInDjango41Warning, stacklevel=2)                 entry = new_entry


update_fields = frozenset(update_fields)             field_names = set()             for field in self._meta.fields:            for field in self._meta.concrete_fields:                 if not field.primary_key:                     field_names.add(field.name)


non_model_fields = update_fields.difference(field_names)              if non_model_fields:                raise ValueError("The following fields do not exist in this "                                 "model or are m2m fields: %s"                                 % ', '.join(non_model_fields))                raise ValueError(                    'The following fields do not exist in this model, are m2m '                    'fields, or are non-concrete fields: %s'                    % ', '.join(non_model_fields)                )          # If saving to the same database, and this model is deferred, then         # automatically do an "update_fields" save on the loaded fields.


from django.urls import reverse from django.utils.decorators import classonlymethod from django.utils.deprecation import RemovedInDjango40Warningfrom django.utils.functional import SimpleLazyObjectfrom django.utils.functional import lazy  logger = logging.getLogger('django.request')


context_kwargs = {}     for key, value in url_kwargs.items():         # Bind into function closure.<del>        @SimpleLazyObject</del>         def access_value(key=key, value=value):             warnings.warn(                 'TemplateView passing URL kwargs to the context is '


RemovedInDjango40Warning, stacklevel=2,             )             return value        context_kwargs[key] = access_value        context_kwargs[key] = lazy(access_value, type(value))()     return context_kwargs


output_field = fields.BooleanField()      def __init__(self, queryset, negated=False, **kwargs):        # As a performance optimization, remove ordering since EXISTS doesn't        # care about it, just whether or not a row matches.        queryset = queryset.order_by()         self.negated = negated         super().__init__(queryset, **kwargs)        self.query = self.query.exists()      def __invert__(self):         clone = self.copy()diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py-- a/django/db/models/sql/compiler.py++ b/django/db/models/sql/compiler.py


Backends (e.g. NoSQL) can override this in order to use optimized         versions of "query has any results."         """        # This is always executed on a query clone, so we can modify self.query        self.query.add_extra({'a': 1}, None, None, None, None, None)        self.query.set_extra_mask(['a'])         return bool(self.execute_sql(SINGLE))      def execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py-- a/django/db/models/sql/query.py++ b/django/db/models/sql/query.py


def has_filters(self):         return self.where     def has_results(self, using):    def exists(self):         q = self.clone()         if not q.distinct:             if q.group_by is True:


q.clear_select_clause()         q.clear_ordering(True)         q.set_limits(high=1)<ins>        q.add_extra({'a': 1}, None, None, None, None, None)        q.set_extra_mask(['a'])        return q    def has_results(self, using):        q = self.exists()</ins>         compiler = q.get_compiler(using=using)         return compiler.has_results()


return result  def get_default_username(check_db=True):def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS):     """     Try to determine the current system user's username to use as a default.      :param check_db: If ``True``, requires that the username does not match an         existing ``auth.User`` (otherwise returns an empty string).    :param database: The database where the unique check will be performed.     :returns: The username, or an empty string if no username can be        determined.        determined or the suggested username is already taken.     """     # This file is used in apps.py, it should not trigger models import.     from django.contrib.auth import models as auth_app


# Don't return the default username if it is already taken.     if check_db and default_username:         try:            auth_app.User._default_manager.get(username=default_username)            auth_app.User._default_manager.db_manager(database).get(                username=default_username,            )         except auth_app.User.DoesNotExist:             pass         else:diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py-- a/django/contrib/auth/management/commands/createsuperuser.py++ b/django/contrib/auth/management/commands/createsuperuser.py


fake_user_data = {}                 if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():                     raise NotRunningInTTYException                default_username = get_default_username()                default_username = get_default_username(database=database)                 if username:                     error_msg = self._validate_username(username, verbose_field_name, database)                     if error_msg:


def apply_limit_choices_to_to_formfield(formfield):     """Apply limit_choices_to to the formfield's queryset if needed."""    from django.db.models import Exists, OuterRef, Q     if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'):         limit_choices_to = formfield.get_limit_choices_to()        if limit_choices_to is not None:            formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)        if limit_choices_to:            complex_filter = limit_choices_to            if not isinstance(complex_filter, Q):                complex_filter = Q(**limit_choices_to)            complex_filter &= Q(pk=OuterRef('pk'))            # Use Exists() to avoid potential duplicates.            formfield.queryset = formfield.queryset.filter(                Exists(formfield.queryset.model._base_manager.filter(complex_filter)),            )   def fields_for_model(model, fields=None, exclude=None, widgets=None,


return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer)         # RemovedInDjango40Warning: when the deprecation ends, handle here         # exceptions similar to what _legacy_decode() does now.<ins>        except signing.BadSignature:            try:                # Return an empty session if data is not in the pre-Django 3.1                # format.                return self._legacy_decode(session_data)            except Exception:                logger = logging.getLogger('django.security.SuspiciousSession')                logger.warning('Session data corrupted')                return {}</ins>         except Exception:             return self._legacy_decode(session_data)


def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):         key = self.make_key(key, version=version)        self.validate_key(key)         with self._lock:             if self._has_expired(key):                 return Falsediff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py-- a/django/core/cache/backends/memcached.py++ b/django/core/cache/backends/memcached.py


def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):         key = self.make_key(key, version=version)<ins>        self.validate_key(key)</ins>         return bool(self._cache.touch(key, self.get_backend_timeout(timeout)))      def delete(self, key, version=None):


return [original_keys[k] for k in failed_keys]      def delete_many(self, keys, version=None):        self._cache.delete_multi(self.make_key(key, version=version) for key in keys)        keys = [self.make_key(key, version=version) for key in keys]        for key in keys:            self.validate_key(key)        self._cache.delete_multi(keys)      def clear(self):         self._cache.flush_all()


def get(self, key, default=None, version=None):         key = self.make_key(key, version=version)<ins>        self.validate_key(key)</ins>         val = self._cache.get(key)         # python-memcached doesn't support default values in get().         # https://github.com/linsomniac/python-memcached/issues/159


# https://github.com/linsomniac/python-memcached/issues/170         # Call _deletetouch() without the NOT_FOUND in expected results.         key = self.make_key(key, version=version)<ins>        self.validate_key(key)</ins>         return bool(self._cache._deletetouch([b'DELETED'], 'delete', key))


def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):         key = self.make_key(key, version=version)<ins>        self.validate_key(key)</ins>         if timeout == 0:             return self._cache.delete(key)         return self._cache.touch(key, self.get_backend_timeout(timeout))


import logging<del>import warnings</del> from functools import update_wrapper  from django.core.exceptions import ImproperlyConfigured


from django.template.response import TemplateResponse from django.urls import reverse from django.utils.decorators import classonlymethod<del>from django.utils.deprecation import RemovedInDjango40Warningfrom django.utils.functional import lazy</del>  logger = logging.getLogger('django.request')