<ins>import sysfrom django.apps import appsfrom django.core.management.base import BaseCommand, CommandErrorfrom django.core.management.utils import run_formattersfrom django.db import migrationsfrom django.db.migrations.exceptions import AmbiguityErrorfrom django.db.migrations.loader import MigrationLoaderfrom django.db.migrations.optimizer import MigrationOptimizerfrom django.db.migrations.writer import MigrationWriterfrom django.utils.version import get_docs_versionclass Command(BaseCommand):    help = "Optimizes the operations for the named migration."    def add_arguments(self, parser):        parser.add_argument(            "app_label",            help="App label of the application to optimize the migration for.",        )        parser.add_argument(            "migration_name", help="Migration name to optimize the operations for."        )        parser.add_argument(            "--check",            action="store_true",            help="Exit with a non-zero status if the migration can be optimized.",        )    def handle(self, *args, **options):        verbosity = options["verbosity"]        app_label = options["app_label"]        migration_name = options["migration_name"]        check = options["check"]        # Validate app_label.        try:            apps.get_app_config(app_label)        except LookupError as err:            raise CommandError(str(err))        # Load the current graph state.        loader = MigrationLoader(None)        if app_label not in loader.migrated_apps:            raise CommandError(f"App '{app_label}' does not have migrations.")        # Find a migration.        try:            migration = loader.get_migration_by_prefix(app_label, migration_name)        except AmbiguityError:            raise CommandError(                f"More than one migration matches '{migration_name}' in app "                f"'{app_label}'. Please be more specific."            )        except KeyError:            raise CommandError(                f"Cannot find a migration matching '{migration_name}' from app "                f"'{app_label}'."            )        # Optimize the migration.        optimizer = MigrationOptimizer()        new_operations = optimizer.optimize(migration.operations, migration.app_label)        if len(migration.operations) == len(new_operations):            if verbosity > 0:                self.stdout.write("No optimizations possible.")            return        else:            if verbosity > 0:                self.stdout.write(                    "Optimizing from %d operations to %d operations."                    % (len(migration.operations), len(new_operations))                )            if check:                sys.exit(1)        # Set the new migration optimizations.        migration.operations = new_operations        # Write out the optimized migration file.        writer = MigrationWriter(migration)        migration_file_string = writer.as_string()        if writer.needs_manual_porting:            if migration.replaces:                raise CommandError(                    "Migration will require manual porting but is already a squashed "                    "migration.\nTransition to a normal migration first: "                    "https://docs.djangoproject.com/en/%s/topics/migrations/"                    "#squashing-migrations" % get_docs_version()                )            # Make a new migration with those operations.            subclass = type(                "Migration",                (migrations.Migration,),                {                    "dependencies": migration.dependencies,                    "operations": new_operations,                    "replaces": [(migration.app_label, migration.name)],                },            )            optimized_migration_name = "%s_optimized" % migration.name            optimized_migration = subclass(optimized_migration_name, app_label)            writer = MigrationWriter(optimized_migration)            migration_file_string = writer.as_string()            if verbosity > 0:                self.stdout.write(                    self.style.MIGRATE_HEADING("Manual porting required") + "\n"                    "  Your migrations contained functions that must be manually "                    "copied over,\n"                    "  as we could not safely copy their implementation.\n"                    "  See the comment at the top of the optimized migration for "                    "details."                )        with open(writer.path, "w", encoding="utf-8") as fh:            fh.write(migration_file_string)        run_formatters([writer.path])        if verbosity > 0:            self.stdout.write(                self.style.MIGRATE_HEADING(f"Optimized migration {writer.path}")            )</ins>


def __init__(self, *args, db_collation=None, **kwargs):         super().__init__(*args, **kwargs)         self.db_collation = db_collation        self.validators.append(validators.MaxLengthValidator(self.max_length))        if self.max_length is not None:            self.validators.append(validators.MaxLengthValidator(self.max_length))      def check(self, **kwargs):         databases = kwargs.get('databases') or []


def add_field(self, model, field):         """Create a field on a model."""        # Fields with default values cannot by handled by ALTER TABLE ADD        # COLUMN statement because DROP DEFAULT is not supported in        # ALTER TABLE.        if not field.null or self.effective_default(field) is not None:        if (            # Primary keys and unique fields are not supported in ALTER TABLE            # ADD COLUMN.            field.primary_key or field.unique or            # Fields with default values cannot by handled by ALTER TABLE ADD            # COLUMN statement because DROP DEFAULT is not supported in            # ALTER TABLE.            not field.null or self.effective_default(field) is not None        ):             self._remake_table(model, create_field=field)         else:             super().add_field(model, field)


# Since we just bypassed this class' get_queryset(), we must manage             # the reverse relation manually.             for rel_obj in queryset:                instance = instances_dict[rel_obj_attr(rel_obj)]                setattr(rel_obj, self.field.name, instance)                if not self.field.is_cached(rel_obj):                    instance = instances_dict[rel_obj_attr(rel_obj)]                    setattr(rel_obj, self.field.name, instance)             cache_name = self.field.remote_field.get_cache_name()             return queryset, rel_obj_attr, instance_attr, False, cache_name, False


obj = resolver_match.func          if hasattr(obj, 'view_class'):            caller = obj.view_class        elif hasattr(obj, '__name__'):            obj = obj.view_class        if hasattr(obj, '__name__'):             caller = obj.__name__         elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):             caller = obj.__class__.__name__


self.namespaces = [x for x in namespaces if x] if namespaces else []         self.namespace = ':'.join(self.namespaces) <ins>        if hasattr(func, 'view_class'):            func = func.view_class</ins>         if not hasattr(func, '__name__'):             # A class-based view             self._func_path = func.__class__.__module__ + '.' + func.__class__.__name__


return NotImplemented      def __hash__(self):        return hash((            self.creation_counter,            self.model._meta.app_label if hasattr(self, 'model') else None,            self.model._meta.model_name if hasattr(self, 'model') else None,        ))        return hash(self.creation_counter)      def __deepcopy__(self, memodict):         # We don't have to deepcopy very much here, since most things are not


for name, urlbase in ROLES.items():         create_reference_role(name, urlbase) # Match the beginning of a named or unnamed group.# Match the beginning of a named, unnamed, or non-capturing groups. named_group_matcher = _lazy_re_compile(r'\(\?P(<\w+>)') unnamed_group_matcher = _lazy_re_compile(r'\(')non_capturing_group_matcher = _lazy_re_compile(r'\(\?\:')   def replace_metacharacters(pattern):


final_pattern += pattern[:start] + '<var>'         prev_end = end     return final_pattern + pattern[prev_end:]def remove_non_capturing_groups(pattern):    r"""    Find non-capturing groups in the given `pattern` and remove them, e.g.    1. (?P\w+)/b/(?:\w+)c(?:\w+) => (?P\\w+)/b/c    2. ^(?:\w+(?:\w+))a => ^a    3. ^a(?:\w+)/b(?:\w+) => ^a/b    """    group_start_end_indices = _find_groups(pattern, non_capturing_group_matcher)    final_pattern, prev_end = '', None    for start, end, _ in group_start_end_indices:        final_pattern += pattern[prev_end:start]        prev_end = end    return final_pattern + pattern[prev_end:]diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py-- a/django/contrib/admindocs/views.py++ b/django/contrib/admindocs/views.py


from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admindocs import utils from django.contrib.admindocs.utils import (    replace_metacharacters, replace_named_groups, replace_unnamed_groups,    remove_non_capturing_groups, replace_metacharacters, replace_named_groups,    replace_unnamed_groups, ) from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.db import models


example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"     into "/<sport_slug>/athletes/<athlete_slug>/".     """<ins>    pattern = remove_non_capturing_groups(pattern)</ins>     pattern = replace_named_groups(pattern)     pattern = replace_unnamed_groups(pattern)     pattern = replace_metacharacters(pattern)


self.core_filters = {self.field.name: instance} <ins>            # Even if this relation is not to pk, we require still pk value.            # The wish is that the instance has been already saved to DB,            # although having a pk value isn't a guarantee of that.            if self.instance.pk is None:                raise ValueError(                    f"{instance.__class__.__name__!r} instance needs to have a primary "                    f"key value before this relationship can be used."                )</ins>         def __call__(self, *, manager):             manager = getattr(self.model, manager)             manager_class = create_reverse_many_to_one_manager(manager.__class__, rel)


do_not_call_in_templates = True <ins>        def _check_fk_val(self):            for field in self.field.foreign_related_fields:                if getattr(self.instance, field.attname) is None:                    raise ValueError(                        f'"{self.instance!r}" needs to have a value for field '                        f'"{field.attname}" before this relationship can be used.'                    )</ins>         def _apply_rel_filters(self, queryset):             """             Filter the queryset for the instance this manager is bound to.


return queryset, rel_obj_attr, instance_attr, False, cache_name, False          def add(self, *objs, bulk=True):<ins>            self._check_fk_val()</ins>             self._remove_prefetched_objects()             db = router.db_for_write(self.model, instance=self.instance)


add.alters_data = True          def create(self, **kwargs):<ins>            self._check_fk_val()</ins>             kwargs[self.field.name] = self.instance             db = router.db_for_write(self.model, instance=self.instance)             return super(RelatedManager, self.db_manager(db)).create(**kwargs)


create.alters_data = True          def get_or_create(self, **kwargs):<ins>            self._check_fk_val()</ins>             kwargs[self.field.name] = self.instance             db = router.db_for_write(self.model, instance=self.instance)             return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs)


get_or_create.alters_data = True          def update_or_create(self, **kwargs):<ins>            self._check_fk_val()</ins>             kwargs[self.field.name] = self.instance             db = router.db_for_write(self.model, instance=self.instance)             return super(RelatedManager, self.db_manager(db)).update_or_create(**kwargs)


def remove(self, *objs, bulk=True):                 if not objs:                     return<ins>                self._check_fk_val()</ins>                 val = self.field.get_foreign_related_value(self.instance)                 old_ids = set()                 for obj in objs:


remove.alters_data = True              def clear(self, *, bulk=True):<ins>                self._check_fk_val()</ins>                 self._clear(self, bulk)              clear.alters_data = True


_clear.alters_data = True          def set(self, objs, *, bulk=True, clear=False):<ins>            self._check_fk_val()</ins>             # Force evaluation of `objs` in case it's a queryset whose value             # could be affected by `manager.clear()`. Refs #19816.             objs = tuple(objs)


def __init__(self, queryset, output_field=None, **extra):         # Allow the usage of both QuerySet and sql.Query objects.        self.query = getattr(queryset, 'query', queryset)        self.query = getattr(queryset, 'query', queryset).clone()        self.query.subquery = True         self.extra = extra         super().__init__(output_field)


file_name = html.unescape(file_name)         file_name = file_name.rsplit('/')[-1]         file_name = file_name.rsplit('\\')[-1]<ins>        # Remove non-printable characters.        file_name = ''.join([char for char in file_name if char.isprintable()])</ins>          if file_name in {'', '.', '..'}:             return None


import copy import operator import warningsfrom itertools import chainfrom itertools import chain, islice  import django from django.conf import settings


from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE from django.db.models.utils import create_namedtuple_class, resolve_callables from django.utils import timezone<ins>from django.utils.deprecation import RemovedInDjango50Warning</ins> from django.utils.functional import cached_property, partition  # The maximum number of results to fetch in a get() query.


####################################      def _iterator(self, use_chunked_fetch, chunk_size):        yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size)        iterable = self._iterable_class(            self,            chunked_fetch=use_chunked_fetch,            chunk_size=chunk_size or 2000,        )        if not self._prefetch_related_lookups or chunk_size is None:            yield from iterable            return        iterator = iter(iterable)        while results := list(islice(iterator, chunk_size)):            prefetch_related_objects(results, *self._prefetch_related_lookups)            yield from results     def iterator(self, chunk_size=2000):    def iterator(self, chunk_size=None):         """         An iterator over the results from applying this QuerySet to the        database.        """        if chunk_size <= 0:        database. chunk_size must be provided for QuerySets that prefetch        related objects. Otherwise, a default chunk_size of 2000 is supplied.        """        if chunk_size is None:            if self._prefetch_related_lookups:                # When the deprecation ends, replace with:                # raise ValueError(                #     'chunk_size must be provided when using '                #     'QuerySet.iterator() after prefetch_related().'                # )                warnings.warn(                    'Using QuerySet.iterator() after prefetch_related() '                    'without specifying chunk_size is deprecated.',                    category=RemovedInDjango50Warning,                    stacklevel=2,                )        elif chunk_size <= 0:             raise ValueError('Chunk size must be strictly positive.')         use_chunked_fetch = not connections[self.db].settings_dict.get('DISABLE_SERVER_SIDE_CURSORS')         return self._iterator(use_chunked_fetch, chunk_size)


return self.name.lower()      def get_field(self, field_name):        field_name = (            self.options['order_with_respect_to']            if field_name == '_order'            else field_name        )        if field_name == '_order':            field_name = self.options.get('order_with_respect_to', field_name)         return self.fields[field_name]      @classmethod


# Using 0/1 here instead of False/True to produce more compact json             is_safedata = 1 if isinstance(obj.message, SafeData) else 0             message = [self.message_key, is_safedata, obj.level, obj.message]            if obj.extra_tags:            if obj.extra_tags is not None:                 message.append(obj.extra_tags)             return message         return super().default(obj)


cleansed_substitute = "********************"     hidden_settings = _lazy_re_compile(        "API|TOKEN|KEY|SECRET|PASS|SIGNATURE", flags=re.I        "API|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flags=re.I     )      def cleanse_setting(self, key, value):


Cleanse an individual setting key/value of sensitive content. If the         value is a dictionary, recursively cleanse the keys in that dictionary.         """        try:            is_sensitive = self.hidden_settings.search(key)        except TypeError:            is_sensitive = False        if key == settings.SESSION_COOKIE_NAME:            is_sensitive = True        else:            try:                is_sensitive = self.hidden_settings.search(key)            except TypeError:                is_sensitive = False          if is_sensitive:             cleansed = self.cleansed_substitute


return {}         return {k: self.cleanse_setting(k, v) for k, v in request.META.items()} <ins>    def get_safe_cookies(self, request):        """        Return a dictionary of request.COOKIES with sensitive values redacted.        """        if not hasattr(request, "COOKIES"):            return {}        return {k: self.cleanse_setting(k, v) for k, v in request.COOKIES.items()}</ins>     def is_active(self, request):         """         This filter is to add safety in production environments (i.e. DEBUG


"frames": frames,             "request": self.request,             "request_meta": self.filter.get_safe_request_meta(self.request),<ins>            "request_COOKIES_items": self.filter.get_safe_cookies(self.request).items(),</ins>             "user_str": user_str,             "filtered_POST_items": list(                 self.filter.get_post_parameters(self.request).items()


if self.request is not None:             c["request_GET_items"] = self.request.GET.items()             c["request_FILES_items"] = self.request.FILES.items()<del>            c["request_COOKIES_items"] = self.request.COOKIES.items()</del>             c["request_insecure_uri"] = self._get_raw_insecure_uri()             c["raising_view_name"] = get_caller(self.request)


from django.db.models import AutoField, DateField, DateTimeField, sql from django.db.models.constants import LOOKUP_SEP, OnConflict from django.db.models.deletion import Collectorfrom django.db.models.expressions import Case, Expression, F, Ref, Value, Whenfrom django.db.models.expressions import Case, F, Ref, Value, When from django.db.models.functions import Cast, Trunc from django.db.models.query_utils import FilteredRelation, Q from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE


when_statements = []                 for obj in batch_objs:                     attr = getattr(obj, field.attname)                    if not isinstance(attr, Expression):                    if not hasattr(attr, 'resolve_expression'):                         attr = Value(attr, output_field=field)                     when_statements.append(When(pk=obj.pk, then=attr))                 case_statement = Case(*when_statements, output_field=field)


class SafeData:<ins>    __slots__ = ()</ins>     def __html__(self):         """         Return the html representation of a string for interoperability.


A str subclass that has been specifically marked as "safe" for HTML output     purposes.     """<ins>    __slots__ = ()</ins>     def __add__(self, rhs):         """         Concatenating a safe string with another safe bytestring or


if hasattr(default, 'resolve_expression'):             default = default.resolve_expression(query, allow_joins, reuse, summarize)         c.default = None  # Reset the default argument before wrapping.        return Coalesce(c, default, output_field=c._output_field_or_none)        coalesce = Coalesce(c, default, output_field=c._output_field_or_none)        coalesce.is_summary = c.is_summary        return coalesce      @property     def default_alias(self):


for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):             old_model_name = self.renamed_models.get((app_label, model_name), model_name)             old_model_state = self.from_state.models[app_label, old_model_name]            new_model_state = self.to_state.models[app_label, old_model_name]            new_model_state = self.to_state.models[app_label, model_name]             field = new_model_state.get_field(field_name)             # Scan to see if this is actually a rename!             field_dec = self.deep_deconstruct(field)


def as_sql(self, compiler, connection, template=None, **extra_context):         query = self.query.exists(using=connection.alias)        sql, params = super().as_sql(            compiler,            connection,            template=template,            query=query,            **extra_context,        )        try:            sql, params = super().as_sql(                compiler,                connection,                template=template,                query=query,                **extra_context,            )        except EmptyResultSet:            if self.negated:                return '', ()            raise         if self.negated:             sql = 'NOT {}'.format(sql)         return sql, params


@receiver(file_changed, dispatch_uid='template_loaders_file_changed') def template_changed(sender, file_path, **kwargs):<ins>    if file_path.suffix == '.py':        return</ins>     for template_dir in get_template_directories():         if template_dir in file_path.parents:             reset_loaders()


return result         return copy.deepcopy(self._wrapped, memo) <ins>    __add__ = new_method_proxy(operator.add)    @new_method_proxy    def __radd__(self, other):        return other + self</ins>  def partition(predicate, values):     """


<ins>import warnings</ins> from django.db.models.lookups import (     Exact,     GreaterThan,


LessThan,     LessThanOrEqual, )<ins>from django.utils.deprecation import RemovedInDjango50Warning</ins>   class MultiColSource:


from django.db.models import Model      if isinstance(value, Model):<ins>        if value.pk is None:            # When the deprecation ends, replace with:            # raise ValueError(            #     "Model instances passed to related filters must be saved."            # )            warnings.warn(                "Passing unsaved model instances to related filters is deprecated.",                RemovedInDjango50Warning,            )</ins>         value_list = []         sources = lhs.output_field.path_infos[-1].target_fields         for source in sources:


if is_async:             if not method_is_async:                 if debug:                    logger.debug("Synchronous %s adapted.", name)                    logger.debug("Synchronous handler adapted for %s.", name)                 return sync_to_async(method, thread_sensitive=True)         elif method_is_async:             if debug:                logger.debug("Asynchronous %s adapted.", name)                logger.debug("Asynchronous handler adapted for %s.", name)             return async_to_sync(method)         return method


)         # PK is used twice in the resulting update query, once in the filter         # and once in the WHEN. Each field will also have one CAST.<ins>        self._for_write = True</ins>         connection = connections[self.db]         max_batch_size = connection.ops.bulk_batch_size(["pk", "pk"] + fields, objs)         batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size


update_kwargs[field.attname] = case_statement             updates.append(([obj.pk for obj in batch_objs], update_kwargs))         rows_updated = 0        queryset = self.using(self.db)         with transaction.atomic(using=self.db, savepoint=False):             for pks, update_kwargs in updates:                rows_updated += self.filter(pk__in=pks).update(**update_kwargs)                rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)         return rows_updated      bulk_update.alters_data = True


import multiprocessing import os import shutilimport sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation


def get_test_db_clone_settings(self, suffix):         orig_settings_dict = self.connection.settings_dict         source_database_name = orig_settings_dict["NAME"]        if self.is_in_memory_db(source_database_name):        if not self.is_in_memory_db(source_database_name):            root, ext = os.path.splitext(source_database_name)            return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"}        start_method = multiprocessing.get_start_method()        if start_method == "fork":             return orig_settings_dict        else:            root, ext = os.path.splitext(orig_settings_dict["NAME"])            return {**orig_settings_dict, "NAME": "{}_{}{}".format(root, suffix, ext)}        if start_method == "spawn":            return {                **orig_settings_dict,                "NAME": f"{self.connection.alias}_{suffix}.sqlite3",            }        raise NotSupportedError(            f"Cloning with start method {start_method!r} is not supported."        )      def _clone_test_db(self, suffix, verbosity, keepdb=False):         source_database_name = self.connection.settings_dict["NAME"]         target_database_name = self.get_test_db_clone_settings(suffix)["NAME"]        # Forking automatically makes a copy of an in-memory database.         if not self.is_in_memory_db(source_database_name):             # Erase the old test database             if os.access(target_database_name, os.F_OK):


except Exception as e:                 self.log("Got an error cloning the test database: %s" % e)                 sys.exit(2)<ins>        # Forking automatically makes a copy of an in-memory database.        # Spawn requires migrating to disk which will be re-opened in        # setup_worker_connection.        elif multiprocessing.get_start_method() == "spawn":            ondisk_db = sqlite3.connect(target_database_name, uri=True)            self.connection.connection.backup(ondisk_db)</ins>      def _destroy_test_db(self, test_database_name, verbosity):         if test_database_name and not self.is_in_memory_db(test_database_name):


else:             sig.append(test_database_name)         return tuple(sig)    def setup_worker_connection(self, _worker_id):        settings_dict = self.get_test_db_clone_settings(_worker_id)        # connection.settings_dict must be updated in place for changes to be        # reflected in django.db.connections. Otherwise new threads would        # connect to the default database instead of the appropriate clone.        start_method = multiprocessing.get_start_method()        if start_method == "fork":            # Update settings_dict in place.            self.connection.settings_dict.update(settings_dict)            self.connection.close()        elif start_method == "spawn":            alias = self.connection.alias            connection_str = (                f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared"            )            source_db = self.connection.Database.connect(                f"file:{alias}_{_worker_id}.sqlite3", uri=True            )            target_db = sqlite3.connect(connection_str, uri=True)            source_db.backup(target_db)            source_db.close()            # Update settings_dict in place.            self.connection.settings_dict.update(settings_dict)            self.connection.settings_dict["NAME"] = connection_str            # Re-open connection to in-memory database before closing copy            # connection.            self.connection.connect()            target_db.close()            if os.environ.get("RUNNING_DJANGOS_TEST_SUITE") == "true":                self.mark_expected_failures_and_skips()diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py-- a/django/utils/autoreload.py++ b/django/utils/autoreload.py


# cause issues here.         if not isinstance(module, ModuleType):             continue        if module.__name__ == "__main__":        if module.__name__ in ("__main__", "__mp_main__"):             # __main__ (usually manage.py) doesn't always have a __spec__ set.             # Handle this by falling back to using __file__, resolved below.             # See https://docs.python.org/reference/import.html#main-spec


def USE_L10N(self):         stack = traceback.extract_stack()         # Show a warning if the setting is used outside of Django.        # Stack index: -1 this line, -2 the caller.        filename, _, _, _ = stack[-2]        # Stack index: -1 this line, -2 the LazyObject __getattribute__(),        # -3 the caller.        filename, _, _, _ = stack[-3]         if not filename.startswith(os.path.dirname(django.__file__)):             warnings.warn(                 USE_L10N_DEPRECATED_MSG,diff --git a/django/utils/functional.py b/django/utils/functional.py-- a/django/utils/functional.py++ b/django/utils/functional.py


self._setup()         return func(self._wrapped, *args) <ins>    inner._mask_wrapped = False</ins>     return inner


# override __copy__() and __deepcopy__() as well.         self._wrapped = empty <ins>    def __getattribute__(self, name):        value = super().__getattribute__(name)        # If attribute is a proxy method, raise an AttributeError to call        # __getattr__() and use the wrapped object method.        if not getattr(value, "_mask_wrapped", True):            raise AttributeError        return value</ins>     __getattr__ = new_method_proxy(getattr)      def __setattr__(self, name, value):


kwargs["db_table"] = self.db_table         if self.remote_field.db_constraint is not True:             kwargs["db_constraint"] = self.remote_field.db_constraint        # Rel needs more work.        # Lowercase model names as they should be treated as case-insensitive.         if isinstance(self.remote_field.model, str):            kwargs["to"] = self.remote_field.model            if "." in self.remote_field.model:                app_label, model_name = self.remote_field.model.split(".")                kwargs["to"] = "%s.%s" % (app_label, model_name.lower())            else:                kwargs["to"] = self.remote_field.model.lower()         else:            kwargs["to"] = self.remote_field.model._meta.label            kwargs["to"] = self.remote_field.model._meta.label_lower         if getattr(self.remote_field, "through", None) is not None:             if isinstance(self.remote_field.through, str):                 kwargs["through"] = self.remote_field.through


SELECT2_TRANSLATIONS.update({"zh-hans": "zh-CN", "zh-hant": "zh-TW"})  <ins>def get_select2_language():    lang_code = get_language()    supported_code = SELECT2_TRANSLATIONS.get(lang_code)    if supported_code is None:        # If 'zh-hant-tw' is not supported, try subsequent language codes i.e.        # 'zh-hant' and 'zh'.        i = None        while (i := lang_code.rfind("-", 0, i)) > -1:            if supported_code := SELECT2_TRANSLATIONS.get(lang_code[:i]):                return supported_code    return supported_code</ins> class AutocompleteMixin:     """     Select widget mixin that loads options from AutocompleteJsonView via AJAX.


self.db = using         self.choices = choices         self.attrs = {} if attrs is None else attrs.copy()        self.i18n_name = SELECT2_TRANSLATIONS.get(get_language())        self.i18n_name = get_select2_language()      def get_url(self):         return reverse(self.url_name % self.admin_site.name)


from functools import wraps <ins>from django.utils.functional import keep_lazy</ins>  class SafeData:     __slots__ = ()


return wrapped  <ins>@keep_lazy(SafeString)</ins> def mark_safe(s):     """     Explicitly mark a string as safe for (HTML) output purposes. The returned


"class": get_ul_class(self.radio_fields[db_field.name]),                     }                 )                kwargs["empty_label"] = _("None") if db_field.blank else None                kwargs["empty_label"] = (                    kwargs.get("empty_label", _("None")) if db_field.blank else None                )          if "queryset" not in kwargs:             queryset = self.get_field_queryset(db, db_field, request)


def add_legacy_name(apps, schema_editor):    alias = schema_editor.connection.alias     ContentType = apps.get_model("contenttypes", "ContentType")    for ct in ContentType.objects.all():    for ct in ContentType.objects.using(alias):         try:             ct.name = apps.get_model(ct.app_label, ct.model)._meta.object_name         except LookupError:


- a naive ``datetime.datetime`` object in UTC,         - an aware ``datetime.datetime`` object in any time zone.         If it is a ``datetime.datetime`` object then calculate ``max_age``.<ins>        ``max_age`` can be:        - int/float specifying seconds,        - ``datetime.timedelta`` object.</ins>         """         self.cookies[key] = value         if expires is not None:


delta = delta + datetime.timedelta(seconds=1)                 # Just set max_age - the max_age logic will set expires.                 expires = None                if max_age is not None:                    raise ValueError("'expires' and 'max_age' can't be used together.")                 max_age = max(0, delta.days * 86400 + delta.seconds)             else:                 self.cookies[key]["expires"] = expires         else:             self.cookies[key]["expires"] = ""         if max_age is not None:            if isinstance(max_age, datetime.timedelta):                max_age = max_age.total_seconds()             self.cookies[key]["max-age"] = int(max_age)             # IE requires expires, so set it if hasn't been already.             if not expires:


"models": [model_dict],                 }         if label:            return app_dict.get(label)         return app_dict     def get_app_list(self, request):    def get_app_list(self, request, app_label=None):         """         Return a sorted list of all the installed apps that have been         registered in this site.         """        app_dict = self._build_app_dict(request)        app_dict = self._build_app_dict(request, app_label)          # Sort the apps alphabetically.         app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower())


)      def app_index(self, request, app_label, extra_context=None):        app_dict = self._build_app_dict(request, app_label)        if not app_dict:        app_list = self.get_app_list(request, app_label)        if not app_list:             raise Http404("The requested admin page does not exist.")        # Sort the models alphabetically within each app.        app_dict["models"].sort(key=lambda x: x["name"])         context = {             **self.each_context(request),            "title": _("%(app)s administration") % {"app": app_dict["name"]},            "title": _("%(app)s administration") % {"app": app_list[0]["name"]},             "subtitle": None,            "app_list": [app_dict],            "app_list": app_list,             "app_label": app_label,             **(extra_context or {}),         }


else:             # Raise if a developer-specified template doesn't exist.             raise    return HttpResponseForbidden(t.render(c), content_type="text/html")    return HttpResponseForbidden(t.render(c))diff --git a/django/views/debug.py b/django/views/debug.py-- a/django/views/debug.py++ b/django/views/debug.py


reporter = get_exception_reporter_class(request)(request, exc_type, exc_value, tb)     if request.accepts("text/html"):         html = reporter.get_traceback_html()        return HttpResponse(html, status=status_code, content_type="text/html")        return HttpResponse(html, status=status_code)     else:         text = reporter.get_traceback_text()         return HttpResponse(


"raising_view_name": get_caller(request),         }     )    return HttpResponseNotFound(t.render(c), content_type="text/html")    return HttpResponseNotFound(t.render(c))   def default_urlconf(request):


}     )     return HttpResponse(t.render(c), content_type="text/html")    return HttpResponse(t.render(c))diff --git a/django/views/defaults.py b/django/views/defaults.py-- a/django/views/defaults.py++ b/django/views/defaults.py


try:         template = loader.get_template(template_name)         body = template.render(context, request)<del>        content_type = None  # Django will use 'text/html'.</del>     except TemplateDoesNotExist:         if template_name != ERROR_404_TEMPLATE_NAME:             # Reraise if it's a missing custom template.


},         )         body = template.render(Context(context))        content_type = "text/html"    return HttpResponseNotFound(body, content_type=content_type)    return HttpResponseNotFound(body)   @requires_csrf_token


raise         return HttpResponseServerError(             ERROR_PAGE_TEMPLATE % {"title": "Server Error (500)", "details": ""},<del>            content_type="text/html",</del>         )     return HttpResponseServerError(template.render())


raise         return HttpResponseBadRequest(             ERROR_PAGE_TEMPLATE % {"title": "Bad Request (400)", "details": ""},<del>            content_type="text/html",</del>         )     # No exception content is passed to the template, to not disclose any     # sensitive information.


raise         return HttpResponseForbidden(             ERROR_PAGE_TEMPLATE % {"title": "403 Forbidden", "details": ""},<del>            content_type="text/html",</del>         )     return HttpResponseForbidden(         template.render(request=request, context={"exception": str(exception)})


import warnings from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.db.models import Exists, OuterRef, Qfrom django.utils.deprecation import RemovedInDjango50Warningfrom django.utils.inspect import func_supports_parameter  UserModel = get_user_model()


"""         if not remote_user:             return<ins>        created = False</ins>         user = None         username = self.clean_username(remote_user)


user, created = UserModel._default_manager.get_or_create(                 **{UserModel.USERNAME_FIELD: username}             )            if created:                user = self.configure_user(request, user)         else:             try:                 user = UserModel._default_manager.get_by_natural_key(username)             except UserModel.DoesNotExist:                 pass        # RemovedInDjango50Warning: When the deprecation ends, replace with:        #   user = self.configure_user(request, user, created=created)        if func_supports_parameter(self.configure_user, "created"):            user = self.configure_user(request, user, created=created)        else:            warnings.warn(                f"`created=True` must be added to the signature of "                f"{self.__class__.__qualname__}.configure_user().",                category=RemovedInDjango50Warning,            )            if created:                user = self.configure_user(request, user)         return user if self.user_can_authenticate(user) else None      def clean_username(self, username):


"""         return username     def configure_user(self, request, user):    def configure_user(self, request, user, created=True):         """        Configure a user after creation and return the updated user.        Configure a user and return the updated user.          By default, return the user unmodified.         """


)             header_value = self.META.get(header)             if header_value is not None:                return "https" if header_value == secure_value else "http"                header_value, *_ = header_value.split(",", 1)                return "https" if header_value.strip() == secure_value else "http"         return self._get_scheme()      def is_secure(self):


if header is None:             raise ValueError         matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE)        if matches is None:            raise ValueError         header_mtime = parse_http_date(matches[1])         header_len = matches[3]         if header_len and int(header_len) != size:             raise ValueError         if int(mtime) > header_mtime:             raise ValueError    except (AttributeError, ValueError, OverflowError):    except (ValueError, OverflowError):         return True     return False


managers=self.managers,                 ),             ]<ins>        elif (            isinstance(operation, AlterModelManagers)            and self.name_lower == operation.name_lower        ):            return [                CreateModel(                    self.name,                    fields=self.fields,                    options=self.options,                    bases=self.bases,                    managers=operation.managers,                ),            ]</ins>         elif (             isinstance(operation, AlterTogetherOptionOperation)             and self.name_lower == operation.name_lower


class HasKeyLookup(PostgresOperatorLookup):     logical_operator = None <ins>    def compile_json_path_final_key(self, key_transform):        # Compile the final key without interpreting ints as array elements.        return ".%s" % json.dumps(key_transform)</ins>     def as_sql(self, compiler, connection, template=None):         # Process JSON path from the left-hand side.         if isinstance(self.lhs, KeyTransform):


*_, rhs_key_transforms = key.preprocess_lhs(compiler, connection)             else:                 rhs_key_transforms = [key]            rhs_params.append(                "%s%s"                % (                    lhs_json_path,                    compile_json_path(rhs_key_transforms, include_root=False),                )            )            *rhs_key_transforms, final_key = rhs_key_transforms            rhs_json_path = compile_json_path(rhs_key_transforms, include_root=False)            rhs_json_path += self.compile_json_path_final_key(final_key)            rhs_params.append(lhs_json_path + rhs_json_path)         # Add condition for each key.         if self.logical_operator:             sql = "(%s)" % self.logical_operator.join([sql] * len(rhs_params))


logical_operator = " OR "  <ins>class HasKeyOrArrayIndex(HasKey):    def compile_json_path_final_key(self, key_transform):        return compile_json_path([key_transform], include_root=False)</ins> class CaseInsensitiveMixin:     """     Mixin to allow case-insensitive comparison of JSON values on MySQL.


class KeyTransformIsNull(lookups.IsNull):     # key__isnull=False is the same as has_key='key'     def as_oracle(self, compiler, connection):        sql, params = HasKey(        sql, params = HasKeyOrArrayIndex(             self.lhs.lhs,             self.lhs.key_name,         ).as_oracle(compiler, connection)


template = "JSON_TYPE(%s, %%s) IS NULL"         if not self.rhs:             template = "JSON_TYPE(%s, %%s) IS NOT NULL"        return HasKey(self.lhs.lhs, self.lhs.key_name).as_sql(        return HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name).as_sql(             compiler,             connection,             template=template,


rhs, rhs_params = super().process_rhs(compiler, connection)         if rhs_params == ["null"]:             # Field has key and it's NULL.            has_key_expr = HasKey(self.lhs.lhs, self.lhs.key_name)            has_key_expr = HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name)             has_key_sql, has_key_params = has_key_expr.as_oracle(compiler, connection)             is_null_expr = self.lhs.get_lookup("isnull")(self.lhs, True)             is_null_sql, is_null_params = is_null_expr.as_sql(compiler, connection)


)  <ins>def is_valid_locale(locale):    return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z].*$", locale)</ins> @total_ordering class TranslatableFile:     def __init__(self, dirpath, file_name, locale_dir):


# Build po files for each selected locale             for locale in locales:                if "-" in locale:                    self.stdout.write(                        "invalid locale %s, did you mean %s?"                        % (                            locale,                            locale.replace("-", "_"),                        ),                if not is_valid_locale(locale):                    # Try to guess what valid locale it could be                    # Valid examples are: en_GB, shi_Latn_MA and nl_NL-x-informal                    # Search for characters followed by a non character (i.e. separator)                    match = re.match(                        r"^(?P<language>[a-zA-Z]+)"                        r"(?P<separator>[^a-zA-Z])"                        r"(?P<territory>.+)$",                        locale,                     )                    if match:                        locale_parts = match.groupdict()                        language = locale_parts["language"].lower()                        territory = (                            locale_parts["territory"][:2].upper()                            + locale_parts["territory"][2:]                        )                        proposed_locale = f"{language}_{territory}"                    else:                        # It could be a language in uppercase                        proposed_locale = locale.lower()                    # Recheck if the proposed locale is valid                    if is_valid_locale(proposed_locale):                        self.stdout.write(                            "invalid locale %s, did you mean %s?"                            % (                                locale,                                proposed_locale,                            ),                        )                    else:                        self.stdout.write("invalid locale %s" % locale)                     continue                 if self.verbosity > 0:                     self.stdout.write("processing locale %s" % locale)


and hasattr(default_manager, "get_by_natural_key")         and hasattr(Model, "natural_key")     ):        natural_key = Model(**data).natural_key()        obj = Model(**data)        obj._state.db = db        natural_key = obj.natural_key()         try:             data[Model._meta.pk.attname] = Model._meta.pk.to_python(                 default_manager.db_manager(db).get_by_natural_key(*natural_key).pk


"content_type_id": get_content_type_for_model(obj).pk,                     "object_id": obj.pk,                 },<ins>                current_app=self.admin_site.name,</ins>             )      def get_empty_value_display(self):


"""         return len([1 for count in self.alias_refcount.values() if count])     def join(self, join, reuse=None):    def join(self, join, reuse=None, reuse_with_filtered_relation=False):         """         Return an alias for the 'join', either reusing an existing alias for         that join or creating a new one. 'join' is either a base_table_class or


The 'reuse' parameter can be either None which means all joins are         reusable, or it can be a set containing the aliases that can be reused.         The 'reuse_with_filtered_relation' parameter is used when computing        FilteredRelation instances.         A join is always created as LOUTER if the lhs alias is LOUTER to make         sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new         joins are created as LOUTER if the join is nullable.         """        reuse_aliases = [            a            for a, j in self.alias_map.items()            if (reuse is None or a in reuse) and j.equals(join)        ]        if reuse_with_filtered_relation and reuse:            reuse_aliases = [                a for a, j in self.alias_map.items() if a in reuse and j.equals(join)            ]        else:            reuse_aliases = [                a                for a, j in self.alias_map.items()                if (reuse is None or a in reuse) and j == join            ]         if reuse_aliases:             if join.table_alias in reuse_aliases:                 reuse_alias = join.table_alias


can_reuse=None,         allow_joins=True,         split_subq=True,<ins>        reuse_with_filtered_relation=False,</ins>         check_filterable=True,     ):         """


The 'can_reuse' is a set of reusable joins for multijoins. <ins>        If 'reuse_with_filtered_relation' is True, then only joins in can_reuse        will be reused.</ins>         The method will create a filter clause that can be added to the current         query. However, if the filter isn't added to the query then the caller         is responsible for unreffing the joins used.


alias,                 can_reuse=can_reuse,                 allow_many=allow_many,<ins>                reuse_with_filtered_relation=reuse_with_filtered_relation,</ins>             )              # Prevent iterator from being consumed by check_related_objects()


current_negated=current_negated,                     allow_joins=True,                     split_subq=False,<ins>                    reuse_with_filtered_relation=True,</ins>                 )             target_clause.add(child_clause, connector)         return target_clause


break         return path, final_field, targets, names[pos + 1 :]     def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True):    def setup_joins(        self,        names,        opts,        alias,        can_reuse=None,        allow_many=True,        reuse_with_filtered_relation=False,    ):         """         Compute the necessary table joins for the passage through the fields         given in 'names'. 'opts' is the Options class for the current model


that can be reused. Note that non-reverse foreign keys are always         reusable when using setup_joins(). <ins>        The 'reuse_with_filtered_relation' can be used to force 'can_reuse'        parameter and force the relation on the given connections.</ins>         If 'allow_many' is False, then any reverse foreign key seen will         generate a MultiJoin exception.


nullable,                 filtered_relation=filtered_relation,             )            reuse = can_reuse if join.m2m else None            alias = self.join(connection, reuse=reuse)            reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None            alias = self.join(                connection,                reuse=reuse,                reuse_with_filtered_relation=reuse_with_filtered_relation,            )             joins.append(alias)             if filtered_relation:                 filtered_relation.path = joins[:]


from django.core import exceptions from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS<ins>from django.utils.functional import cached_property</ins> from django.utils.text import capfirst


else "",         )     @cached_property    def username_is_unique(self):        if self.username_field.unique:            return True        for unique_constraint in self.UserModel._meta.total_unique_constraints:            if (                len(unique_constraint.fields) == 1                and unique_constraint.fields[0] == self.username_field.name            ):                return True        return False     def _validate_username(self, username, verbose_field_name, database):         """Validate username. If invalid, return a string error message."""        if self.username_field.unique:        if self.username_is_unique:             try:                 self.UserModel._default_manager.db_manager(database).get_by_natural_key(                     username


# - changing only a field name         # - changing an attribute that doesn't affect the schema         # - adding only a db_column and the column name is not changed        non_database_attrs = [            "blank",            "db_column",            "editable",            "error_messages",            "help_text",            "limit_choices_to",            # Database-level options are not supported, see #21961.            "on_delete",            "related_name",            "related_query_name",            "validators",            "verbose_name",        ]        for attr in non_database_attrs:        for attr in old_field.non_db_attrs:             old_kwargs.pop(attr, None)        for attr in new_field.non_db_attrs:             new_kwargs.pop(attr, None)         return self.quote_name(old_field.column) != self.quote_name(             new_field.columndiff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py-- a/django/db/models/fields/__init__.py++ b/django/db/models/fields/__init__.py


system_check_deprecated_details = None     system_check_removed_details = None <ins>    # Attributes that don't affect a column definition.    # These attributes are ignored when altering the field.    non_db_attrs = (        "blank",        "choices",        "db_column",        "editable",        "error_messages",        "help_text",        "limit_choices_to",        # Database-level options are not supported, see #21961.        "on_delete",        "related_name",        "related_query_name",        "validators",        "verbose_name",    )</ins>     # Field flags     hidden = False


query.clear_ordering(force=True)         query.extra = {}         query.select = []        query.add_fields([query.get_meta().pk.name])        meta = query.get_meta()        fields = [meta.pk.name]        related_ids_index = []        for related in self.query.related_updates:            if all(                path.join_field.primary_key for path in meta.get_path_to_parent(related)            ):                # If a primary key chain exists to the targeted related update,                # then the meta.pk value can be used for it.                related_ids_index.append((related, 0))            else:                # This branch will only be reached when updating a field of an                # ancestor that is not part of the primary key chain of a MTI                # tree.                related_ids_index.append((related, len(fields)))                fields.append(related._meta.pk.name)        query.add_fields(fields)         super().pre_sql_setup()          must_pre_select = (


# don't want them to change), or the db backend doesn't support             # selecting from the updating table (e.g. MySQL).             idents = []            related_ids = collections.defaultdict(list)             for rows in query.get_compiler(self.using).execute_sql(MULTI):                 idents.extend(r[0] for r in rows)                for parent, index in related_ids_index:                    related_ids[parent].extend(r[index] for r in rows)             self.query.add_filter("pk__in", idents)            self.query.related_ids = idents            self.query.related_ids = related_ids         else:             # The fast path. Filters and updates in one query.             self.query.add_filter("pk__in", query)diff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py-- a/django/db/models/sql/subqueries.py++ b/django/db/models/sql/subqueries.py


query = UpdateQuery(model)             query.values = values             if self.related_ids is not None:                query.add_filter("pk__in", self.related_ids)                query.add_filter("pk__in", self.related_ids[model])             result.append(query)         return result


if lookup_name is None:             lookup_name = lookup.lookup_name         del cls.class_lookups[lookup_name]<ins>        cls._clear_cached_lookups()</ins>   def select_related_descend(field, restricted, requested, load_fields, reverse=False):


if not isinstance(backend, DjangoTemplates):             continue         items.update(cwd / to_path(dir) for dir in backend.engine.dirs)        items.update(cwd / to_path(dir) for dir in backend.engine.dirs if dir)          for loader in backend.engine.template_loaders:             if not hasattr(loader, "get_dirs"):


items.update(                 cwd / to_path(directory)                 for directory in loader.get_dirs()                if not is_django_path(directory)                if directory and not is_django_path(directory)             )     return items


def exists(self, using, limit=True):         q = self.clone()        if not q.distinct:        if not (q.distinct and q.is_sliced):             if q.group_by is True:                 q.add_fields(                     (f.attname for f in self.model._meta.concrete_fields), False


loaders = ["django.template.loaders.filesystem.Loader"]             if app_dirs:                 loaders += ["django.template.loaders.app_directories.Loader"]            if not debug:                loaders = [("django.template.loaders.cached.Loader", loaders)]            loaders = [("django.template.loaders.cached.Loader", loaders)]         else:             if app_dirs:                 raise ImproperlyConfigured(


# Security check -- Ensure the user-originating redirection URL is             # safe.             if not url_is_safe:                next_page = self.request.path                if settings.LOGOUT_REDIRECT_URL:                    next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)                else:                    next_page = self.request.path         return next_page      def get_context_data(self, **kwargs):


def _prepare_related_fields_for_save(self, operation_name, fields=None):         # Ensure that a model instance without a PK hasn't been assigned to        # a ForeignKey or OneToOneField on this model. If the field is        # nullable, allowing the save would result in silent data loss.        # a ForeignKey, GenericForeignKey or OneToOneField on this model. If        # the field is nullable, allowing the save would result in silent data        # loss.         for field in self._meta.concrete_fields:             if fields and field not in fields:                 continue


self, field.attname                 ):                     field.delete_cached_value(self)<ins>        # GenericForeignKeys are private.        for field in self._meta.private_fields:            if fields and field not in fields:                continue            if (                field.is_relation                and field.is_cached(self)                and hasattr(field, "fk_field")            ):                obj = field.get_cached_value(self, default=None)                if obj and obj.pk is None:                    raise ValueError(                        f"{operation_name}() prohibited to prevent data loss due to "                        f"unsaved related object '{field.name}'."                    )</ins>      def delete(self, using=None, keep_parents=False):         if self.pk is None:


# there instead             if collect_sql:                 schema_editor.collected_sql.append("--")                if not operation.reduces_to_sql:                    schema_editor.collected_sql.append(                        "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS "                        "SQL:"                    )                 schema_editor.collected_sql.append("-- %s" % operation.describe())                 schema_editor.collected_sql.append("--")                 if not operation.reduces_to_sql:                    schema_editor.collected_sql.append(                        "-- THIS OPERATION CANNOT BE WRITTEN AS SQL"                    )                     continue                collected_sql_before = len(schema_editor.collected_sql)             # Save the state before the operation has run             old_state = project_state.clone()             operation.state_forwards(self.app_label, project_state)


operation.database_forwards(                     self.app_label, schema_editor, old_state, project_state                 )<ins>            if collect_sql and collected_sql_before == len(schema_editor.collected_sql):                schema_editor.collected_sql.append("-- (no-op)")</ins>         return project_state      def unapply(self, project_state, schema_editor, collect_sql=False):


for operation, to_state, from_state in to_run:             if collect_sql:                 schema_editor.collected_sql.append("--")                if not operation.reduces_to_sql:                    schema_editor.collected_sql.append(                        "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS "                        "SQL:"                    )                 schema_editor.collected_sql.append("-- %s" % operation.describe())                 schema_editor.collected_sql.append("--")                 if not operation.reduces_to_sql:                    schema_editor.collected_sql.append(                        "-- THIS OPERATION CANNOT BE WRITTEN AS SQL"                    )                     continue                collected_sql_before = len(schema_editor.collected_sql)             atomic_operation = operation.atomic or (                 self.atomic and operation.atomic is not False             )


operation.database_backwards(                     self.app_label, schema_editor, from_state, to_state                 )<ins>            if collect_sql and collected_sql_before == len(schema_editor.collected_sql):                schema_editor.collected_sql.append("-- (no-op)")</ins>         return project_state      def suggest_name(self):


self.execute(self._delete_unique_sql(model, constraint_name))         # Drop incoming FK constraints if the field is a primary key or unique,         # which might be a to_field target, and things are going to change.        old_collation = old_db_params.get("collation")        new_collation = new_db_params.get("collation")         drop_foreign_keys = (             self.connection.features.supports_foreign_keys             and (                 (old_field.primary_key and new_field.primary_key)                 or (old_field.unique and new_field.unique)             )            and old_type != new_type            and ((old_type != new_type) or (old_collation != new_collation))         )         if drop_foreign_keys:             # '_meta.related_field' also contains M2M reverse fields, these


old_type_suffix = old_field.db_type_suffix(connection=self.connection)         new_type_suffix = new_field.db_type_suffix(connection=self.connection)         # Collation change?<del>        old_collation = old_db_params.get("collation")        new_collation = new_db_params.get("collation")</del>         if old_collation != new_collation:             # Collation change handles also a type change.             fragment = self._alter_column_collation_sql(


for old_rel, new_rel in rels_to_update:             rel_db_params = new_rel.field.db_parameters(connection=self.connection)             rel_type = rel_db_params["type"]            fragment, other_actions = self._alter_column_type_sql(                new_rel.related_model, old_rel.field, new_rel.field, rel_type            )            rel_collation = rel_db_params.get("collation")            old_rel_db_params = old_rel.field.db_parameters(connection=self.connection)            old_rel_collation = old_rel_db_params.get("collation")            if old_rel_collation != rel_collation:                # Collation change handles also a type change.                fragment = self._alter_column_collation_sql(                    new_rel.related_model,                    new_rel.field,                    rel_type,                    rel_collation,                )                other_actions = []            else:                fragment, other_actions = self._alter_column_type_sql(                    new_rel.related_model, old_rel.field, new_rel.field, rel_type                )             self.execute(                 self.sql_alter_column                 % {diff --git a/django/db/backends/oracle/features.py b/django/db/backends/oracle/features.py-- a/django/db/backends/oracle/features.py++ b/django/db/backends/oracle/features.py


"Raises ORA-00600: internal error code.": {             "model_fields.test_jsonfield.TestQuerying.test_usage_in_subquery",         },        "Oracle doesn't support changing collations on indexed columns (#33671).": {            "migrations.test_operations.OperationTests."            "test_alter_field_pk_fk_db_collation",        },     }     django_test_expected_failures = {         # A bug in Django/cx_Oracle with respect to string handling (#23843).diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py-- a/django/db/backends/sqlite3/schema.py++ b/django/db/backends/sqlite3/schema.py


# Alter by remaking table         self._remake_table(model, alter_field=(old_field, new_field))         # Rebuild tables with FKs pointing to this field.        if new_field.unique and old_type != new_type:        old_collation = old_db_params.get("collation")        new_collation = new_db_params.get("collation")        if new_field.unique and (            old_type != new_type or old_collation != new_collation        ):             related_models = set()             opts = new_field.model._meta             for remote_field in opts.related_objects:diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py-- a/django/db/models/fields/related.py++ b/django/db/models/fields/related.py


return self.target_field.rel_db_type(connection=connection)      def db_parameters(self, connection):        return {"type": self.db_type(connection), "check": self.db_check(connection)}        target_db_parameters = self.target_field.db_parameters(connection)        return {            "type": self.db_type(connection),            "check": self.db_check(connection),            "collation": target_db_parameters.get("collation"),        }      def convert_empty_strings(self, value, expression, connection):         if (not value) and isinstance(value, str):


OuterRef,     Ref,     ResolvedOuterRef,<ins>    Value,</ins> ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource


q.clear_ordering(force=True)         if limit:             q.set_limits(high=1)        q.add_extra({"a": 1}, None, None, None, None, None)        q.set_extra_mask(["a"])        q.add_annotation(Value(1), "a")         return q      def has_results(self, using):


alter_field and getattr(alter_field[1], "primary_key", False)         ):             for name, field in list(body.items()):                if field.primary_key:                if field.primary_key and not (                    # Do not remove the old primary key when an altered field                    # that introduces a primary key is the same field.                    alter_field                    and name == alter_field[1].name                ):                     field.primary_key = False                     restore_pk_field = field                     if field.auto_created:


<ins>from inspect import getattr_static, unwrap</ins> from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404, HttpResponse


# Check co_argcount rather than try/excepting the function and             # catching the TypeError, because something inside the function             # may raise the TypeError. This technique is more accurate.            func = unwrap(attr)             try:                code = attr.__code__                code = func.__code__             except AttributeError:                code = attr.__call__.__code__                func = unwrap(attr.__call__)                code = func.__code__            # If function doesn't have arguments and it is not a static method,            # it was decorated without using @functools.wraps.            if not code.co_argcount and not isinstance(                getattr_static(self, func.__name__, None), staticmethod            ):                raise ImproperlyConfigured(                    f"Feed method {attname!r} decorated by {func.__name__!r} needs to "                    f"use @functools.wraps."                )             if code.co_argcount == 2:  # one argument is 'self'                 return attr(obj)             else:


import functools import re<ins>from collections import defaultdict</ins> from itertools import chain  from django.conf import settings


self.generated_operations = {}         self.altered_indexes = {}         self.altered_constraints = {}<ins>        self.renamed_fields = {}</ins>          # Prepare some old/new state and model lists, separating         # proxy models and ignoring unmigrated apps.


self.generate_altered_options()         self.generate_altered_managers() <ins>        # Create the renamed fields and store them in self.renamed_fields.        # They are used by create_altered_indexes(), generate_altered_fields(),        # generate_removed_altered_index/unique_together(), and        # generate_altered_index/unique_together().        self.create_renamed_fields()</ins>         # Create the altered indexes and store them in self.altered_indexes.         # This avoids the same computation in generate_removed_indexes()         # and generate_added_indexes().


),             )     def generate_renamed_fields(self):    def create_renamed_fields(self):         """Work out renamed fields."""        self.renamed_fields = {}        self.renamed_operations = []        old_field_keys = self.old_field_keys.copy()         for app_label, model_name, field_name in sorted(            self.new_field_keys - self.old_field_keys            self.new_field_keys - old_field_keys         ):             old_model_name = self.renamed_models.get(                 (app_label, model_name), model_name


# Scan to see if this is actually a rename!             field_dec = self.deep_deconstruct(field)             for rem_app_label, rem_model_name, rem_field_name in sorted(                self.old_field_keys - self.new_field_keys                old_field_keys - self.new_field_keys             ):                 if rem_app_label == app_label and rem_model_name == model_name:                     old_field = old_model_state.get_field(rem_field_name)


if self.questioner.ask_rename(                             model_name, rem_field_name, field_name, field                         ):                            # A db_column mismatch requires a prior noop                            # AlterField for the subsequent RenameField to be a                            # noop on attempts at preserving the old name.                            if old_field.db_column != field.db_column:                                altered_field = field.clone()                                altered_field.name = rem_field_name                                self.add_operation(                            self.renamed_operations.append(                                (                                    rem_app_label,                                    rem_model_name,                                    old_field.db_column,                                    rem_field_name,                                     app_label,                                    operations.AlterField(                                        model_name=model_name,                                        name=rem_field_name,                                        field=altered_field,                                    ),                                    model_name,                                    field,                                    field_name,                                 )                            self.add_operation(                                app_label,                                operations.RenameField(                                    model_name=model_name,                                    old_name=rem_field_name,                                    new_name=field_name,                                ),                             )                            self.old_field_keys.remove(                            old_field_keys.remove(                                 (rem_app_label, rem_model_name, rem_field_name)                             )                            self.old_field_keys.add((app_label, model_name, field_name))                            old_field_keys.add((app_label, model_name, field_name))                             self.renamed_fields[                                 app_label, model_name, field_name                             ] = rem_field_name                             break     def generate_renamed_fields(self):        """Generate RenameField operations."""        for (            rem_app_label,            rem_model_name,            rem_db_column,            rem_field_name,            app_label,            model_name,            field,            field_name,        ) in self.renamed_operations:            # A db_column mismatch requires a prior noop AlterField for the            # subsequent RenameField to be a noop on attempts at preserving the            # old name.            if rem_db_column != field.db_column:                altered_field = field.clone()                altered_field.name = rem_field_name                self.add_operation(                    app_label,                    operations.AlterField(                        model_name=model_name,                        name=rem_field_name,                        field=altered_field,                    ),                )            self.add_operation(                app_label,                operations.RenameField(                    model_name=model_name,                    old_name=rem_field_name,                    new_name=field_name,                ),            )            self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))            self.old_field_keys.add((app_label, model_name, field_name))     def generate_added_fields(self):         """Make AddField operations."""         for app_label, model_name, field_name in sorted(


def create_altered_indexes(self):         option_name = operations.AddIndex.option_name<ins>        self.renamed_index_together_values = defaultdict(list)</ins>         for app_label, model_name in sorted(self.kept_model_keys):             old_model_name = self.renamed_models.get(                 (app_label, model_name), model_name


renamed_indexes.append((old_index_name, new_index_name, None))                         remove_from_added.append(new_index)                         remove_from_removed.append(old_index)<ins>            # Find index_together changed to indexes.            for (                old_value,                new_value,                index_together_app_label,                index_together_model_name,                dependencies,            ) in self._get_altered_foo_together_operations(                operations.AlterIndexTogether.option_name            ):                if (                    app_label != index_together_app_label                    or model_name != index_together_model_name                ):                    continue                removed_values = old_value.difference(new_value)                for removed_index_together in removed_values:                    renamed_index_together_indexes = []                    for new_index in added_indexes:                        _, args, kwargs = new_index.deconstruct()                        # Ensure only 'fields' are defined in the Index.                        if (                            not args                            and new_index.fields == list(removed_index_together)                            and set(kwargs) == {"name", "fields"}                        ):                            renamed_index_together_indexes.append(new_index)                    if len(renamed_index_together_indexes) == 1:                        renamed_index = renamed_index_together_indexes[0]                        remove_from_added.append(renamed_index)                        renamed_indexes.append(                            (None, renamed_index.name, removed_index_together)                        )                        self.renamed_index_together_values[                            index_together_app_label, index_together_model_name                        ].append(removed_index_together)</ins>             # Remove renamed indexes from the lists of added and removed             # indexes.             added_indexes = [


model_name,             dependencies,         ) in self._get_altered_foo_together_operations(operation.option_name):<ins>            if operation == operations.AlterIndexTogether:                old_value = {                    value                    for value in old_value                    if value                    not in self.renamed_index_together_values[app_label, model_name]                }</ins>             removal_value = new_value.intersection(old_value)             if removal_value or old_value:                 self.add_operation(


def copy(self):         return copy.copy(self)     def prefix_references(self, prefix):        clone = self.copy()        clone.set_source_expressions(            [                F(f"{prefix}{expr.name}")                if isinstance(expr, F)                else expr.prefix_references(prefix)                for expr in self.get_source_expressions()            ]        )        return clone     def get_group_by_cols(self, alias=None):         if not self.contains_aggregate:             return [self]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


):                     item = item.desc() if descending else item.asc()                 if isinstance(item, OrderBy):                    results.append((item, False))                    results.append(                        (item.prefix_references(f"{name}{LOOKUP_SEP}"), False)                    )                     continue                 results.extend(                    self.find_ordering_name(item, opts, alias, order, already_seen)                    (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref)                    for expr, is_ref in self.find_ordering_name(                        item, opts, alias, order, already_seen                    )                 )             return results         targets, alias, _ = self.query.trim_joins(targets, joins, path)


from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader<ins>from django.db.migrations.migration import SwappableTuplefrom django.db.migrations.optimizer import MigrationOptimizer</ins> from django.db.migrations.questioner import (     InteractiveMigrationQuestioner,     MigrationQuestioner,


"paths of generated migration files to stdout."             ),         )<ins>        parser.add_argument(            "--update",            action="store_true",            dest="update",            help=(                "Merge model changes into the latest migration and optimize the "                "resulting operations."            ),        )</ins>      @property     def log_output(self):


self.include_header = options["include_header"]         check_changes = options["check_changes"]         self.scriptable = options["scriptable"]<ins>        self.update = options["update"]</ins>         # If logs and prompts are diverted to stderr, remove the ERROR style.         if self.scriptable:             self.stderr.style_func = None


else:                     self.log("No changes detected")         else:            self.write_migration_files(changes)            if self.update:                self.write_to_last_migration_files(changes)            else:                self.write_migration_files(changes)             if check_changes:                 sys.exit(1)     def write_migration_files(self, changes):    def write_to_last_migration_files(self, changes):        loader = MigrationLoader(connections[DEFAULT_DB_ALIAS])        new_changes = {}        update_previous_migration_paths = {}        for app_label, app_migrations in changes.items():            # Find last migration.            leaf_migration_nodes = loader.graph.leaf_nodes(app=app_label)            if len(leaf_migration_nodes) == 0:                raise CommandError(                    f"App {app_label} has no migration, cannot update last migration."                )            leaf_migration_node = leaf_migration_nodes[0]            # Multiple leaf nodes have already been checked earlier in command.            leaf_migration = loader.graph.nodes[leaf_migration_node]            # Updated migration cannot be a squash migration, a dependency of            # another migration, and cannot be already applied.            if leaf_migration.replaces:                raise CommandError(                    f"Cannot update squash migration '{leaf_migration}'."                )            if leaf_migration_node in loader.applied_migrations:                raise CommandError(                    f"Cannot update applied migration '{leaf_migration}'."                )            depending_migrations = [                migration                for migration in loader.disk_migrations.values()                if leaf_migration_node in migration.dependencies            ]            if depending_migrations:                formatted_migrations = ", ".join(                    [f"'{migration}'" for migration in depending_migrations]                )                raise CommandError(                    f"Cannot update migration '{leaf_migration}' that migrations "                    f"{formatted_migrations} depend on."                )            # Build new migration.            for migration in app_migrations:                leaf_migration.operations.extend(migration.operations)                for dependency in migration.dependencies:                    if isinstance(dependency, SwappableTuple):                        if settings.AUTH_USER_MODEL == dependency.setting:                            leaf_migration.dependencies.append(                                ("__setting__", "AUTH_USER_MODEL")                            )                        else:                            leaf_migration.dependencies.append(dependency)                    elif dependency[0] != migration.app_label:                        leaf_migration.dependencies.append(dependency)            # Optimize migration.            optimizer = MigrationOptimizer()            leaf_migration.operations = optimizer.optimize(                leaf_migration.operations, app_label            )            # Update name.            previous_migration_path = MigrationWriter(leaf_migration).path            suggested_name = (                leaf_migration.name[:4] + "_" + leaf_migration.suggest_name()            )            if leaf_migration.name == suggested_name:                new_name = leaf_migration.name + "_updated"            else:                new_name = suggested_name            leaf_migration.name = new_name            # Register overridden migration.            new_changes[app_label] = [leaf_migration]            update_previous_migration_paths[app_label] = previous_migration_path        self.write_migration_files(new_changes, update_previous_migration_paths)    def write_migration_files(self, changes, update_previous_migration_paths=None):         """         Take a changes dict and write them out as migration files.         """


if self.verbosity >= 1:                     # Display a relative path if it's below the current working                     # directory, or an absolute path otherwise.                    try:                        migration_string = os.path.relpath(writer.path)                    except ValueError:                        migration_string = writer.path                    if migration_string.startswith(".."):                        migration_string = writer.path                    migration_string = self.get_relative_path(writer.path)                     self.log("  %s\n" % self.style.MIGRATE_LABEL(migration_string))                     for operation in migration.operations:                         self.log("    - %s" % operation.describe())


with open(writer.path, "w", encoding="utf-8") as fh:                         fh.write(migration_string)                         self.written_files.append(writer.path)<ins>                    if update_previous_migration_paths:                        prev_path = update_previous_migration_paths[app_label]                        rel_prev_path = self.get_relative_path(prev_path)                        if writer.needs_manual_porting:                            migration_path = self.get_relative_path(writer.path)                            self.log(                                self.style.WARNING(                                    f"Updated migration {migration_path} requires "                                    f"manual porting.\n"                                    f"Previous migration {rel_prev_path} was kept and "                                    f"must be deleted after porting functions manually."                                )                            )                        else:                            os.remove(prev_path)                            self.log(f"Deleted {rel_prev_path}")</ins>                 elif self.verbosity == 3:                     # Alternatively, makemigrations --dry-run --verbosity 3                     # will log the migrations rather than saving the file to


self.log(writer.as_string())         run_formatters(self.written_files) <ins>    @staticmethod    def get_relative_path(path):        try:            migration_string = os.path.relpath(path)        except ValueError:            migration_string = path        if migration_string.startswith(".."):            migration_string = path        return migration_string</ins>     def handle_merge(self, loader, conflicts):         """         Handles merging together conflicted migrations interactively,


from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _from django.utils.translation import ngettextfrom django.utils.translation import ngettext_lazy  __all__ = ("BaseFormSet", "formset_factory", "all_valid")


"ManagementForm data is missing or has been tampered with. Missing fields: "             "%(field_names)s. You may need to file a bug report if the issue persists."         ),<ins>        "too_many_forms": ngettext_lazy(            "Please submit at most %(num)d form.",            "Please submit at most %(num)d forms.",            "num",        ),        "too_few_forms": ngettext_lazy(            "Please submit at least %(num)d form.",            "Please submit at least %(num)d forms.",            "num",        ),</ins>     }      template_name_div = "django/forms/formsets/div.html"


TOTAL_FORM_COUNT             ] > self.absolute_max:                 raise ValidationError(                    ngettext(                        "Please submit at most %d form.",                        "Please submit at most %d forms.",                        self.max_num,                    )                    % self.max_num,                    self.error_messages["too_many_forms"] % {"num": self.max_num},                     code="too_many_forms",                 )             if (


< self.min_num             ):                 raise ValidationError(                    ngettext(                        "Please submit at least %d form.",                        "Please submit at least %d forms.",                        self.min_num,                    )                    % self.min_num,                    self.error_messages["too_few_forms"] % {"num": self.min_num},                     code="too_few_forms",                 )             # Give self.clean() a chance to do cross-form validation.


md5,     pbkdf2, )<ins>from django.utils.deprecation import RemovedInDjango50Warning</ins> from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _


pass  <ins># RemovedInDjango50Warning.</ins> class CryptPasswordHasher(BasePasswordHasher):     """     Password hashing using UNIX crypt (not recommended)


algorithm = "crypt"     library = "crypt" <ins>    def __init__(self, *args, **kwargs):        warnings.warn(            "django.contrib.auth.hashers.CryptPasswordHasher is deprecated.",            RemovedInDjango50Warning,            stacklevel=2,        )        super().__init__(*args, **kwargs)</ins>     def salt(self):         return get_random_string(2)


import datetime import functools import inspect<ins>import warnings</ins> from collections import defaultdict from decimal import Decimal from uuid import UUID


from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import Q from django.utils.deconstruct import deconstructible<ins>from django.utils.deprecation import RemovedInDjango50Warning</ins> from django.utils.functional import cached_property from django.utils.hashable import make_hashable


template = "%(expression)s %(ordering)s"     conditional = False     def __init__(        self, expression, descending=False, nulls_first=False, nulls_last=False    ):    def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None):         if nulls_first and nulls_last:             raise ValueError("nulls_first and nulls_last are mutually exclusive")        if nulls_first is False or nulls_last is False:            # When the deprecation ends, replace with:            # raise ValueError(            #     "nulls_first and nulls_last values must be True or None."            # )            warnings.warn(                "Passing nulls_first=False or nulls_last=False is deprecated, use None "                "instead.",                RemovedInDjango50Warning,                stacklevel=2,            )         self.nulls_first = nulls_first         self.nulls_last = nulls_last         self.descending = descending


def reverse_ordering(self):         self.descending = not self.descending        if self.nulls_first or self.nulls_last:            self.nulls_first = not self.nulls_first            self.nulls_last = not self.nulls_last        if self.nulls_first:            self.nulls_last = True            self.nulls_first = None        elif self.nulls_last:            self.nulls_first = True            self.nulls_last = None         return self      def asc(self):


# Check for a redirect based on settings.PREPEND_WWW         host = request.get_host()        must_prepend = settings.PREPEND_WWW and host and not host.startswith("www.")        redirect_url = ("%s://www.%s" % (request.scheme, host)) if must_prepend else ""         # Check if a slash should be appended        if self.should_redirect_with_slash(request):            path = self.get_full_path_with_slash(request)        else:            path = request.get_full_path()        # Return a redirect if necessary        if redirect_url or path != request.get_full_path():            redirect_url += path            return self.response_redirect_class(redirect_url)        if settings.PREPEND_WWW and host and not host.startswith("www."):            # Check if we also need to append a slash so we can do it all            # with a single redirect. (This check may be somewhat expensive,            # so we only do it if we already know we're sending a redirect,            # or in process_response if we get a 404.)            if self.should_redirect_with_slash(request):                path = self.get_full_path_with_slash(request)            else:                path = request.get_full_path()            return self.response_redirect_class(f"{request.scheme}://www.{host}{path}")      def should_redirect_with_slash(self, request):         """


else:             from_model_state = from_state.models[app_label, self.model_name_lower]             old_index = from_model_state.get_index_by_name(self.old_name)<ins>        # Don't alter when the index name is not changed.        if old_index.name == self.new_name:            return</ins>          to_model_state = to_state.models[app_label, self.model_name_lower]         new_index = to_model_state.get_index_by_name(self.new_name)


try:  # method call (assuming no args required)                             current = current()                         except TypeError:                            signature = inspect.signature(current)                             try:                                signature.bind()                            except TypeError:  # arguments *were* required                                current = (                                    context.template.engine.string_if_invalid                                )  # invalid method call                                signature = inspect.signature(current)                            except ValueError:  # No signature found.                                current = context.template.engine.string_if_invalid                             else:                                raise                                try:                                    signature.bind()                                except TypeError:  # Arguments *were* required.                                    # Invalid method call.                                    current = context.template.engine.string_if_invalid                                else:                                    raise         except Exception as e:             template_name = getattr(context, "template_name", None) or "unknown"             logger.debug(


option_name = "index_together"     system_check_deprecated_details = {        "msg": (            "AlterIndexTogether is deprecated. Support for it (except in historical "            "migrations) will be removed in Django 5.1."        ),        "id": "migrations.W001",    }     def __init__(self, name, index_together):         super().__init__(name, index_together) diff --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


import bisect import copy import inspect<ins>import warnings</ins> from collections import defaultdict  from django.apps import apps


from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint from django.db.models.query_utils import PathInfo from django.utils.datastructures import ImmutableList, OrderedSet<ins>from django.utils.deprecation import RemovedInDjango51Warning</ins> from django.utils.functional import cached_property from django.utils.module_loading import import_string from django.utils.text import camel_case_to_spaces, format_lazy


self.unique_together = normalize_together(self.unique_together)             self.index_together = normalize_together(self.index_together)<ins>            if self.index_together:                warnings.warn(                    f"'index_together' is deprecated. Use 'Meta.indexes' in "                    f"{self.label!r} instead.",                    RemovedInDjango51Warning,                )</ins>             # App label/class name interpolation for names of constraints and             # indexes.             if not getattr(cls._meta, "abstract", False):


import copy import inspect<ins>from functools import wraps</ins> from importlib import import_module  from django.db import router


@classmethod     def _get_queryset_methods(cls, queryset_class):         def create_method(name, method):            @wraps(method)             def manager_method(self, *args, **kwargs):                 return getattr(self.get_queryset(), name)(*args, **kwargs)             manager_method.__name__ = method.__name__            manager_method.__doc__ = method.__doc__             return manager_method          new_methods = {}


# Deleted uniques         for fields in olds.difference(news):             self._delete_composed_index(                model, fields, {"unique": True}, self.sql_delete_unique                model,                fields,                {"unique": True, "primary_key": False},                self.sql_delete_unique,             )         # Created uniques         for field_names in news.difference(olds):


exclude=meta_constraint_names | meta_index_names,             **constraint_kwargs,         )<ins>        if (            constraint_kwargs.get("unique") is True            and constraint_names            and self.connection.features.allows_multiple_constraints_on_same_fields        ):            # Constraint matching the unique_together name.            default_name = str(                self._unique_constraint_name(model._meta.db_table, columns, quote=False)            )            if default_name in constraint_names:                constraint_names = [default_name]</ins>         if len(constraint_names) != 1:             raise ValueError(                 "Found wrong number (%s) of constraints for %s(%s)"


):             return None         def create_unique_name(*args, **kwargs):            return self.quote_name(self._create_index_name(*args, **kwargs))         compiler = Query(model, alias_cols=False).get_compiler(             connection=self.connection         )         table = model._meta.db_table         columns = [field.column for field in fields]         if name is None:            name = IndexName(table, columns, "_uniq", create_unique_name)            name = self._unique_constraint_name(table, columns, quote=True)         else:             name = self.quote_name(name)         if condition or include or opclasses or expressions:


include=self._index_include_sql(model, include),         ) <ins>    def _unique_constraint_name(self, table, columns, quote=True):        if quote:            def create_unique_name(*args, **kwargs):                return self.quote_name(self._create_index_name(*args, **kwargs))        else:            create_unique_name = self._create_index_name        return IndexName(table, columns, "_uniq", create_unique_name)</ins>     def _delete_unique_sql(         self,         model,