if from_obj:                     final_field.remote_field.set_cached_value(from_obj, obj) <ins>            def local_setter_noop(obj, from_obj):                pass</ins>             def remote_setter(name, obj, from_obj):                 setattr(from_obj, name, obj)


"model": model,                         "field": final_field,                         "reverse": True,                        "local_setter": partial(local_setter, final_field),                        "local_setter": (                            partial(local_setter, final_field)                            if len(joins) <= 2                            else local_setter_noop                        ),                         "remote_setter": partial(remote_setter, name),                         "from_parent": from_parent,                     }


class ManifestFilesMixin(HashedFilesMixin):    manifest_version = "1.0"  # the manifest format standard    manifest_version = "1.1"  # the manifest format standard     manifest_name = "staticfiles.json"     manifest_strict = True     keep_intermediate_files = False


if manifest_storage is None:             manifest_storage = self         self.manifest_storage = manifest_storage        self.hashed_files = self.load_manifest()        self.hashed_files, self.manifest_hash = self.load_manifest()      def read_manifest(self):         try:


def load_manifest(self):         content = self.read_manifest()         if content is None:            return {}            return {}, ""         try:             stored = json.loads(content)         except json.JSONDecodeError:             pass         else:             version = stored.get("version")            if version == "1.0":                return stored.get("paths", {})            if version in ("1.0", "1.1"):                return stored.get("paths", {}), stored.get("hash", "")         raise ValueError(             "Couldn't load manifest '%s' (version %s)"             % (self.manifest_name, self.manifest_version)


self.save_manifest()      def save_manifest(self):        payload = {"paths": self.hashed_files, "version": self.manifest_version}        self.manifest_hash = self.file_hash(            None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode())        )        payload = {            "paths": self.hashed_files,            "version": self.manifest_version,            "hash": self.manifest_hash,        }         if self.manifest_storage.exists(self.manifest_name):             self.manifest_storage.delete(self.manifest_name)         contents = json.dumps(payload).encode()


d.hour,             d.minute,             d.second,<ins>            tzinfo=d.tzinfo,</ins>         )     else:         pivot = d


import os import sys from argparse import ArgumentParser, HelpFormatter<ins>from functools import partial</ins> from io import TextIOBase  import django


else:             raise CommandError("Error: %s" % message) <ins>    def add_subparsers(self, **kwargs):        parser_class = kwargs.get("parser_class", type(self))        if issubclass(parser_class, CommandParser):            kwargs["parser_class"] = partial(                parser_class,                called_from_command_line=self.called_from_command_line,            )        return super().add_subparsers(**kwargs)</ins>  def handle_default_options(options):     """


except (ValueError, OverflowError, InvalidOperation):         return input_val     if not m and p < 0:    if not m and p <= 0:         return mark_safe(             formats.number_format(                 "%d" % (int(d)),


class Exists(Subquery):     template = "EXISTS(%(subquery)s)"     output_field = fields.BooleanField()<ins>    empty_result_set_value = False</ins>      def __init__(self, queryset, **kwargs):         super().__init__(queryset, **kwargs)


if kwargs.get("max_length") == 100:             del kwargs["max_length"]         kwargs["upload_to"] = self.upload_to        if self.storage is not default_storage:            kwargs["storage"] = getattr(self, "_storage_callable", self.storage)        storage = getattr(self, "_storage_callable", self.storage)        if storage is not default_storage:            kwargs["storage"] = storage         return name, path, args, kwargs      def get_internal_type(self):


from django.core.exceptions import FieldError, ValidationError from django.db import connectionsfrom django.db.models.expressions import Exists, ExpressionList, Ffrom django.db.models.expressions import Exists, ExpressionList, F, OrderBy from django.db.models.indexes import IndexExpression from django.db.models.lookups import Exact from django.db.models.query_utils import Q


meta=model._meta, exclude=exclude                 ).items()             }            expressions = [                Exact(expr, expr.replace_expressions(replacements))                for expr in self.expressions            ]            expressions = []            for expr in self.expressions:                # Ignore ordering.                if isinstance(expr, OrderBy):                    expr = expr.expression                expressions.append(Exact(expr, expr.replace_expressions(replacements)))             queryset = queryset.filter(*expressions)         model_class_pk = instance._get_pk_val(model._meta)         if not instance._state.adding and model_class_pk is not None:


import socket import socketserver import sys<ins>from collections import deque</ins> from wsgiref import simple_server  from django.core.exceptions import ImproperlyConfigured


def cleanup_headers(self):         super().cleanup_headers()        if (            self.environ["REQUEST_METHOD"] == "HEAD"            and "Content-Length" in self.headers        ):            del self.headers["Content-Length"]         # HTTP/1.1 requires support for persistent connections. Send 'close' if         # the content length is unknown to prevent clients from reusing the         # connection.        if "Content-Length" not in self.headers:        if (            self.environ["REQUEST_METHOD"] != "HEAD"            and "Content-Length" not in self.headers        ):             self.headers["Connection"] = "close"         # Persistent connections require threading server.         elif not isinstance(self.request_handler.server, socketserver.ThreadingMixIn):


self.get_stdin().read()         super().close() <ins>    def finish_response(self):        if self.environ["REQUEST_METHOD"] == "HEAD":            try:                deque(self.result, maxlen=0)  # Consume iterator.                # Don't call self.finish_content() as, if the headers have not                # been sent and Content-Length isn't set, it'll default to "0"                # which will prevent omission of the Content-Length header with                # HEAD requests as permitted by RFC 9110 Section 9.3.2.                # Instead, send the headers, if not sent yet.                if not self.headers_sent:                    self.send_headers()            finally:                self.close()        else:            super().finish_response()</ins>  class WSGIRequestHandler(simple_server.WSGIRequestHandler):     protocol_version = "HTTP/1.1"


**kwargs,         )     def update_or_create(self, defaults=None, **kwargs):    def update_or_create(self, defaults=None, create_defaults=None, **kwargs):         """         Look up an object with the given kwargs, updating one with defaults        if it exists, otherwise create a new one.        if it exists, otherwise create a new one. Optionally, an object can        be created with different values than defaults by using        create_defaults.         Return a tuple (object, created), where created is a boolean         specifying whether an object was created.         """        defaults = defaults or {}        if create_defaults is None:            update_defaults = create_defaults = defaults or {}        else:            update_defaults = defaults or {}         self._for_write = True         with transaction.atomic(using=self.db):             # Lock the row so that a concurrent update is blocked until             # update_or_create() has performed its save.            obj, created = self.select_for_update().get_or_create(defaults, **kwargs)            obj, created = self.select_for_update().get_or_create(                create_defaults, **kwargs            )             if created:                 return obj, created            for k, v in resolve_callables(defaults):            for k, v in resolve_callables(update_defaults):                 setattr(obj, k, v)             update_fields = set(defaults)            update_fields = set(update_defaults)             concrete_field_names = self.model._meta._non_pk_concrete_field_names             # update_fields does not support non-concrete fields.             if concrete_field_names.issuperset(update_fields):


obj.save(using=self.db)         return obj, False     async def aupdate_or_create(self, defaults=None, **kwargs):    async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):         return await sync_to_async(self.update_or_create)(             defaults=defaults,            create_defaults=create_defaults,             **kwargs,         )


"available_apps": self.get_app_list(request),             "is_popup": False,             "is_nav_sidebar_enabled": self.enable_nav_sidebar,<ins>            "log_entries": self.get_log_entries(request),</ins>         }      def password_change(self, request, extra_context=None):


context,         )     def get_log_entries(self, request):        from django.contrib.admin.models import LogEntry        return LogEntry.objects.select_related("content_type", "user")  class DefaultAdminSite(LazyObject):     def _setup(self):diff --git a/django/contrib/admin/templatetags/log.py b/django/contrib/admin/templatetags/log.py-- a/django/contrib/admin/templatetags/log.py++ b/django/contrib/admin/templatetags/log.py


from django import template<del>from django.contrib.admin.models import LogEntry</del>  register = template.Library()


return "<GetAdminLog Node>"      def render(self, context):        if self.user is None:            entries = LogEntry.objects.all()        else:        entries = context["log_entries"]        if self.user is not None:             user_id = self.user             if not user_id.isdigit():                 user_id = context[self.user].pk            entries = LogEntry.objects.filter(user__pk=user_id)        context[self.varname] = entries.select_related("content_type", "user")[            : int(self.limit)        ]            entries = entries.filter(user__pk=user_id)        context[self.varname] = entries[: int(self.limit)]         return ""


def create_reference_role(rolename, urlbase):<ins>    # Views and template names are case-sensitive.    is_case_sensitive = rolename in ["template", "view"]</ins>     def _role(name, rawtext, text, lineno, inliner, options=None, content=None):         if options is None:             options = {}


urlbase                 % (                     inliner.document.settings.link_base,                    text.lower(),                    text if is_case_sensitive else text.lower(),                 )             ),             **options,


and context.get("show_delete", True)             ),             "show_save_as_new": not is_popup            and has_change_permission            and has_add_permission             and change             and save_as,             "show_save_and_add_another": can_save_and_add_another,


or not new_field.remote_field.through._meta.auto_created                 ):                     continue                # Rename the M2M table that's based on this model's name.                old_m2m_model = old_field.remote_field.through                new_m2m_model = new_field.remote_field.through                schema_editor.alter_db_table(                    new_m2m_model,                    old_m2m_model._meta.db_table,                    new_m2m_model._meta.db_table,                )                # Rename the column in the M2M table that's based on this                # model's name.                schema_editor.alter_field(                    new_m2m_model,                    old_m2m_model._meta.get_field(old_model._meta.model_name),                    new_m2m_model._meta.get_field(new_model._meta.model_name),                # Rename columns and the M2M table.                schema_editor._alter_many_to_many(                    new_model,                    old_field,                    new_field,                    strict=False,                 )      def database_backwards(self, app_label, schema_editor, from_state, to_state):


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


<ins>import warnings</ins> from enum import Enum from types import NoneType


from django.db.models.query_utils import Q from django.db.models.sql.query import Query from django.db.utils import DEFAULT_DB_ALIAS<ins>from django.utils.deprecation import RemovedInDjango60Warning</ins> from django.utils.translation import gettext_lazy as _  __all__ = ["BaseConstraint", "CheckConstraint", "Deferrable", "UniqueConstraint"]


default_violation_error_message = _("Constraint “%(name)s” is violated.")     violation_error_message = None     def __init__(self, name, violation_error_message=None):    # RemovedInDjango60Warning: When the deprecation ends, replace with:    # def __init__(self, *, name, violation_error_message=None):    def __init__(self, *args, name=None, violation_error_message=None):        # RemovedInDjango60Warning.        if name is None and not args:            raise TypeError(                f"{self.__class__.__name__}.__init__() missing 1 required keyword-only "                f"argument: 'name'"            )         self.name = name         if violation_error_message is not None:             self.violation_error_message = violation_error_message         else:             self.violation_error_message = self.default_violation_error_message        # RemovedInDjango60Warning.        if args:            warnings.warn(                f"Passing positional arguments to {self.__class__.__name__} is "                f"deprecated.",                RemovedInDjango60Warning,                stacklevel=2,            )            for arg, attr in zip(args, ["name", "violation_error_message"]):                if arg:                    setattr(self, attr, arg)      @property     def contains_expressions(self):


raise TypeError(                 "CheckConstraint.check must be a Q instance or boolean expression."             )        super().__init__(name, violation_error_message=violation_error_message)        super().__init__(name=name, violation_error_message=violation_error_message)      def _get_check_sql(self, model, schema_editor):         query = Query(model=model, alias_cols=False)


F(expression) if isinstance(expression, str) else expression             for expression in expressions         )        super().__init__(name, violation_error_message=violation_error_message)        super().__init__(name=name, violation_error_message=violation_error_message)      @property     def contains_expressions(self):


import re import types import warningsfrom decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperationfrom decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation, getcontext from functools import wraps from inspect import unwrap from operator import itemgetter


units = len(tupl[1])     units += -tupl[2] if m else tupl[2]     prec = abs(p) + units + 1<ins>    prec = max(getcontext().prec, prec)</ins>      # Avoid conversion to scientific notation by accessing `sign`, `digits`,     # and `exponent` from Decimal.as_tuple() directly.


return "alter_%s_%s" % (self.model_name_lower, self.name_lower)      def reduce(self, operation, app_label):        if isinstance(operation, RemoveField) and self.is_same_field_operation(            operation        ):        if isinstance(            operation, (AlterField, RemoveField)        ) and self.is_same_field_operation(operation):             return [operation]         elif (             isinstance(operation, RenameField)


def resolve_expression(self, *args, **kwargs):         col = super().resolve_expression(*args, **kwargs)        if col.contains_over_clause:            raise NotSupportedError(                f"Referencing outer query window expression is not supported: "                f"{self.name}."            )         # FIXME: Rename possibly_multivalued to multivalued and fix detection         # for non-multivalued JOINs (e.g. foreign key fields). This should take         # into account only many-to-many and one-to-many relationships.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


)             )         inner_query_compiler = inner_query.get_compiler(            self.using, elide_empty=self.elide_empty            self.using, connection=self.connection, elide_empty=self.elide_empty         )         inner_sql, inner_params = inner_query_compiler.as_sql(             # The limits must be applied to the outer query to avoid pruning


import itertools import math from django.core.exceptions import EmptyResultSetfrom django.core.exceptions import EmptyResultSet, FullResultSet from django.db.models.expressions import Case, Expression, Func, Value, When from django.db.models.fields import (     BooleanField,


lookup_name = "lte"  <ins>class IntegerFieldOverflow:    underflow_exception = EmptyResultSet    overflow_exception = EmptyResultSet    def process_rhs(self, compiler, connection):        rhs = self.rhs        if isinstance(rhs, int):            field_internal_type = self.lhs.output_field.get_internal_type()            min_value, max_value = connection.ops.integer_field_range(                field_internal_type            )            if min_value is not None and rhs < min_value:                raise self.underflow_exception            if max_value is not None and rhs > max_value:                raise self.overflow_exception        return super().process_rhs(compiler, connection)</ins> class IntegerFieldFloatRounding:     """     Allow floats to work as query values for IntegerField. Without this, the


@IntegerField.register_lookupclass IntegerGreaterThanOrEqual(IntegerFieldFloatRounding, GreaterThanOrEqual):class IntegerFieldExact(IntegerFieldOverflow, Exact):     pass   @IntegerField.register_lookupclass IntegerLessThan(IntegerFieldFloatRounding, LessThan):    passclass IntegerGreaterThan(IntegerFieldOverflow, GreaterThan):    underflow_exception = FullResultSet@IntegerField.register_lookupclass IntegerGreaterThanOrEqual(    IntegerFieldOverflow, IntegerFieldFloatRounding, GreaterThanOrEqual):    underflow_exception = FullResultSet@IntegerField.register_lookupclass IntegerLessThan(IntegerFieldOverflow, IntegerFieldFloatRounding, LessThan):    overflow_exception = FullResultSet@IntegerField.register_lookupclass IntegerLessThanOrEqual(IntegerFieldOverflow, LessThanOrEqual):    overflow_exception = FullResultSet   @Field.register_lookup


if (                         field.nulls_first is None and field.nulls_last is None                     ) or self.connection.features.supports_order_by_nulls_modifier:                        field = field.copy()                         field.expression = select_ref                     # Alias collisions are not possible when dealing with                     # combined queries so fallback to it if emulation of NULLS                     # handling is required.                     elif self.query.combinator:                        field = field.copy()                         field.expression = Ref(select_ref.refs, select_ref.source)                 yield field, select_ref is not None                 continue


<ins>import asyncio</ins> import logging import sys import tempfile


body_file.close()             await self.send_response(error_response, send)             return        # Get the response, using the async mode of BaseHandler.        # Try to catch a disconnect while getting response.        tasks = [            asyncio.create_task(self.run_get_response(request)),            asyncio.create_task(self.listen_for_disconnect(receive)),        ]        done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)        done, pending = done.pop(), pending.pop()        # Allow views to handle cancellation.        pending.cancel()        try:            await pending        except asyncio.CancelledError:            # Task re-raised the CancelledError as expected.            pass        try:            response = done.result()        except RequestAborted:            body_file.close()            return        except AssertionError:            body_file.close()            raise        # Send the response.        await self.send_response(response, send)    async def listen_for_disconnect(self, receive):        """Listen for disconnect from the client."""        message = await receive()        if message["type"] == "http.disconnect":            raise RequestAborted()        # This should never happen.        assert False, "Invalid ASGI message after request body: %s" % message["type"]    async def run_get_response(self, request):        """Get async response."""        # Use the async mode of BaseHandler.         response = await self.get_response_async(request)         response._handler_class = self.__class__         # Increase chunk size on file responses (ASGI servers handles low-level         # chunking).         if isinstance(response, FileResponse):             response.block_size = self.chunk_size        # Send the response.        await self.send_response(response, send)        return response      async def read_body(self, receive):         """Reads an HTTP body from an ASGI connection."""


pass             else:                 if getattr(match.func, "should_append_slash", True):                    return HttpResponsePermanentRedirect("%s/" % request.path)                    return HttpResponsePermanentRedirect(                        request.get_full_path(force_append_slash=True)                    )         raise Http404      def _build_app_dict(self, request, label=None):


import os import re import uuid<ins>import warnings</ins> from decimal import Decimal, DecimalException from io import BytesIO from urllib.parse import urlsplit, urlunsplit


) from django.utils import formats from django.utils.dateparse import parse_datetime, parse_duration<ins>from django.utils.deprecation import RemovedInDjango60Warning</ins> from django.utils.duration import duration_string from django.utils.ipv6 import clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile


}     default_validators = [validators.URLValidator()]     def __init__(self, **kwargs):    def __init__(self, *, assume_scheme=None, **kwargs):        if assume_scheme is None:            warnings.warn(                "The default scheme will be changed from 'http' to 'https' in Django "                "6.0. Pass the forms.URLField.assume_scheme argument to silence this "                "warning.",                RemovedInDjango60Warning,                stacklevel=2,            )            assume_scheme = "http"        # RemovedInDjango60Warning: When the deprecation ends, replace with:        # self.assume_scheme = assume_scheme or "https"        self.assume_scheme = assume_scheme         super().__init__(strip=True, **kwargs)      def to_python(self, value):


if value:             url_fields = split_url(value)             if not url_fields[0]:                # If no URL scheme given, assume http://                url_fields[0] = "http"                # If no URL scheme given, add a scheme.                url_fields[0] = self.assume_scheme             if not url_fields[1]:                 # Assume that if no domain is provided, that the path segment                 # contains the domain.


from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP<ins>from django.db.models.enums import ChoicesMeta</ins> from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper


self.unique_for_date = unique_for_date         self.unique_for_month = unique_for_month         self.unique_for_year = unique_for_year        if isinstance(choices, ChoicesMeta):            choices = choices.choices         if isinstance(choices, collections.abc.Iterator):             choices = list(choices)         self.choices = choicesdiff --git a/django/forms/fields.py b/django/forms/fields.py-- a/django/forms/fields.py++ b/django/forms/fields.py


from django.core import validators from django.core.exceptions import ValidationError<ins>from django.db.models.enums import ChoicesMeta</ins> from django.forms.boundfield import BoundField from django.forms.utils import from_current_timezone, to_current_timezone from django.forms.widgets import (


def __init__(self, *, choices=(), **kwargs):         super().__init__(**kwargs)<ins>        if isinstance(choices, ChoicesMeta):            choices = choices.choices</ins>         self.choices = choices      def __deepcopy__(self, memo):


# Verify the session             if hasattr(user, "get_session_auth_hash"):                 session_hash = request.session.get(HASH_SESSION_KEY)                session_hash_verified = session_hash and constant_time_compare(                    session_hash, user.get_session_auth_hash()                )                if not session_hash:                    session_hash_verified = False                else:                    session_auth_hash = user.get_session_auth_hash()                    session_hash_verified = constant_time_compare(                        session_hash, session_auth_hash                    )                 if not session_hash_verified:                    request.session.flush()                    user = None                    # If the current secret does not verify the session, try                    # with the fallback secrets and stop when a matching one is                    # found.                    if session_hash and any(                        constant_time_compare(session_hash, fallback_auth_hash)                        for fallback_auth_hash in user.get_session_auth_fallback_hash()                    ):                        request.session.cycle_key()                        request.session[HASH_SESSION_KEY] = session_auth_hash                    else:                        request.session.flush()                        user = None      return user or AnonymousUser() diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py-- a/django/contrib/auth/base_user.py++ b/django/contrib/auth/base_user.py


import unicodedata import warnings <ins>from django.conf import settings</ins> from django.contrib.auth import password_validation from django.contrib.auth.hashers import (     check_password,


"""         Return an HMAC of the password field.         """        return self._get_session_auth_hash()    def get_session_auth_fallback_hash(self):        for fallback_secret in settings.SECRET_KEY_FALLBACKS:            yield self._get_session_auth_hash(secret=fallback_secret)    def _get_session_auth_hash(self, secret=None):         key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"         return salted_hmac(             key_salt,             self.password,            secret=secret,             algorithm="sha256",         ).hexdigest()


def generate_added_indexes(self):         for (app_label, model_name), alt_indexes in self.altered_indexes.items():<ins>            dependencies = self._get_dependencies_for_model(app_label, model_name)</ins>             for index in alt_indexes["added_indexes"]:                 self.add_operation(                     app_label,


model_name=model_name,                         index=index,                     ),<ins>                    dependencies=dependencies,</ins>                 )      def generate_removed_indexes(self):


app_label,             model_name,         ), alt_constraints in self.altered_constraints.items():<ins>            dependencies = self._get_dependencies_for_model(app_label, model_name)</ins>             for constraint in alt_constraints["added_constraints"]:                 self.add_operation(                     app_label,


model_name=model_name,                         constraint=constraint,                     ),<ins>                    dependencies=dependencies,</ins>                 )      def generate_removed_constraints(self):


dependencies.append((through_app_label, through_object_name, None, True))         return dependencies <ins>    def _get_dependencies_for_model(self, app_label, model_name):        """Return foreign key dependencies of the given model."""        dependencies = []        model_state = self.to_state.models[app_label, model_name]        for field in model_state.fields.values():            if field.is_relation:                dependencies.extend(                    self._get_dependencies_for_foreign_key(                        app_label,                        model_name,                        field,                        self.to_state,                    )                )        return dependencies</ins>     def _get_altered_foo_together_operations(self, option_name):         for app_label, model_name in sorted(self.kept_model_keys):             old_model_name = self.renamed_models.get(


# Encoding isn't set to prevent browsers from automatically                 # uncompressing files.                 content_type = {                    "br": "application/x-brotli",                     "bzip2": "application/x-bzip",                    "compress": "application/x-compress",                     "gzip": "application/gzip",                     "xz": "application/x-xz",                 }.get(encoding, content_type)


if select:             self.append_annotation_mask([alias])         else:            self.set_annotation_mask(set(self.annotation_select).difference({alias}))            annotation_mask = (                value                for value in dict.fromkeys(self.annotation_select)                if value != alias            )            self.set_annotation_mask(annotation_mask)         self.annotations[alias] = annotation      def resolve_expression(self, query, *args, **kwargs):


if names is None:             self.annotation_select_mask = None         else:            self.annotation_select_mask = set(names)            self.annotation_select_mask = list(dict.fromkeys(names))         self._annotation_select_cache = None      def append_annotation_mask(self, names):         if self.annotation_select_mask is not None:            self.set_annotation_mask(self.annotation_select_mask.union(names))            self.set_annotation_mask((*self.annotation_select_mask, *names))      def set_extra_mask(self, names):         """


return {}         elif self.annotation_select_mask is not None:             self._annotation_select_cache = {                k: v                for k, v in self.annotations.items()                if k in self.annotation_select_mask                k: self.annotations[k]                for k in self.annotation_select_mask                if k in self.annotations             }             return self._annotation_select_cache         else:


"update.tests.AdvancedTests."                 "test_update_ordered_by_inline_m2m_annotation",                 "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation",                "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation_desc",             },         }         if self.connection.mysql_is_mariadb and (diff --git a/django/db/models/query.py b/django/db/models/query.py-- a/django/db/models/query.py++ b/django/db/models/query.py


# Inline annotations in order_by(), if possible.         new_order_by = []         for col in query.order_by:            if annotation := query.annotations.get(col):            alias = col            descending = False            if isinstance(alias, str) and alias.startswith("-"):                alias = alias.removeprefix("-")                descending = True            if annotation := query.annotations.get(alias):                 if getattr(annotation, "contains_aggregate", False):                     raise exceptions.FieldError(                         f"Cannot update when ordering by an aggregate: {annotation}"                     )                if descending:                    annotation = annotation.desc()                 new_order_by.append(annotation)             else:                 new_order_by.append(col)


# Lookups on nonexistent fields are ok, since they're ignored                 # later.                 break            # It is allowed to filter on values that would be found from local            # model anyways. For example, if you filter on employee__department__id,            # then the id value would be found already from employee__department_id.             if not prev_field or (                 prev_field.is_relation                and field not in prev_field.path_infos[-1].target_fields                and field not in model._meta.parents.values()                and field is not model._meta.auto_field                and (                    model._meta.auto_field is None                    or part not in getattr(prev_field, "to_fields", [])                )             ):                 relation_parts.append(part)             if not getattr(field, "path_infos", None):


# Sort imports by the package / module to be imported (the part after         # "from" in "from ... import ..." or after "import" in "import ...").        sorted_imports = sorted(imports, key=lambda i: i.split()[1])        # First group the "import" statements, then "from ... import ...".        sorted_imports = sorted(            imports, key=lambda i: (i.split()[0] == "from", i.split()[1])        )         items["imports"] = "\n".join(sorted_imports) + "\n" if imports else ""         if migration_imports:             items["imports"] += (


# Return pseudo-ISO dates with zeros for any unselected values,                 # e.g. '2017-0-23'.                 return "%s-%s-%s" % (y or 0, m or 0, d or 0)<ins>            except OverflowError:                return "0-0-0"</ins>             return date_value.strftime(input_format)         return data.get(name)


async def get_response_async(self, request):         response = await super().get_response_async(request)         response._resource_closers.append(request.close)<ins>        # FileResponse is not async compatible.        if response.streaming and not response.is_async:            _iterator = response.streaming_content            async def awrapper():                for part in await sync_to_async(list)(_iterator):                    yield part            response.streaming_content = awrapper()</ins>         return response


# For lookups spanning over relationships, show the error                 # from the model on which the lookup failed.                 raise<del>            elif name in self.annotations:                raise FieldError(                    "Cannot select the '%s' alias. Use annotate() to promote "                    "it." % name                )</del>             else:                 names = sorted(                     [


extra_names.append(f)                     elif f in self.annotation_select:                         annotation_names.append(f)                    elif f in self.annotations:                        raise FieldError(                            f"Cannot select the '{f}' alias. Use annotate() to "                            "promote it."                        )                     else:                        # Call `names_to_path` to ensure a FieldError including                        # annotations about to be masked as valid choices if                        # `f` is not resolvable.                        if self.annotation_select:                            self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)                         field_names.append(f)             self.set_extra_mask(extra_names)             self.set_annotation_mask(annotation_names)


processors = template.engine.template_context_processors + self._processors         updates = {}         for processor in processors:            updates.update(processor(self.request))            context = processor(self.request)            try:                updates.update(context)            except TypeError as e:                raise TypeError(                    f"Context processor {processor.__qualname__} didn't return a "                    "dictionary."                ) from e         self.dicts[self._processors_index] = updates          try:


raise ValueError(                     "Cannot call lazy() with both bytes and text return types."                 )            if cls._delegate_text:                cls.__str__ = cls.__text_cast            elif cls._delegate_bytes:            if cls._delegate_bytes:                 cls.__bytes__ = cls.__bytes_cast          @classmethod


return __wrapper__         def __text_cast(self):            return func(*self.__args, **self.__kw)         def __bytes_cast(self):             return bytes(func(*self.__args, **self.__kw))         def __bytes_cast_encoded(self):            return func(*self.__args, **self.__kw).encode()         def __cast(self):             if self._delegate_bytes:                 return self.__bytes_cast()            elif self._delegate_text:                return self.__text_cast()             else:                 return func(*self.__args, **self.__kw)


from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import _lazy_re_compile, normalizefrom django.utils.translation import get_languagefrom django.utils.translation import get_language, get_supported_language_variant  from .converters import get_converter from .exceptions import NoReverseMatch, Resolver404


@property     def language_prefix(self):         language_code = get_language() or settings.LANGUAGE_CODE        if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:        default_language = get_supported_language_variant(settings.LANGUAGE_CODE)        if language_code == default_language and not self.prefix_default_language:             return ""         else:             return "%s/" % language_codediff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py-- a/django/utils/translation/__init__.py++ b/django/utils/translation/__init__.py


"get_language_from_request",     "get_language_info",     "get_language_bidi",<ins>    "get_supported_language_variant",</ins>     "check_for_language",     "to_language",     "to_locale",


message = _("Ensure this value is a multiple of step size %(limit_value)s.")     code = "step_size"     def __init__(self, limit_value, message=None, offset=None):        super().__init__(limit_value, message)        if offset is not None:            self.message = _(                "Ensure this value is a multiple of step size %(limit_value)s, "                "starting from %(offset)s, e.g. %(offset)s, %(valid_value1)s, "                "%(valid_value2)s, and so on."            )        self.offset = offset    def __call__(self, value):        if self.offset is None:            super().__call__(value)        else:            cleaned = self.clean(value)            limit_value = (                self.limit_value() if callable(self.limit_value) else self.limit_value            )            if self.compare(cleaned, limit_value):                offset = cleaned.__class__(self.offset)                params = {                    "limit_value": limit_value,                    "offset": offset,                    "valid_value1": offset + limit_value,                    "valid_value2": offset + 2 * limit_value,                }                raise ValidationError(self.message, code=self.code, params=params)     def compare(self, a, b):        return not math.isclose(math.remainder(a, b), 0, abs_tol=1e-9)        offset = 0 if self.offset is None else self.offset        return not math.isclose(math.remainder(a - offset, b), 0, abs_tol=1e-9)   @deconstructiblediff --git a/django/forms/fields.py b/django/forms/fields.py-- a/django/forms/fields.py++ b/django/forms/fields.py


if min_value is not None:             self.validators.append(validators.MinValueValidator(min_value))         if step_size is not None:            self.validators.append(validators.StepValueValidator(step_size))            self.validators.append(                validators.StepValueValidator(step_size, offset=min_value)            )      def to_python(self, value):         """


# Translators: String used to replace omitted page numbers in elided page     # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10].     ELLIPSIS = _("…")    def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True):    default_error_messages = {        "invalid_page": _("That page number is not an integer"),        "min_page": _("That page number is less than 1"),        "no_results": _("That page contains no results"),    }    def __init__(        self,        object_list,        per_page,        orphans=0,        allow_empty_first_page=True,        error_messages=None,    ):         self.object_list = object_list         self._check_object_list_is_ordered()         self.per_page = int(per_page)         self.orphans = int(orphans)         self.allow_empty_first_page = allow_empty_first_page        self.error_messages = (            self.default_error_messages            if error_messages is None            else self.default_error_messages | error_messages        )      def __iter__(self):         for page_number in self.page_range:


raise ValueError             number = int(number)         except (TypeError, ValueError):            raise PageNotAnInteger(_("That page number is not an integer"))            raise PageNotAnInteger(self.error_messages["invalid_page"])         if number < 1:            raise EmptyPage(_("That page number is less than 1"))            raise EmptyPage(self.error_messages["min_page"])         if number > self.num_pages:            raise EmptyPage(_("That page contains no results"))            raise EmptyPage(self.error_messages["no_results"])         return number      def get_page(self, number):


logger = logging.getLogger("django.request")  <ins>def get_script_prefix(scope):    """    Return the script prefix to use from either the scope or a setting.    """    if settings.FORCE_SCRIPT_NAME:        return settings.FORCE_SCRIPT_NAME    return scope.get("root_path", "") or ""</ins> class ASGIRequest(HttpRequest):     """     Custom request subclass that decodes from an ASGI-standard request dict


self._post_parse_error = False         self._read_started = False         self.resolver_match = None        self.script_name = self.scope.get("root_path", "")        self.script_name = get_script_prefix(scope)         if self.script_name:             # TODO: Better is-prefix checking, slash handling?             self.path_info = scope["path"].removeprefix(self.script_name)


except RequestAborted:             return         # Request is complete and can be served.        set_script_prefix(self.get_script_prefix(scope))        set_script_prefix(get_script_prefix(scope))         await signals.request_started.asend(sender=self.__class__, scope=scope)         # Get the request and check for basic issues.         request, error_response = self.create_request(scope, body_file)


(position + cls.chunk_size) >= len(data),             )             position += cls.chunk_size<del>    def get_script_prefix(self, scope):        """        Return the script prefix to use from either the scope or a setting.        """        if settings.FORCE_SCRIPT_NAME:            return settings.FORCE_SCRIPT_NAME        return scope.get("root_path", "") or ""</del>


class Chr(Transform):     function = "CHR"     lookup_name = "chr"<ins>    output_field = CharField()</ins>      def as_mysql(self, compiler, connection, **extra_context):         return super().as_sql(


id="admin.E108",                     )                 ]        if isinstance(field, models.ManyToManyField):        if isinstance(field, models.ManyToManyField) or (            getattr(field, "rel", None) and field.rel.field.many_to_one        ):             return [                 checks.Error(                    "The value of '%s' must not be a ManyToManyField." % label,                    f"The value of '{label}' must not be a many-to-many field or a "                    f"reverse foreign key.",                     obj=obj.__class__,                     id="admin.E109",                 )


else self.get_list_display(request)         )     def lookup_allowed(self, lookup, value):    # RemovedInDjango60Warning: when the deprecation ends, replace with:    # def lookup_allowed(self, lookup, value, request):    def lookup_allowed(self, lookup, value, request=None):         from django.contrib.admin.filters import SimpleListFilter          model = self.model


# Either a local field filter, or no fields at all.             return True         valid_lookups = {self.date_hierarchy}        for filter_item in self.list_filter:        # RemovedInDjango60Warning: when the deprecation ends, replace with:        # for filter_item in self.get_list_filter(request):        list_filter = (            self.get_list_filter(request) if request is not None else self.list_filter        )        for filter_item in list_filter:             if isinstance(filter_item, type) and issubclass(                 filter_item, SimpleListFilter             ):diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py-- a/django/contrib/admin/views/main.py++ b/django/contrib/admin/views/main.py


<ins>import warnings</ins> from datetime import datetime, timedelta  from django import forms


from django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterRef from django.db.models.expressions import Combinable from django.urls import reversefrom django.utils.deprecation import RemovedInDjango60Warning from django.utils.http import urlencodefrom django.utils.inspect import func_supports_parameter from django.utils.timezone import make_aware from django.utils.translation import gettext


may_have_duplicates = False         has_active_filters = False         supports_request = func_supports_parameter(            self.model_admin.lookup_allowed, "request"        )        if not supports_request:            warnings.warn(                f"`request` must be added to the signature of "                f"{self.model_admin.__class__.__qualname__}.lookup_allowed().",                RemovedInDjango60Warning,            )         for key, value_list in lookup_params.items():             for value in value_list:                if not self.model_admin.lookup_allowed(key, value):                params = (key, value, request) if supports_request else (key, value)                if not self.model_admin.lookup_allowed(*params):                     raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed")          filter_specs = []diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py-- a/django/contrib/auth/admin.py++ b/django/contrib/auth/admin.py


),         ] + super().get_urls()     def lookup_allowed(self, lookup, value):    # RemovedInDjango60Warning: when the deprecation ends, replace with:    # def lookup_allowed(self, lookup, value, request):    def lookup_allowed(self, lookup, value, request=None):         # Don't allow lookups involving passwords.         return not lookup.startswith("password") and super().lookup_allowed(            lookup, value            lookup, value, request         )      @sensitive_post_parameters_m


# after their corresponding image field don't stay cleared by         # Model.__init__, see bug #11196.         # Only run post-initialization dimension update on non-abstract models        if not cls._meta.abstract:        # with width_field/height_field.        if not cls._meta.abstract and (self.width_field or self.height_field):             signals.post_init.connect(self.update_dimension_fields, sender=cls)      def update_dimension_fields(self, instance, force=False, *args, **kwargs):


Dimensions can be forced to update with force=True, which is how         ImageFileDescriptor.__set__ calls this method.         """        # Nothing to update if the field doesn't have dimension fields or if        # the field is deferred.        has_dimension_fields = self.width_field or self.height_field        if not has_dimension_fields or self.attname not in instance.__dict__:        # Nothing to update if the field is deferred.        if self.attname not in instance.__dict__:             return          # getattr will call the ImageFileDescriptor's __get__ method, which


@register.filter(is_safe=True) def random(value):     """Return a random item from the list."""    return random_module.choice(value)    try:        return random_module.choice(value)    except IndexError:        return ""   @register.filter("slice", is_safe=True)


response_redirect_class = HttpResponseRedirect     def get_fallback_language(self, request):        """        Return the fallback language for the current request based on the        settings. If LANGUAGE_CODE is a variant not included in the supported        languages, get_fallback_language() will try to fallback to a supported        generic variant.        Can be overridden to have a fallback language depending on the request,        e.g. based on top level domain.        """        try:            return translation.get_supported_language_variant(settings.LANGUAGE_CODE)        except LookupError:            return settings.LANGUAGE_CODE     def process_request(self, request):         urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)        i18n_patterns_used, _ = is_language_prefix_patterns_used(urlconf)        (            i18n_patterns_used,            prefixed_default_language,        ) = is_language_prefix_patterns_used(urlconf)         language = translation.get_language_from_request(             request, check_path=i18n_patterns_used         )        if not language:            language = self.get_fallback_language(request)        language_from_path = translation.get_language_from_path(request.path_info)        if (            not language_from_path            and i18n_patterns_used            and not prefixed_default_language        ):            language = settings.LANGUAGE_CODE         translation.activate(language)         request.LANGUAGE_CODE = translation.get_language()      def process_response(self, request, response):         language = translation.get_language()         language_from_path = translation.get_language_from_path(request.path_info)        language_from_request = translation.get_language_from_request(request)         urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)         (             i18n_patterns_used,


response.status_code == 404             and not language_from_path             and i18n_patterns_used            and (prefixed_default_language or language_from_request)            and prefixed_default_language         ):             # Maybe the language code is missing in the URL? Try adding the             # language prefix and redirecting to that URL.diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py-- a/django/urls/resolvers.py++ b/django/urls/resolvers.py


from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import _lazy_re_compile, normalizefrom django.utils.translation import get_language, get_supported_language_variantfrom django.utils.translation import get_language  from .converters import get_converter from .exceptions import NoReverseMatch, Resolver404


@property     def language_prefix(self):         language_code = get_language() or settings.LANGUAGE_CODE        default_language = get_supported_language_variant(settings.LANGUAGE_CODE)        if language_code == default_language and not self.prefix_default_language:        if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:             return ""         else:             return "%s/" % language_codediff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py-- a/django/utils/translation/__init__.py++ b/django/utils/translation/__init__.py


"get_language_from_request",     "get_language_info",     "get_language_bidi",    "get_supported_language_variant",     "check_for_language",     "to_language",     "to_locale",diff --git a/django/utils/translation/trans_null.py b/django/utils/translation/trans_null.py-- a/django/utils/translation/trans_null.py++ b/django/utils/translation/trans_null.py


def get_language_from_request(request, check_path=False):    return None    return settings.LANGUAGE_CODE   def get_language_from_path(request):diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py-- a/django/utils/translation/trans_real.py++ b/django/utils/translation/trans_real.py


return get_supported_language_variant(accept_lang)         except LookupError:             continue    return None    try:        return get_supported_language_variant(settings.LANGUAGE_CODE)    except LookupError:        return settings.LANGUAGE_CODE   @functools.lru_cache(maxsize=1000)


id="admin.E108",                     )                 ]        if isinstance(field, models.ManyToManyField) or (            getattr(field, "rel", None) and field.rel.field.many_to_one        ):        if (            getattr(field, "is_relation", False)            and (field.many_to_many or field.one_to_many)        ) or (getattr(field, "rel", None) and field.rel.field.many_to_one):             return [                 checks.Error(                     f"The value of '{label}' must not be a many-to-many field or a "


def migration_name_fragment(self):         return "%s_%s" % (self.model_name_lower, self.index.name.lower()) <ins>    def reduce(self, operation, app_label):        if isinstance(operation, RemoveIndex) and self.index.name == operation.name:            return []        return super().reduce(operation, app_label)</ins>  class RemoveIndex(IndexOperation):     """Remove an index from a model."""


managers=self.managers,                     ),                 ]<ins>        elif (            isinstance(operation, IndexOperation)            and self.name_lower == operation.model_name_lower        ):            if isinstance(operation, AddIndex):                return [                    CreateModel(                        self.name,                        fields=self.fields,                        options={                            **self.options,                            "indexes": [                                *self.options.get("indexes", []),                                operation.index,                            ],                        },                        bases=self.bases,                        managers=self.managers,                    ),                ]            elif isinstance(operation, RemoveIndex):                options_indexes = [                    index                    for index in self.options.get("indexes", [])                    if index.name != operation.name                ]                return [                    CreateModel(                        self.name,                        fields=self.fields,                        options={                            **self.options,                            "indexes": options_indexes,                        },                        bases=self.bases,                        managers=self.managers,                    ),                ]            elif isinstance(operation, RenameIndex) and operation.old_fields:                options_index_together = {                    fields                    for fields in self.options.get("index_together", [])                    if fields != operation.old_fields                }                if options_index_together:                    self.options["index_together"] = options_index_together                else:                    self.options.pop("index_together", None)                return [                    CreateModel(                        self.name,                        fields=self.fields,                        options={                            **self.options,                            "indexes": [                                *self.options.get("indexes", []),                                models.Index(                                    fields=operation.old_fields, name=operation.new_name                                ),                            ],                        },                        bases=self.bases,                        managers=self.managers,                    ),                ]</ins>         return super().reduce(operation, app_label)


raise CommandError(                 '"%s" returned non-zero exit status %s.'                 % (                    " ".join(e.cmd),                    " ".join(map(str, e.cmd)),                     e.returncode,                 ),                 returncode=e.returncode,


asave.alters_data = True <ins>    @classmethod    def _validate_force_insert(cls, force_insert):        if force_insert is False:            return ()        if force_insert is True:            return (cls,)        if not isinstance(force_insert, tuple):            raise TypeError("force_insert must be a bool or tuple.")        for member in force_insert:            if not isinstance(member, ModelBase):                raise TypeError(                    f"Invalid force_insert member. {member!r} must be a model subclass."                )            if not issubclass(cls, member):                raise TypeError(                    f"Invalid force_insert member. {member.__qualname__} must be a "                    f"base of {cls.__qualname__}."                )        return force_insert</ins>     def save_base(         self,         raw=False,


with context_manager:             parent_inserted = False             if not raw:                parent_inserted = self._save_parents(cls, using, update_fields)                # Validate force insert only when parents are inserted.                force_insert = self._validate_force_insert(force_insert)                parent_inserted = self._save_parents(                    cls, using, update_fields, force_insert                )             updated = self._save_table(                 raw,                 cls,


save_base.alters_data = True     def _save_parents(self, cls, using, update_fields, updated_parents=None):    def _save_parents(        self, cls, using, update_fields, force_insert, updated_parents=None    ):         """Save all the parents of cls using values from self."""         meta = cls._meta         inserted = False


cls=parent,                     using=using,                     update_fields=update_fields,                    force_insert=force_insert,                     updated_parents=updated_parents,                 )                 updated = self._save_table(                     cls=parent,                     using=using,                     update_fields=update_fields,                    force_insert=parent_inserted,                    force_insert=parent_inserted or issubclass(parent, force_insert),                 )                 if not updated:                     inserted = True


return "JSONField"      def get_db_prep_value(self, value, connection, prepared=False):<ins>        if not prepared:            value = self.get_prep_value(value)</ins>         # RemovedInDjango51Warning: When the deprecation ends, replace with:         # if (         #     isinstance(value, expressions.Value)


)             # Update name.             previous_migration_path = MigrationWriter(leaf_migration).path            suggested_name = (                leaf_migration.name[:4] + "_" + leaf_migration.suggest_name()            )            name_fragment = self.migration_name or leaf_migration.suggest_name()            suggested_name = leaf_migration.name[:4] + f"_{name_fragment}"             if leaf_migration.name == suggested_name:                 new_name = leaf_migration.name + "_updated"             else:


"""Join a list with a string, like Python's ``str.join(list)``."""     try:         if autoescape:            value = [conditional_escape(v) for v in value]        data = conditional_escape(arg).join(value)            data = conditional_escape(arg).join([conditional_escape(v) for v in value])        else:            data = arg.join(value)     except TypeError:  # Fail silently if arg isn't iterable.         return value     return mark_safe(data)


return conditional_escape(value)  <ins>@register.filter(is_safe=True)def escapeseq(value):    """    An "escape" filter for sequences. Mark each element in the sequence,    individually, as a string that should be auto-escaped. Return a list with    the results.    """    return [conditional_escape(obj) for obj in value]</ins> @register.filter(is_safe=True) @stringfilter def force_escape(value):


c.filter = c.filter and c.filter.resolve_expression(             query, allow_joins, reuse, summarize         )        if not summarize:        if summarize:            # Summarized aggregates cannot refer to summarized aggregates.            for ref in c.get_refs():                if query.annotations[ref].is_summary:                    raise FieldError(                        f"Cannot compute {c.name}('{ref}'): '{ref}' is an aggregate"                    )        elif not self.is_summary:             # Call Aggregate.get_source_expressions() to avoid             # returning self.filter and including that in this loop.             expressions = super(Aggregate, c).get_source_expressions()diff --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


template = "(%(subquery)s)"     contains_aggregate = False     empty_result_set_value = None    subquery = True      def __init__(self, queryset, output_field=None, **extra):         # Allow the usage of both QuerySet and sql.Query objects.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


"""         if not aggregate_exprs:             return {}        aggregates = {}        # Store annotation mask prior to temporarily adding aggregations for        # resolving purpose to facilitate their subsequent removal.        refs_subquery = False        replacements = {}        annotation_select_mask = self.annotation_select_mask         for alias, aggregate_expr in aggregate_exprs.items():             self.check_alias(alias)             aggregate = aggregate_expr.resolve_expression(


)             if not aggregate.contains_aggregate:                 raise TypeError("%s is not an aggregate expression" % alias)            aggregates[alias] = aggregate            # Temporarily add aggregate to annotations to allow remaining            # members of `aggregates` to resolve against each others.            self.append_annotation_mask([alias])            refs_subquery |= any(                getattr(self.annotations[ref], "subquery", False)                for ref in aggregate.get_refs()            )            aggregate = aggregate.replace_expressions(replacements)            self.annotations[alias] = aggregate            replacements[Ref(alias, aggregate)] = aggregate        # Stash resolved aggregates now that they have been allowed to resolve        # against each other.        aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}        self.set_annotation_mask(annotation_select_mask)         # Existing usage of aggregation can be determined by the presence of         # selected aggregates but also by filters against aliased aggregates.         _, having, qualify = self.where.split_having_qualify()


isinstance(self.group_by, tuple)             or self.is_sliced             or has_existing_aggregation<ins>            or refs_subquery</ins>             or qualify             or self.distinct             or self.combinator


# 'table_name_filter' is a stealth option         table_name_filter = options.get("table_name_filter") <del>        def table2model(table_name):            return re.sub(r"[^a-zA-Z0-9]", "", table_name.title())</del>         with connection.cursor() as cursor:             yield "# This is an auto-generated Django model module."             yield "# You'll have to do the following manually to clean this up:"


yield "# The error was: %s" % e                     continue                 model_name = table2model(table_name)                model_name = self.normalize_table_name(table_name)                 yield ""                 yield ""                 yield "class %s(models.Model):" % model_name


rel_to = (                             "self"                             if ref_db_table == table_name                            else table2model(ref_db_table)                            else self.normalize_table_name(ref_db_table)                         )                         if rel_to in known_models:                             field_type = "%s(%s" % (rel_type, rel_to)


return new_name, field_params, field_notes <ins>    def normalize_table_name(self, table_name):        """Translate the table name to a Python-compatible model name."""        return re.sub(r"[^a-zA-Z0-9]", "", table_name.title())</ins>     def get_field_type(self, connection, table_name, row):         """         Given the database connection, the table name, and the cursor row


)         return decimal_value     def get_db_prep_value(self, value, connection, prepared=False):        if not prepared:            value = self.get_prep_value(value)    def get_db_prep_save(self, value, connection):         if hasattr(value, "as_sql"):             return value         return connection.ops.adapt_decimalfield_value(            value, self.max_digits, self.decimal_places            self.to_python(value), self.max_digits, self.decimal_places         )      def get_prep_value(self, value):


except FieldDoesNotExist:                 return [                     checks.Error(                        "The value of '%s' is not a callable, an attribute of "                        "'%s', or an attribute of '%s'."                        "The value of '%s' refers to '%s', which is not a callable, "                        "an attribute of '%s', or an attribute of '%s'."                         % (                             label,                            field_name,                             obj.__class__.__name__,                             obj.model._meta.label,                         ),


from django.core.exceptions import EmptyResultSet, FullResultSet from django.db.models.expressions import Case, When<ins>from django.db.models.functions import Mod</ins> from django.db.models.lookups import Exact from django.utils import tree from django.utils.functional import cached_property


# Convert if the database doesn't support XOR:             #   a XOR b XOR c XOR ...             # to:            #   (a OR b OR c OR ...) AND (a + b + c + ...) == 1            #   (a OR b OR c OR ...) AND MOD(a + b + c + ..., 2) == 1            # The result of an n-ary XOR is true when an odd number of operands            # are true.             lhs = self.__class__(self.children, OR)             rhs_sum = reduce(                 operator.add,                 (Case(When(c, then=1), default=0) for c in self.children),             )            if len(self.children) > 2:                rhs_sum = Mod(rhs_sum, 2)             rhs = Exact(1, rhs_sum)             return self.__class__([lhs, rhs], AND, self.negated).as_sql(                 compiler, connection


def get_substr(self):         return Substr(            self.source_expressions[0], self.source_expressions[1] * Value(-1)            self.source_expressions[0],            self.source_expressions[1] * Value(-1),            self.source_expressions[1],         )


save_base.alters_data = True     def _save_parents(self, cls, using, update_fields):    def _save_parents(self, cls, using, update_fields, updated_parents=None):         """Save all the parents of cls using values from self."""         meta = cls._meta         inserted = False        if updated_parents is None:            updated_parents = {}         for parent, field in meta.parents.items():             # Make sure the link fields are synced between parent and self.             if (


and getattr(self, field.attname) is not None             ):                 setattr(self, parent._meta.pk.attname, getattr(self, field.attname))            parent_inserted = self._save_parents(                cls=parent, using=using, update_fields=update_fields            )            updated = self._save_table(                cls=parent,                using=using,                update_fields=update_fields,                force_insert=parent_inserted,            )            if not updated:            if (parent_updated := updated_parents.get(parent)) is None:                parent_inserted = self._save_parents(                    cls=parent,                    using=using,                    update_fields=update_fields,                    updated_parents=updated_parents,                )                updated = self._save_table(                    cls=parent,                    using=using,                    update_fields=update_fields,                    force_insert=parent_inserted,                )                if not updated:                    inserted = True                updated_parents[parent] = updated            elif not parent_updated:                 inserted = True             # Set the parent's PK value to self.             if field:


# Only include fields mentioned in the mask.         for field_name, field_mask in mask.items():             field = opts.get_field(field_name)            field_select_mask = select_mask.setdefault(field, {})            # Retrieve the actual field associated with reverse relationships            # as that's what is expected in the select mask.            if field in opts.related_objects:                field_key = field.field            else:                field_key = field            field_select_mask = select_mask.setdefault(field_key, {})             if field_mask:                 if not field.is_relation:                     raise FieldError(next(iter(field_mask)))


attrs["required"] = True         if self.field.disabled:             attrs["disabled"] = True<ins>        # If a custom aria-describedby attribute is given and help_text is        # used, the custom aria-described by is preserved so user can set the        # desired order.        if custom_aria_described_by_id := widget.attrs.get("aria-describedby"):            attrs["aria-describedby"] = custom_aria_described_by_id        elif self.field.help_text and self.id_for_label:            attrs["aria-describedby"] = f"{self.id_for_label}_helptext"</ins>         return attrs      @property


return self._value_from_field(value, value._meta.pk)                  def queryset_iterator(obj, field):                    return getattr(obj, field.name).only("pk").iterator()                    return (                        getattr(obj, field.name).select_related().only("pk").iterator()                    )              m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get(                 field.name,diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py-- a/django/core/serializers/xml_serializer.py++ b/django/core/serializers/xml_serializer.py


self.xml.addQuickElement("object", attrs={"pk": str(value.pk)})                  def queryset_iterator(obj, field):                    return getattr(obj, field.name).only("pk").iterator()                    return (                        getattr(obj, field.name).select_related().only("pk").iterator()                    )              m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get(                 field.name,


import html import json import reimport warnings from html.parser import HTMLParser from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from django.utils.deprecation import RemovedInDjango60Warning from django.utils.encoding import punycode from django.utils.functional import Promise, keep_lazy, keep_lazy_text from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS


and call mark_safe() on the result. This function should be used instead     of str.format or % interpolation to build up small HTML fragments.     """<ins>    if not (args or kwargs):        # RemovedInDjango60Warning: when the deprecation ends, replace with:        # raise ValueError("args or kwargs must be provided.")        warnings.warn(            "Calling format_html() without passing args or kwargs is deprecated.",            RemovedInDjango60Warning,        )</ins>     args_safe = map(conditional_escape, args)     kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}     return mark_safe(format_string.format(*args_safe, **kwargs_safe))


to_field = self.instance._meta.get_field(kwargs["to_field"])             else:                 to_field = self.instance._meta.pk            if to_field.has_default():            if to_field.has_default() and (                # Don't ignore a parent's auto-generated key if it's not the                # parent model's pk and form data is provided.                to_field.attname == self.fk.remote_field.model._meta.pk.name                or not form.data            ):                 setattr(self.instance, to_field.attname, None)          form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)


if f not in used_fields:                     used_fields[f.name] = f         # Check that parent links in diamond-shaped MTI models don't clash.        for parent_link in cls._meta.parents.values():            if not parent_link:                continue            clash = used_fields.get(parent_link.name) or None            if clash:                errors.append(                    checks.Error(                        f"The field '{parent_link.name}' clashes with the field "                        f"'{clash.name}' from model '{clash.model._meta}'.",                        obj=cls,                        id="models.E006",                    )                )         for f in cls._meta.local_fields:             clash = used_fields.get(f.name) or used_fields.get(f.attname) or None             # Note that we may detect clash between user-defined non-uniquediff --git a/django/db/models/options.py b/django/db/models/options.py-- a/django/db/models/options.py++ b/django/db/models/options.py


reverse=True,         include_parents=True,         include_hidden=False,        seen_models=None,        topmost_call=True,     ):         """         Internal helper function to return fields of the model.


# implementation and to provide a fast way for Django's internals to         # access specific subsets of fields. <del>        # We must keep track of which models we have already seen. Otherwise we        # could include the same field multiple times from different models.        topmost_call = seen_models is None        if topmost_call:            seen_models = set()        seen_models.add(self.model)</del>         # Creates a cache key composed of all arguments         cache_key = (forward, reverse, include_parents, include_hidden, topmost_call)


# Recursively call _get_fields() on each parent, with the same         # options provided in this call.         if include_parents is not False:            # In diamond inheritance it is possible that we see the same model            # from two different routes. In that case, avoid adding fields from            # the same parent again.            parent_fields = set()             for parent in self.parents:                # In diamond inheritance it is possible that we see the same                # model from two different routes. In that case, avoid adding                # fields from the same parent again.                if parent in seen_models:                    continue                 if (                     parent._meta.concrete_model != self.concrete_model                     and include_parents == PROXY_PARENTS


reverse=reverse,                     include_parents=include_parents,                     include_hidden=include_hidden,                    seen_models=seen_models,                    topmost_call=False,                 ):                     if (                         not getattr(obj, "parent_link", False)                         or obj.model == self.concrete_model                    ):                    ) and obj not in parent_fields:                         fields.append(obj)                        parent_fields.add(obj)         if reverse and not self.proxy:             # Tree is computed once and cached until the app cache is expired.             # It is composed of a list of fields pointing to the current model


return must_be(                     "a many-to-many field", option=label, obj=obj, id="admin.E020"                 )<ins>            elif not field.remote_field.through._meta.auto_created:                return [                    checks.Error(                        f"The value of '{label}' cannot include the ManyToManyField "                        f"'{field_name}', because that field manually specifies a "                        f"relationship model.",                        obj=obj.__class__,                        id="admin.E013",                    )                ]</ins>             else:                 return []


This is mostly used in tests.         """<ins>        self.get_swappable_settings_name.cache_clear()</ins>         # Call expire cache on each model. This will purge         # the relation tree and the fields cache.         self.get_models.cache_clear()


return None      def check(self):        warnings = self._check_pattern_startswith_slash()        warnings = [            *self._check_pattern_startswith_slash(),            *self._check_pattern_unmatched_angle_brackets(),        ]         route = self._route         if "(?P<" in route or route.startswith("^") or route.endswith("$"):             warnings.append(


)         return warnings <ins>    def _check_pattern_unmatched_angle_brackets(self):        warnings = []        segments = self._route.split("/")        for segment in segments:            open_bracket_counter = 0            unmatched_angle_bracket = None            for char in segment:                if char == "<":                    open_bracket_counter += 1                elif char == ">":                    open_bracket_counter -= 1                    if open_bracket_counter < 0:                        unmatched_angle_bracket = ">"                        break            else:                if open_bracket_counter > 0:                    unmatched_angle_bracket = "<"            if unmatched_angle_bracket is not None:                warnings.append(                    Warning(                        "Your URL pattern %s has an unmatched '%s' bracket."                        % (self.describe(), unmatched_angle_bracket),                        id="urls.W010",                    )                )        return warnings</ins>     def _compile(self, route):         return re.compile(_route_to_regex(route, self._is_endpoint)[0])


SuspiciousOperation, ) from django.core.paginator import InvalidPagefrom django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterReffrom django.db.models import F, Field, ManyToOneRel, OrderBy from django.db.models.expressions import Combinable from django.urls import reverse from django.utils.deprecation import RemovedInDjango60Warning


# ValueError, ValidationError, or ?.             raise IncorrectLookupParameters(e) <ins>        if not qs.query.select_related:            qs = self.apply_select_related(qs)        # Set ordering.        ordering = self.get_ordering(request, qs)        qs = qs.order_by(*ordering)</ins>         # Apply search results         qs, search_may_have_duplicates = self.model_admin.get_search_results(             request,


)         # Remove duplicates from results, if necessary         if filters_may_have_duplicates | search_may_have_duplicates:            qs = qs.filter(pk=OuterRef("pk"))            qs = self.root_queryset.filter(Exists(qs))        # Set ordering.        ordering = self.get_ordering(request, qs)        qs = qs.order_by(*ordering)        if not qs.query.select_related:            qs = self.apply_select_related(qs)        return qs            return qs.distinct()        else:            return qs      def apply_select_related(self, qs):         if self.list_select_related is True:diff --git a/django/db/models/query.py b/django/db/models/query.py-- a/django/db/models/query.py++ b/django/db/models/query.py


self._not_support_combined_queries("delete")         if self.query.is_sliced:             raise TypeError("Cannot use 'limit' or 'offset' with delete().")        if self.query.distinct or self.query.distinct_fields:            raise TypeError("Cannot call delete() after .distinct().")        if self.query.distinct_fields:            raise TypeError("Cannot call delete() after .distinct(*fields).")         if self._fields is not None:             raise TypeError("Cannot call delete() after .values() or .values_list()")


inserted_rows = []         bulk_return = connection.features.can_return_rows_from_bulk_insert         for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]:            if bulk_return and on_conflict is None:            if bulk_return and (                on_conflict is None or on_conflict == OnConflict.UPDATE            ):                 inserted_rows.extend(                     self._insert(                         item,                         fields=fields,                         using=self.db,                        on_conflict=on_conflict,                        update_fields=update_fields,                        unique_fields=unique_fields,                         returning_fields=self.model._meta.db_returning_fields,                     )                 )


attrs["required"] = True         if self.field.disabled:             attrs["disabled"] = True        # If a custom aria-describedby attribute is given and help_text is        # used, the custom aria-described by is preserved so user can set the        # desired order.        if custom_aria_described_by_id := widget.attrs.get("aria-describedby"):            attrs["aria-describedby"] = custom_aria_described_by_id        elif self.field.help_text and self.id_for_label:        # If a custom aria-describedby attribute is given (either via the attrs        # argument or widget.attrs) and help_text is used, the custom        # aria-described by is preserved so user can set the desired order.        if (            not attrs.get("aria-describedby")            and not widget.attrs.get("aria-describedby")            and self.field.help_text            and self.id_for_label        ):             attrs["aria-describedby"] = f"{self.id_for_label}_helptext"         return attrs


return value % (", ".join(strings)), imports  <ins>class BaseUnorderedSequenceSerializer(BaseSequenceSerializer):    def __init__(self, value):        super().__init__(sorted(value, key=repr))</ins> class BaseSimpleSerializer(BaseSerializer):     def serialize(self):         return repr(self.value), set()


return super().serialize()  class FrozensetSerializer(BaseSequenceSerializer):class FrozensetSerializer(BaseUnorderedSequenceSerializer):     def _format(self):         return "frozenset([%s])"


return "[%s]"  class SetSerializer(BaseSequenceSerializer):class SetSerializer(BaseUnorderedSequenceSerializer):     def _format(self):         # Serialize as a set literal except when value is empty because {}         # is an empty dict.diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py-- a/django/db/migrations/writer.py++ b/django/db/migrations/writer.py


imports.add("from django.conf import settings")             else:                 dependencies.append("        %s," % self.serialize(dependency)[0])        items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else ""        items["dependencies"] = (            "\n".join(sorted(dependencies)) + "\n" if dependencies else ""        )          # Format imports nicely, swapping imports of functions from migration files         # for comments


# Store annotation mask prior to temporarily adding aggregations for         # resolving purpose to facilitate their subsequent removal.         refs_subquery = False<ins>        refs_window = False</ins>         replacements = {}         annotation_select_mask = self.annotation_select_mask         for alias, aggregate_expr in aggregate_exprs.items():


getattr(self.annotations[ref], "subquery", False)                 for ref in aggregate.get_refs()             )<ins>            refs_window |= any(                getattr(self.annotations[ref], "contains_over_clause", True)                for ref in aggregate.get_refs()            )</ins>             aggregate = aggregate.replace_expressions(replacements)             self.annotations[alias] = aggregate             replacements[Ref(alias, aggregate)] = aggregate


or self.is_sliced             or has_existing_aggregation             or refs_subquery<ins>            or refs_window</ins>             or qualify             or self.distinct             or self.combinator


):             klass = self.value.__self__             module = klass.__module__            return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {            return "%s.%s.%s" % (module, klass.__qualname__, self.value.__name__), {                 "import %s" % module             }         # Further error checking


try:             app_name = commands[subcommand]         except KeyError:            # This might trigger ImproperlyConfigured (masked in get_commands)            settings.INSTALLED_APPS            if os.environ.get('DJANGO_SETTINGS_MODULE'):                # If `subcommand` is missing due to misconfigured settings, the                # following line will retrigger an ImproperlyConfigured exception                # (get_commands() swallows the original one) so the user is                # informed about it.                settings.INSTALLED_APPS            else:                sys.stderr.write("No Django settings specified.\n")             sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %                 (subcommand, self.prog_name))             sys.exit(1)


<ins>from __future__ import unicode_literals</ins> from django.utils.version import get_version  VERSION = (1, 10, 0, 'alpha', 0)


__version__ = get_version(VERSION)  def setup():def setup(set_prefix=True):     """     Configure the settings (this happens as a side effect of accessing the     first setting), configure logging and populate the app registry.    Set the thread-local urlresolvers script prefix if `set_prefix` is True.     """     from django.apps import apps     from django.conf import settings    from django.core.urlresolvers import set_script_prefix    from django.utils.encoding import force_text     from django.utils.log import configure_logging      configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)    if set_prefix:        set_script_prefix(            '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME)        )     apps.populate(settings.INSTALLED_APPS)diff --git a/django/core/wsgi.py b/django/core/wsgi.py-- a/django/core/wsgi.py++ b/django/core/wsgi.py


Allows us to avoid making django.core.handlers.WSGIHandler public API, in     case the internal WSGI implementation changes or moves in the future.     """    django.setup()    django.setup(set_prefix=False)     return WSGIHandler()


from .management import create_permissions  class AuthConfig(AppConfig):class BaseAuthConfig(AppConfig):    """    AppConfig which assumes that the auth models don't exist.    """     name = 'django.contrib.auth'     verbose_name = _("Authentication and Authorization")      def ready(self):        checks.register(check_user_model, checks.Tags.models)class AuthConfig(BaseAuthConfig):    """    The default AppConfig for auth.    """    def ready(self):        super(AuthConfig, self).ready()         post_migrate.connect(             create_permissions,             dispatch_uid="django.contrib.auth.management.create_permissions"         )        checks.register(check_user_model, checks.Tags.models)         checks.register(check_models_permissions, checks.Tags.models)


'--all', action='store_true', dest='all', default=False,             help='Display all settings, regardless of their value. Default values are prefixed by "###".',         )        parser.add_argument(            '--default', dest='default', metavar='MODULE', default=None,            help=(                "The settings module to compare the current settings against. Leave empty to "                "compare against Django's default settings."            ),        )      def handle(self, **options):         # Inspired by Postfix's "postconf -n".        from django.conf import settings, global_settings        from django.conf import settings, Settings, global_settings          # Because settings are imported lazily, we need to explicitly load them.         settings._setup()          user_settings = module_to_dict(settings._wrapped)        default_settings = module_to_dict(global_settings)        default = options['default']        default_settings = module_to_dict(Settings(default) if default else global_settings)          output = []         for key in sorted(user_settings):


# At least one model must be migrated to the database.                     router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name)                     for app_label in consistency_check_labels                    for model in apps.get_models(app_label)                    for model in apps.get_app_config(app_label).get_models()             )):                 loader.check_consistent_history(connection)


"""         pass     def conditional_expression_supported_in_where_clause(self, expression):        """        Return True, if the conditional expression is supported in the WHERE        clause.        """        return True     def combine_expression(self, connector, sub_expressions):         """         Combine a list of subexpressions into a single expression, usingdiff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py-- a/django/db/backends/oracle/operations.py++ b/django/db/backends/oracle/operations.py


from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import strip_quotes, truncate_name<ins>from django.db.models.expressions import Exists, ExpressionWrapperfrom django.db.models.query_utils import Q</ins> from django.db.utils import DatabaseError from django.utils import timezone from django.utils.encoding import force_bytes, force_str


if fields:             return self.connection.features.max_query_params // len(fields)         return len(objs)    def conditional_expression_supported_in_where_clause(self, expression):        """        Oracle supports only EXISTS(...) or filters in the WHERE clause, others        must be compared with True.        """        if isinstance(expression, Exists):            return True        if isinstance(expression, ExpressionWrapper) and isinstance(expression.expression, Q):            return True        return Falsediff --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


return self._combine(other, self.POW, False)      def __and__(self, other):<ins>        if getattr(self, 'conditional', False) and getattr(other, 'conditional', False):            return Q(self) & Q(other)</ins>         raise NotImplementedError(             "Use .bitand() and .bitor() for bitwise logical operations."         )


return self._combine(other, self.BITRIGHTSHIFT, False)      def __or__(self, other):<ins>        if getattr(self, 'conditional', False) and getattr(other, 'conditional', False):            return Q(self) | Q(other)</ins>         raise NotImplementedError(             "Use .bitand() and .bitor() for bitwise logical operations."         )


])         return c <ins>    @property    def conditional(self):        return isinstance(self.output_field, fields.BooleanField)</ins>     @property     def field(self):         return self.output_field


class When(Expression):     template = 'WHEN %(condition)s THEN %(result)s'    # This isn't a complete conditional expression, must be used in Case().    conditional = False      def __init__(self, condition=None, then=None, **lookups):         if lookups and condition is None:             condition, lookups = Q(**lookups), None         if condition is None or not getattr(condition, 'conditional', False) or lookups:            raise TypeError("__init__() takes either a Q object or lookups as keyword arguments")            raise TypeError(                'When() supports a Q object, a boolean expression, or lookups '                'as a condition.'            )         if isinstance(condition, Q) and not condition:             raise ValueError("An empty Q() can't be used as a When() condition.")         super().__init__(output_field=None)


class OrderBy(BaseExpression):     template = '%(expression)s %(ordering)s'    conditional = False      def __init__(self, expression, descending=False, nulls_first=False, nulls_last=False):         if nulls_first and nulls_last: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


"""         if isinstance(filter_expr, dict):             raise FieldError("Cannot parse keyword query as dict")<ins>        if hasattr(filter_expr, 'resolve_expression') and getattr(filter_expr, 'conditional', False):            if connections[DEFAULT_DB_ALIAS].ops.conditional_expression_supported_in_where_clause(filter_expr):                condition = filter_expr.resolve_expression(self)            else:                # Expression is not supported in the WHERE clause, add                # comparison with True.                condition = self.build_lookup(['exact'], filter_expr.resolve_expression(self), True)            clause = self.where_class()            clause.add(condition, AND)            return clause, []</ins>         arg, value = filter_expr         if not arg:             raise FieldError("Cannot parse keyword query %r" % arg)


class Command(BaseCommand):     help = """Displays differences between the current settings.py and Django's    default settings. Settings that don't appear in the defaults are    followed by "###"."""    default settings."""      requires_system_checks = False      def add_arguments(self, parser):         parser.add_argument(             '--all', action='store_true', dest='all',            help='Display all settings, regardless of their value. Default values are prefixed by "###".',            help=(                'Display all settings, regardless of their value. In "hash" '                'mode, default values are prefixed by "###".'            ),         )         parser.add_argument(             '--default', dest='default', metavar='MODULE', default=None,


"compare against Django's default settings."             ),         )        parser.add_argument(            '--output', default='hash', choices=('hash', 'unified'), dest='output',            help=(                "Selects the output format. 'hash' mode displays each changed "                "setting, with the settings that don't appear in the defaults "                "followed by ###. 'unified' mode prefixes the default setting "                "with a minus sign, followed by the changed setting prefixed "                "with a plus sign."            ),        )      def handle(self, **options):        # Inspired by Postfix's "postconf -n".         from django.conf import settings, Settings, global_settings          # Because settings are imported lazily, we need to explicitly load them.


user_settings = module_to_dict(settings._wrapped)         default = options['default']         default_settings = module_to_dict(Settings(default) if default else global_settings)        output_func = {            'hash': self.output_hash,            'unified': self.output_unified,        }[options['output']]        return '\n'.join(output_func(user_settings, default_settings, **options))     def output_hash(self, user_settings, default_settings, **options):        # Inspired by Postfix's "postconf -n".         output = []         for key in sorted(user_settings):             if key not in default_settings:


output.append("%s = %s" % (key, user_settings[key]))             elif options['all']:                 output.append("### %s = %s" % (key, user_settings[key]))        return '\n'.join(output)        return output    def output_unified(self, user_settings, default_settings, **options):        output = []        for key in sorted(user_settings):            if key not in default_settings:                output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))            elif user_settings[key] != default_settings[key]:                output.append(self.style.ERROR("- %s = %s" % (key, default_settings[key])))                output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))            elif options['all']:                output.append("  %s = %s" % (key, user_settings[key]))        return output


"""     form_class = AuthenticationForm     authentication_form = None<ins>    next_page = None</ins>     redirect_field_name = REDIRECT_FIELD_NAME     template_name = 'registration/login.html'     redirect_authenticated_user = False