from django.core.exceptions import ImproperlyConfiguredfrom django.forms import models as model_formsfrom django.forms import Form, models as model_forms from django.http import HttpResponseRedirect from django.views.generic.base import ContextMixin, TemplateResponseMixin, View from django.views.generic.detail import (


"No URL to redirect to. Provide a success_url.")  class BaseDeleteView(DeletionMixin, BaseDetailView):class BaseDeleteView(DeletionMixin, FormMixin, BaseDetailView):     """     Base view for deleting an object.      Using this base class requires subclassing to provide a response mixin.     """    form_class = Form    def post(self, request, *args, **kwargs):        # Set self.object before the usual form processing flow.        # Inlined because having DeletionMixin as the first base, for        # get_success_url(), makes leveraging super() with ProcessFormView        # overly complex.        self.object = self.get_object()        form = self.get_form()        if form.is_valid():            return self.form_valid(form)        else:            return self.form_invalid(form)    def form_valid(self, form):        success_url = self.get_success_url()        self.object.delete()        return HttpResponseRedirect(success_url)   class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):


<del>import datetime</del> import re  from django.core.exceptions import ValidationError


@cached_property     def initial(self):        data = self.form.get_initial_for_field(self.field, self.name)        # If this is an auto-generated default date, nix the microseconds for        # standardized handling. See #22502.        if (isinstance(data, (datetime.datetime, datetime.time)) and                not self.field.widget.supports_microseconds):            data = data.replace(microsecond=0)        return data        return self.form.get_initial_for_field(self.field, self.name)      def build_widget_attrs(self, attrs, widget=None):         widget = widget or self.field.widgetdiff --git a/django/forms/forms.py b/django/forms/forms.py-- a/django/forms/forms.py++ b/django/forms/forms.py


"""  import copy<ins>import datetime</ins>  from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django.forms.fields import Field, FileField


value = self.initial.get(field_name, field.initial)         if callable(value):             value = value()<ins>        # If this is an auto-generated default date, nix the microseconds        # for standardized handling. See #22502.        if (isinstance(value, (datetime.datetime, datetime.time)) and                not field.widget.supports_microseconds):            value = value.replace(microsecond=0)</ins>         return value


raise ValidationError(self.error_messages['invalid'], code='invalid')         return value <ins>    def validate(self, value):        super().validate(value)        if value in self.empty_values:            return        if not value.is_finite():            raise ValidationError(                self.error_messages['invalid'],                code='invalid',                params={'value': value},            )</ins>     def widget_attrs(self, widget):         attrs = super().widget_attrs(widget)         if isinstance(widget, NumberInput) and 'step' not in widget.attrs:


import re import string from importlib import import_module<ins>from pickle import PicklingError</ins> from urllib.parse import quote  from asgiref.local import Local


)         ) <ins>    def __reduce_ex__(self, protocol):        raise PicklingError(f'Cannot pickle {self.__class__.__qualname__}.')</ins>  def get_resolver(urlconf=None):     if urlconf is None:


self.deferred_loading = existing.union(field_names), True         else:             # Remove names from the set of any existing "immediate load" names.            self.deferred_loading = existing.difference(field_names), False            if new_existing := existing.difference(field_names):                self.deferred_loading = new_existing, False            else:                self.clear_deferred_loading()                if new_only := set(field_names).difference(existing):                    self.deferred_loading = new_only, True      def add_immediate_loading(self, field_names):         """


def identity(self):         return super().identity + (             self.through,            self.through_fields,            make_hashable(self.through_fields),             self.db_constraint,         )


from django.conf import settings from django.core.exceptions import DisallowedHost, ImproperlyConfigured<ins>from django.http import UnreadablePostError</ins> from django.http.request import HttpHeaders from django.urls import get_callable from django.utils.cache import patch_vary_headers


if request.method == 'POST':             try:                 request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')            except OSError:            except UnreadablePostError:                 # Handle a broken connection before we've completed reading the                 # POST data. process_view shouldn't raise any exceptions, so                 # we'll ignore and serve the user a 403 (assuming they're still


}  <ins>def _to_naive(value):    if timezone.is_aware(value):        value = timezone.make_naive(value, timezone.utc)    return valuedef _get_naive_now():    return _to_naive(timezone.now())</ins> class DateTimeCheckMixin:      def check(self, **kwargs):


def _check_fix_default_value(self):         return [] <ins>    # Concrete subclasses use this in their implementations of    # _check_fix_default_value().    def _check_if_value_fixed(self, value, now=None):        """        Check if the given value appears to have been provided as a "fixed"        time value, and include a warning in the returned list if it does. The        value argument must be a date object or aware/naive datetime object. If        now is provided, it must be a naive datetime object.        """        if now is None:            now = _get_naive_now()        offset = datetime.timedelta(seconds=10)        lower = now - offset        upper = now + offset        if isinstance(value, datetime.datetime):            value = _to_naive(value)        else:            assert isinstance(value, datetime.date)            lower = lower.date()            upper = upper.date()        if lower <= value <= upper:            return [                checks.Warning(                    'Fixed default value provided.',                    hint=(                        'It seems you set a fixed date / time / datetime '                        'value as default for this field. This may not be '                        'what you want. If you want to have the current date '                        'as default, use `django.utils.timezone.now`'                    ),                    obj=self,                    id='fields.W161',                )            ]        return []</ins>  class DateField(DateTimeCheckMixin, Field):     empty_strings_allowed = False


if not self.has_default():             return []         now = timezone.now()        if not timezone.is_naive(now):            now = timezone.make_naive(now, timezone.utc)         value = self.default         if isinstance(value, datetime.datetime):            if not timezone.is_naive(value):                value = timezone.make_naive(value, timezone.utc)            value = value.date()            value = _to_naive(value).date()         elif isinstance(value, datetime.date):            # Nothing to do, as dates don't have tz information             pass         else:             # No explicit date / datetime value -- no checks necessary             return []        offset = datetime.timedelta(days=1)        lower = (now - offset).date()        upper = (now + offset).date()        if lower <= value <= upper:            return [                checks.Warning(                    'Fixed default value provided.',                    hint='It seems you set a fixed date / time / datetime '                         'value as default for this field. This may not be '                         'what you want. If you want to have the current date '                         'as default, use `django.utils.timezone.now`',                    obj=self,                    id='fields.W161',                )            ]        return []        # At this point, value is a date object.        return self._check_if_value_fixed(value)      def deconstruct(self):         name, path, args, kwargs = super().deconstruct()


if not self.has_default():             return []         now = timezone.now()        if not timezone.is_naive(now):            now = timezone.make_naive(now, timezone.utc)         value = self.default        if isinstance(value, datetime.datetime):            second_offset = datetime.timedelta(seconds=10)            lower = now - second_offset            upper = now + second_offset            if timezone.is_aware(value):                value = timezone.make_naive(value, timezone.utc)        elif isinstance(value, datetime.date):            second_offset = datetime.timedelta(seconds=10)            lower = now - second_offset            lower = datetime.datetime(lower.year, lower.month, lower.day)            upper = now + second_offset            upper = datetime.datetime(upper.year, upper.month, upper.day)            value = datetime.datetime(value.year, value.month, value.day)        else:            # No explicit date / datetime value -- no checks necessary            return []        if lower <= value <= upper:            return [                checks.Warning(                    'Fixed default value provided.',                    hint='It seems you set a fixed date / time / datetime '                         'value as default for this field. This may not be '                         'what you want. If you want to have the current date '                         'as default, use `django.utils.timezone.now`',                    obj=self,                    id='fields.W161',                )            ]        if isinstance(value, (datetime.datetime, datetime.date)):            return self._check_if_value_fixed(value)        # No explicit date / datetime value -- no checks necessary.         return []      def get_internal_type(self):


if not self.has_default():             return []         now = timezone.now()        if not timezone.is_naive(now):            now = timezone.make_naive(now, timezone.utc)         value = self.default         if isinstance(value, datetime.datetime):            second_offset = datetime.timedelta(seconds=10)            lower = now - second_offset            upper = now + second_offset            if timezone.is_aware(value):                value = timezone.make_naive(value, timezone.utc)            now = None         elif isinstance(value, datetime.time):            second_offset = datetime.timedelta(seconds=10)            lower = now - second_offset            upper = now + second_offset            now = _get_naive_now()            # This will not use the right date in the race condition where now            # is just before the date change and value is just past 0:00.             value = datetime.datetime.combine(now.date(), value)            if timezone.is_aware(value):                value = timezone.make_naive(value, timezone.utc).time()         else:             # No explicit time / datetime value -- no checks necessary             return []        if lower <= value <= upper:            return [                checks.Warning(                    'Fixed default value provided.',                    hint='It seems you set a fixed date / time / datetime '                         'value as default for this field. This may not be '                         'what you want. If you want to have the current date '                         'as default, use `django.utils.timezone.now`',                    obj=self,                    id='fields.W161',                )            ]        return []        # At this point, value is a datetime object.        return self._check_if_value_fixed(value, now=now)      def deconstruct(self):         name, path, args, kwargs = super().deconstruct()


# Generate index removal operations before field is removed         self.generate_removed_constraints()         self.generate_removed_indexes()        # Generate field operations        # Generate field renaming operations.         self.generate_renamed_fields()        # Generate removal of foo together.        self.generate_removed_altered_unique_together()        self.generate_removed_altered_index_together()        # Generate field operations.         self.generate_removed_fields()         self.generate_added_fields()         self.generate_altered_fields()


dependencies.append((through_app_label, through_object_name, None, True))         return dependencies     def _generate_altered_foo_together(self, operation):        option_name = operation.option_name    def _get_altered_foo_together_operations(self, option_name):         for app_label, model_name in sorted(self.kept_model_keys):             old_model_name = self.renamed_models.get((app_label, model_name), model_name)             old_model_state = self.from_state.models[app_label, old_model_name]


dependencies.extend(self._get_dependencies_for_foreign_key(                                 app_label, model_name, field, self.to_state,                             ))                yield (                    old_value,                    new_value,                    app_label,                    model_name,                    dependencies,                )     def _generate_removed_altered_foo_together(self, operation):        for (            old_value,            new_value,            app_label,            model_name,            dependencies,        ) in self._get_altered_foo_together_operations(operation.option_name):            removal_value = new_value.intersection(old_value)            if removal_value or old_value:                 self.add_operation(                     app_label,                    operation(                        name=model_name,                        **{option_name: new_value}                    ),                    operation(name=model_name, **{operation.option_name: removal_value}),                    dependencies=dependencies,                )    def generate_removed_altered_unique_together(self):        self._generate_removed_altered_foo_together(operations.AlterUniqueTogether)    def generate_removed_altered_index_together(self):        self._generate_removed_altered_foo_together(operations.AlterIndexTogether)    def _generate_altered_foo_together(self, operation):        for (            old_value,            new_value,            app_label,            model_name,            dependencies,        ) in self._get_altered_foo_together_operations(operation.option_name):            removal_value = new_value.intersection(old_value)            if new_value != removal_value:                self.add_operation(                    app_label,                    operation(name=model_name, **{operation.option_name: new_value}),                     dependencies=dependencies,                 )


for form in self.saved_forms:                     form.save_m2m()             self.save_m2m = save_m2m        return self.save_existing_objects(commit) + self.save_new_objects(commit)        if self.edit_only:            return self.save_existing_objects(commit)        else:            return self.save_existing_objects(commit) + self.save_new_objects(commit)      save.alters_data = True


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


absolute_max=absolute_max, can_delete_extra=can_delete_extra,                               renderer=renderer)     FormSet.model = model<ins>    FormSet.edit_only = edit_only</ins>     return FormSet


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


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


except KeyError:                     raise CommandError("Cannot find a migration matching '%s' from app '%s'." % (                         migration_name, app_label))                targets = [(app_label, migration.name)]                target = (app_label, migration.name)                # Partially applied squashed migrations are not included in the                # graph, use the last replacement instead.                if (                    target not in executor.loader.graph.nodes and                    target in executor.loader.replacements                ):                    incomplete_migration = executor.loader.replacements[target]                    target = incomplete_migration.replaces[-1]                targets = [target]             target_app_labels_only = False         elif options['app_label']:             targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py-- a/django/core/management/commands/sqlmigrate.py++ b/django/core/management/commands/sqlmigrate.py


# Get the database we're operating from         connection = connections[options['database']]         # Load up an loader to get all the migration data, but don't replace        # Load up a loader to get all the migration data, but don't replace         # migrations.         loader = MigrationLoader(connection, replace_migrations=False) diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py-- a/django/db/migrations/loader.py++ b/django/db/migrations/loader.py


"There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix)             )         elif not results:            raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))            raise KeyError(                f"There is no migration for '{app_label}' with the prefix "                f"'{name_prefix}'"            )         else:             return self.disk_migrations[results[0]]


)             ) <ins>        if self.remote_field.symmetrical and self._related_name:            warnings.append(                checks.Warning(                    'related_name has no effect on ManyToManyField '                    'with a symmetrical relationship, e.g. to "self".',                    obj=self,                    id='fields.W345',                )            )</ins>         return warnings      def _check_relationship_model(self, from_model=None, **kwargs):


from django.forms import Form from django.forms.fields import BooleanField, IntegerField from django.forms.utils import ErrorListfrom django.forms.widgets import HiddenInput, NumberInputfrom django.forms.widgets import CheckboxInput, HiddenInput, NumberInput from django.utils.functional import cached_property from django.utils.html import html_safe from django.utils.safestring import mark_safe


"""     A collection of instances of the same Form class.     """<ins>    deletion_widget = CheckboxInput</ins>     ordering_widget = NumberInput     default_error_messages = {         'missing_management_form': _(


def get_default_prefix(cls):         return 'form' <ins>    @classmethod    def get_deletion_widget(cls):        return cls.deletion_widget</ins>     @classmethod     def get_ordering_widget(cls):         return cls.ordering_widget


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


'--check', action='store_true', dest='check_changes',             help='Exit with a non-zero status if model changes are missing migrations.',         )        parser.add_argument(            '--scriptable', action='store_true', dest='scriptable',            help=(                'Divert log output and input prompts to stderr, writing only '                'paths of generated migration files to stdout.'            ),        )    @property    def log_output(self):        return self.stderr if self.scriptable else self.stdout      def log(self, msg):        self.stdout.write(msg)        self.log_output.write(msg)      @no_translations     def handle(self, *app_labels, **options):


raise CommandError('The migration name must be a valid Python identifier.')         self.include_header = options['include_header']         check_changes = options['check_changes']<ins>        self.scriptable = options['scriptable']        # If logs and prompts are diverted to stderr, remove the ERROR style.        if self.scriptable:            self.stderr.style_func = None</ins>          # Make sure the app they asked for exists         app_labels = set(app_labels)


questioner = InteractiveMigrationQuestioner(                 specified_apps=app_labels,                 dry_run=self.dry_run,                prompt_output=self.stdout,                prompt_output=self.log_output,             )         else:             questioner = NonInteractiveMigrationQuestioner(


self.log('  %s\n' % self.style.MIGRATE_LABEL(migration_string))                     for operation in migration.operations:                         self.log('    - %s' % operation.describe())<ins>                    if self.scriptable:                        self.stdout.write(migration_string)</ins>                 if not self.dry_run:                     # Write the migrations file to the disk.                     migrations_directory = os.path.dirname(writer.path)


if it's safe; otherwise, advises on how to fix it.         """         if self.interactive:            questioner = InteractiveMigrationQuestioner(prompt_output=self.stdout)            questioner = InteractiveMigrationQuestioner(prompt_output=self.log_output)         else:             questioner = MigrationQuestioner(defaults={'ask_merge': True})


fh.write(writer.as_string())                     if self.verbosity > 0:                         self.log('\nCreated new merge migration %s' % writer.path)<ins>                        if self.scriptable:                            self.stdout.write(writer.path)</ins>                 elif self.verbosity == 3:                     # Alternatively, makemigrations --merge --dry-run --verbosity 3                     # will log the merge migrations rather than saving the file


def get(self, request, *args, **kwargs):         """        Return a JsonResponse with search results of the form:        Return a JsonResponse with search results as defined in        serialize_result(), by default:         {             results: [{id: "123" text: "foo"}],             pagination: {more: true}


context = self.get_context_data()         return JsonResponse({             'results': [                {'id': str(getattr(obj, to_field_name)), 'text': str(obj)}                self.serialize_result(obj, to_field_name)                 for obj in context['object_list']             ],             'pagination': {'more': context['page_obj'].has_next()},         })     def serialize_result(self, obj, to_field_name):        """        Convert the provided model object to a dictionary that is added to the        results list.        """        return {'id': str(getattr(obj, to_field_name)), 'text': str(obj)}     def get_paginator(self, *args, **kwargs):         """Use the ModelAdmin's paginator."""         return self.model_admin.get_paginator(self.request, *args, **kwargs)


gfk_key,             True,             self.name,            True,            False,         )      def __get__(self, instance, cls=None):


pk_val = getattr(instance, self.fk_field)          rel_obj = self.get_cached_value(instance, default=None)<ins>        if rel_obj is None and self.is_cached(instance):            return rel_obj</ins>         if rel_obj is not None:             ct_match = ct_id == self.get_content_type(obj=rel_obj, using=instance._state.db).id             pk_match = rel_obj._meta.pk.to_python(pk_val) == rel_obj.pk


def __init__(self, models=None, real_apps=None):         self.models = models or {}         # Apps to include from main registry, usually unmigrated ones        if real_apps:            self.real_apps = real_apps if isinstance(real_apps, set) else set(real_apps)        if real_apps is None:            real_apps = set()         else:            self.real_apps = set()            assert isinstance(real_apps, set)        self.real_apps = real_apps         self.is_delayed = False         # {remote_model_key: {model_key: [(field_name, field)]}}         self.relations = None


py_script = Path(sys.argv[0])      args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]<ins>    if sys.implementation.name == 'cpython':        args.extend(            f'-X{key}' if value is True else f'-X{key}={value}'            for key, value in sys._xoptions.items()        )</ins>     # __spec__ is set when the server was started with the `-m` option,     # see https://docs.python.org/3/reference/import.html#main-spec     # __spec__ may not exist, e.g. when running in a Conda env.


keyword arguments.     """     if takes_context:        if params[0] == 'context':        if params and params[0] == 'context':             params = params[1:]         else:             raise TemplateSyntaxError(


import copy import datetime import decimal<ins>import math</ins> import operator import uuid import warnings


if value is None:             return value         if isinstance(value, float):<ins>            if math.isnan(value):                raise exceptions.ValidationError(                    self.error_messages['invalid'],                    code='invalid',                    params={'value': value},                )</ins>             return self.context.create_decimal_from_float(value)         try:             return decimal.Decimal(value)


# 'self' argument, but it's a closure over self so it can call         # 'func'. Also, wrap method.__get__() in a function because new         # attributes can't be set on bound method objects, only on functions.        bound_method = partial(method.__get__(self, type(self)))        bound_method = wraps(method)(partial(method.__get__(self, type(self))))         for dec in decorators:             bound_method = dec(bound_method)         return bound_method(*args, **kwargs)


def _get_timezone_name(timezone):    """Return the name of ``timezone``."""    return str(timezone)    """    Return the offset for fixed offset timezones, or the name of timezone if    not set.    """    return timezone.tzname(None) or str(timezone)  # Timezone selection functions.


if self.interactive:             questioner = InteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run)         else:            questioner = NonInteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run)            questioner = NonInteractiveMigrationQuestioner(                specified_apps=app_labels,                dry_run=self.dry_run,                verbosity=self.verbosity,                log=self.log,            )         # Set up autodetector         autodetector = MigrationAutodetector(             loader.project_state(),diff --git a/django/db/migrations/questioner.py b/django/db/migrations/questioner.py-- a/django/db/migrations/questioner.py++ b/django/db/migrations/questioner.py


class NonInteractiveMigrationQuestioner(MigrationQuestioner):    def __init__(        self, defaults=None, specified_apps=None, dry_run=None, verbosity=1,        log=None,    ):        self.verbosity = verbosity        self.log = log        super().__init__(            defaults=defaults, specified_apps=specified_apps, dry_run=dry_run,        )    def log_lack_of_migration(self, field_name, model_name, reason):        if self.verbosity > 0:            self.log(                f"Field '{field_name}' on model '{model_name}' not migrated: "                f"{reason}."            )      def ask_not_null_addition(self, field_name, model_name):         # We can't ask the user, so act like the user aborted.        self.log_lack_of_migration(            field_name,            model_name,            'it is impossible to add a non-nullable field without specifying '            'a default',        )         sys.exit(3)      def ask_not_null_alteration(self, field_name, model_name):         # We can't ask the user, so set as not provided.        self.log(            f"Field '{field_name}' on model '{model_name}' given a default of "            f"NOT PROVIDED and must be corrected."        )         return NOT_PROVIDED      def ask_auto_now_add_addition(self, field_name, model_name):         # We can't ask the user, so act like the user aborted.        self.log_lack_of_migration(            field_name,            model_name,            "it is impossible to add a field with 'auto_now_add=True' without "            "specifying a default",        )         sys.exit(3)


fks_to_parent = [f for f in opts.fields if f.name == fk_name]         if len(fks_to_parent) == 1:             fk = fks_to_parent[0]            if not isinstance(fk, ForeignKey) or \                    (fk.remote_field.model != parent_model and                     fk.remote_field.model not in parent_model._meta.get_parent_list()):            parent_list = parent_model._meta.get_parent_list()            if not isinstance(fk, ForeignKey) or (                # ForeignKey to proxy models.                fk.remote_field.model._meta.proxy and                fk.remote_field.model._meta.proxy_for_model not in parent_list            ) or (                # ForeignKey to concrete models.                not fk.remote_field.model._meta.proxy and                fk.remote_field.model != parent_model and                fk.remote_field.model not in parent_list            ):                 raise ValueError(                     "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label)                 )


)     else:         # Try to discover what the ForeignKey from model to parent_model is        parent_list = parent_model._meta.get_parent_list()         fks_to_parent = [             f for f in opts.fields             if isinstance(f, ForeignKey) and (                 f.remote_field.model == parent_model or                f.remote_field.model in parent_model._meta.get_parent_list()                f.remote_field.model in parent_list or (                    f.remote_field.model._meta.proxy and                    f.remote_field.model._meta.proxy_for_model in parent_list                )             )         ]         if len(fks_to_parent) == 1:


* {{ 6666.6666|floatformat:"2g" }} displays "6,666.67"     * {{ 10000|floatformat:"g" }} displays "10,000"     If arg has the 'u' suffix, force the result to be unlocalized. When the    active locale is pl (Polish):    * {{ 66666.6666|floatformat:"2" }} displays "66666,67"    * {{ 66666.6666|floatformat:"2u" }} displays "66666.67"     If the input float is infinity or NaN, display the string representation     of that value.     """     force_grouping = False    if isinstance(arg, str) and arg.endswith('g'):        force_grouping = True        arg = arg[:-1] or -1    use_l10n = True    if isinstance(arg, str):        last_char = arg[-1]        if arg[-2:] in {'gu', 'ug'}:            force_grouping = True            use_l10n = False            arg = arg[:-2] or -1        elif last_char == 'g':            force_grouping = True            arg = arg[:-1] or -1        elif last_char == 'u':            use_l10n = False            arg = arg[:-1] or -1     try:         input_val = repr(text)         d = Decimal(input_val)


return input_val      if not m and p < 0:        return mark_safe(            formats.number_format('%d' % (int(d)), 0, force_grouping=force_grouping),        )        return mark_safe(formats.number_format(            '%d' % (int(d)),            0,            use_l10n=use_l10n,            force_grouping=force_grouping,        ))      exp = Decimal(1).scaleb(-abs(p))     # Set the precision high enough to avoid an exception (#15789).


if sign and rounded_d:         digits.append('-')     number = ''.join(reversed(digits))    return mark_safe(        formats.number_format(number, abs(p), force_grouping=force_grouping),    )    return mark_safe(formats.number_format(        number,        abs(p),        use_l10n=use_l10n,        force_grouping=force_grouping,    ))   @register.filter(is_safe=True)


remote_field.model._meta.model_name,         )         try:            url = reverse(url_name, args=[quote(remote_obj.pk)])            url = reverse(                url_name,                args=[quote(remote_obj.pk)],                current_app=self.model_admin.admin_site.name,            )             return format_html('{}', url, remote_obj)         except NoReverseMatch:             return str(remote_obj)


)         if request.method == 'POST':             form = ModelForm(request.POST, request.FILES, instance=obj)            formsets, inline_instances = self._create_formsets(                request,                form.instance if add else obj,                change=not add,            )             form_validated = form.is_valid()             if form_validated:                 new_object = self.save_form(request, form, change=not add)             else:                 new_object = form.instance            formsets, inline_instances = self._create_formsets(request, new_object, change=not add)             if all_valid(formsets) and form_validated:                 self.save_model(request, new_object, form, not add)                 self.save_related(request, form, formsets, not add)


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


'data-theme': 'admin-autocomplete',             'data-allow-clear': json.dumps(not self.is_required),             'data-placeholder': '',  # Allows clearing of the input.<ins>            'lang': self.i18n_name,</ins>             'class': attrs['class'] + (' ' if attrs['class'] else '') + 'admin-autocomplete',         })         return attrs


@property     def media(self):         extra = '' if settings.DEBUG else '.min'        i18n_name = SELECT2_TRANSLATIONS.get(get_language())        i18n_file = ('admin/js/vendor/select2/i18n/%s.js' % i18n_name,) if i18n_name else ()        i18n_file = ('admin/js/vendor/select2/i18n/%s.js' % self.i18n_name,) if self.i18n_name else ()         return forms.Media(             js=(                 'admin/js/vendor/jquery/jquery%s.js' % extra,


def get_primary_key_column(self, cursor, table_name):         """Return the column name of the primary key for the given table."""        # Don't use PRAGMA because that causes issues with some transactions         cursor.execute(            "SELECT sql, type FROM sqlite_master "            "WHERE tbl_name = %s AND type IN ('table', 'view')",            [table_name]            'PRAGMA table_info(%s)' % self.connection.ops.quote_name(table_name)         )        row = cursor.fetchone()        if row is None:            raise ValueError("Table %s does not exist" % table_name)        create_sql, table_type = row        if table_type == 'view':            # Views don't have a primary key.            return None        fields_sql = create_sql[create_sql.index('(') + 1:create_sql.rindex(')')]        for field_desc in fields_sql.split(','):            field_desc = field_desc.strip()            m = re.match(r'(?:(?:["`\[])(.*)(?:["`\]])|(\w+)).*PRIMARY KEY.*', field_desc)            if m:                return m[1] if m[1] else m[2]        for _, name, *_, pk in cursor.fetchall():            if pk:                return name         return None      def _get_foreign_key_constraints(self, cursor, table_name):


if not rel_is_hidden and clash_field.name == rel_name:                 errors.append(                     checks.Error(                        "Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),                        f"Reverse accessor '{rel_opts.object_name}.{rel_name}' "                        f"for '{field_name}' clashes with field name "                        f"'{clash_name}'.",                         hint=("Rename field '%s', or add/change a related_name "                               "argument to the definition for field '%s'.") % (clash_name, field_name),                         obj=self,


if not rel_is_hidden and clash_field.get_accessor_name() == rel_name:                 errors.append(                     checks.Error(                        "Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),                        f"Reverse accessor '{rel_opts.object_name}.{rel_name}' "                        f"for '{field_name}' clashes with reverse accessor for "                        f"'{clash_name}'.",                         hint=("Add or change a related_name argument "                               "to the definition for '%s' or '%s'.") % (field_name, clash_name),                         obj=self,


return cls      def __and__(self, other):<ins>        self._check_operator_queryset(other, '&')</ins>         self._merge_sanity_check(other)         if isinstance(other, EmptyQuerySet):             return other


return combined      def __or__(self, other):<ins>        self._check_operator_queryset(other, '|')</ins>         self._merge_sanity_check(other)         if isinstance(self, EmptyQuerySet):             return other


% (operation_name, self.query.combinator)             ) <ins>    def _check_operator_queryset(self, other, operator_):        if self.query.combinator or other.query.combinator:            raise TypeError(f'Cannot use {operator_} operator with combined queryset.')</ins>  class InstanceCheckMeta(type):     def __instancecheck__(self, instance):


def __str__(self):         return str(self.value) <ins>    def __hash__(self):        return hash(self.value)</ins>     def __eq__(self, other):         if isinstance(other, ModelChoiceIteratorValue):             other = other.value


clone = self.__class__._new_instance(             children=None, connector=self.connector, negated=self.negated,         )        clone.children = self.children[:]        for child in self.children:            if hasattr(child, 'clone'):                clone.children.append(child.clone())            else:                clone.children.append(child)         return clone      def relabeled_clone(self, change_map):


self.savepoint_state = 0         # List of savepoints created by 'atomic'.         self.savepoint_ids = []<ins>        # Stack of active 'atomic' blocks.        self.atomic_blocks = []</ins>         # Tracks if the outermost 'atomic' block should commit on exit,         # ie. if autocommit was active on entry.         self.commit_on_exit = True


# In case the previous connection was closed while in an atomic block         self.in_atomic_block = False         self.savepoint_ids = []        self.atomic_blocks = []         self.needs_rollback = False         # Reset parameters defining when to close the connection         max_age = self.settings_dict['CONN_MAX_AGE']diff --git a/django/db/transaction.py b/django/db/transaction.py-- a/django/db/transaction.py++ b/django/db/transaction.py


This is a private API.     """    # This private flag is provided only to disable the durability checks in    # TestCase.    _ensure_durability = True      def __init__(self, using, savepoint, durable):         self.using = using         self.savepoint = savepoint         self.durable = durable        self._from_testcase = False      def __enter__(self):         connection = get_connection(self.using)         if self.durable and self._ensure_durability and connection.in_atomic_block:        if (            self.durable and            connection.atomic_blocks and            not connection.atomic_blocks[-1]._from_testcase        ):             raise RuntimeError(                 'A durable atomic block cannot be nested within another '                 'atomic block.'


connection.set_autocommit(False, force_begin_transaction_with_broken_autocommit=True)             connection.in_atomic_block = True         if connection.in_atomic_block:            connection.atomic_blocks.append(self)     def __exit__(self, exc_type, exc_value, traceback):         connection = get_connection(self.using)         if connection.in_atomic_block:            connection.atomic_blocks.pop()         if connection.savepoint_ids:             sid = connection.savepoint_ids.pop()         else:


field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name)             else:                 field.default = self.questioner.ask_not_null_addition(field_name, model_name)        if (            field.unique and            field.default is not models.NOT_PROVIDED and            callable(field.default)        ):            self.questioner.ask_unique_callable_default_addition(field_name, model_name)         self.add_operation(             app_label,             operations.AddField(diff --git a/django/db/migrations/questioner.py b/django/db/migrations/questioner.py-- a/django/db/migrations/questioner.py++ b/django/db/migrations/questioner.py


from django.apps import apps from django.db.models import NOT_PROVIDED from django.utils import timezone<ins>from django.utils.version import get_docs_version</ins>  from .loader import MigrationLoader


# None means quit         return None <ins>    def ask_unique_callable_default_addition(self, field_name, model_name):        """Adding a unique field with a callable default."""        # None means continue.        return None</ins>  class InteractiveMigrationQuestioner(MigrationQuestioner):


return self._ask_default(default='timezone.now')         return None <ins>    def ask_unique_callable_default_addition(self, field_name, model_name):        """Adding a unique field with a callable default."""        if not self.dry_run:            version = get_docs_version()            choice = self._choice_input(                f'Callable default on unique field {model_name}.{field_name} '                f'will not generate unique values upon migrating.\n'                f'Please choose how to proceed:\n',                [                    f'Continue making this migration as the first step in '                    f'writing a manual migration to generate unique values '                    f'described here: '                    f'https://docs.djangoproject.com/en/{version}/howto/'                    f'writing-migrations/#migrations-that-add-unique-fields.',                    'Quit and edit field options in models.py.',                ],            )            if choice == 2:                sys.exit(3)        return None</ins>  class NonInteractiveMigrationQuestioner(MigrationQuestioner):


raise CommandError('You must use --%s with --noinput.' % field_name)                     field = self.UserModel._meta.get_field(field_name)                     user_data[field_name] = field.clean(value, None)<ins>                    if field.many_to_many and isinstance(user_data[field_name], str):                        user_data[field_name] = [                            pk.strip() for pk in user_data[field_name].split(',')                        ]</ins>              self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)             if options['verbosity'] >= 1:


for field_name in self.UserModel.REQUIRED_FIELDS:                     field = self.UserModel._meta.get_field(field_name)                     user_data[field_name] = options[field_name]<ins>                    if user_data[field_name] is not None:                        user_data[field_name] = field.clean(user_data[field_name], None)</ins>                     while user_data[field_name] is None:                         message = self._get_input_message(field)                         input_value = self.get_input_data(field, message)


from django.db import models from django.db.models.manager import EmptyManager from django.utils import timezone<ins>from django.utils.itercompat import is_iterable</ins> from django.utils.translation import gettext_lazy as _  from .validators import UnicodeUsernameValidator


Return True if the user has each of the specified permissions. If         object is passed, check if the user has all required perms for it.         """<ins>        if not is_iterable(perm_list) or isinstance(perm_list, str):            raise ValueError('perm_list must be an iterable of permissions.')</ins>         return all(self.has_perm(perm, obj) for perm in perm_list)      def has_module_perms(self, app_label):


return _user_has_perm(self, perm, obj=obj)      def has_perms(self, perm_list, obj=None):<ins>        if not is_iterable(perm_list) or isinstance(perm_list, str):            raise ValueError('perm_list must be an iterable of permissions.')</ins>         return all(self.has_perm(perm, obj) for perm in perm_list)      def has_module_perms(self, module):


def parse_number(cls, name):         """         Given a migration name, try to extract a number from the beginning of        it. If no number is found, return None.        it. For a squashed migration such as '0001_squashed_0004…', return the        second number. If no number is found, return None.         """        if squashed_match := re.search(r'.*_squashed_(\d+)', name):            return int(squashed_match[1])         match = re.match(r'^\d+', name)         if match:             return int(match[0])


old_field_dec[0:2] == field_dec[0:2] and                             dict(old_field_dec[2], db_column=old_db_column) == field_dec[2])):                         if self.questioner.ask_rename(model_name, rem_field_name, field_name, field):<ins>                            # 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(                                    app_label,                                    operations.AlterField(                                        model_name=model_name,                                        name=rem_field_name,                                        field=altered_field,                                    ),                                )</ins>                             self.add_operation(                                 app_label,                                 operations.RenameField(


new_field.remote_field.through = old_field.remote_field.through             old_field_dec = self.deep_deconstruct(old_field)             new_field_dec = self.deep_deconstruct(new_field)            if old_field_dec != new_field_dec:            # If the field was confirmed to be renamed it means that only            # db_column was allowed to change which generate_renamed_fields()            # already accounts for by adding an AlterField operation.            if old_field_dec != new_field_dec and old_field_name == field_name:                 both_m2m = old_field.many_to_many and new_field.many_to_many                 neither_m2m = not old_field.many_to_many and not new_field.many_to_many                 if both_m2m or neither_m2m:diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py-- a/django/db/migrations/operations/fields.py++ b/django/db/migrations/operations/fields.py


def reduce(self, operation, app_label):         if isinstance(operation, RemoveField) and self.is_same_field_operation(operation):             return [operation]        elif isinstance(operation, RenameField) and self.is_same_field_operation(operation):        elif (            isinstance(operation, RenameField) and            self.is_same_field_operation(operation) and            self.field.db_column is None        ):             return [                 operation,                 AlterField(


def rename_table_references(self, old_table, new_table):         if self.table != old_table:             return        expressions = deepcopy(self.expressions)        self.columns = []        for col in self.compiler.query._gen_cols([expressions]):            col.alias = new_table        self.expressions = expressions        self.expressions = self.expressions.relabeled_clone({old_table: new_table})         super().rename_table_references(old_table, new_table)      def rename_column_references(self, table, old_column, new_column):


new_model = to_state.apps.get_model(app_label, self.new_name)         if self.allow_migrate_model(schema_editor.connection.alias, new_model):             old_model = from_state.apps.get_model(app_label, self.old_name)            old_db_table = old_model._meta.db_table            new_db_table = new_model._meta.db_table            # Don't alter when a table name is not changed.            if old_db_table == new_db_table:                return             # Move the main table            schema_editor.alter_db_table(                new_model,                old_model._meta.db_table,                new_model._meta.db_table,            )            schema_editor.alter_db_table(new_model, old_db_table, new_db_table)             # Alter the fields pointing to us             for related_object in old_model._meta.related_objects:                 if related_object.related_model == old_model:


opt.dest in options and             (opt.required or opt in mutually_exclusive_required_options)         ):<ins>            opt_dest_count = sum(v == opt.dest for v in opt_mapping.values())            if opt_dest_count > 1:                raise TypeError(                    f'Cannot pass the dest {opt.dest!r} that matches multiple '                    f'arguments via **options.'                )</ins>             parse_args.append(min(opt.option_strings))             if isinstance(opt, (_AppendConstAction, _CountAction, _StoreConstAction)):                 continue


if search_fields and search_term:             orm_lookups = [construct_search(str(search_field))                            for search_field in search_fields]<ins>            term_queries = []</ins>             for bit in smart_split(search_term):                 if bit.startswith(('"', "'")) and bit[0] == bit[-1]:                     bit = unescape_string_literal(bit)


*((orm_lookup, bit) for orm_lookup in orm_lookups),                     _connector=models.Q.OR,                 )                queryset = queryset.filter(or_queries)                term_queries.append(or_queries)            queryset = queryset.filter(models.Q(*term_queries))             may_have_duplicates |= any(                 lookup_spawns_duplicates(self.opts, search_spec)                 for search_spec in orm_lookups


class FieldListFilter(ListFilter):     _field_list_filters = []     _take_priority_index = 0<ins>    list_separator = ','</ins>      def __init__(self, field, request, params, model, model_admin, field_path):         self.field = field


for p in self.expected_parameters():             if p in params:                 value = params.pop(p)                self.used_parameters[p] = prepare_lookup_value(p, value)                self.used_parameters[p] = prepare_lookup_value(p, value, self.list_separator)      def has_output(self):         return Truediff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py-- a/django/contrib/admin/utils.py++ b/django/contrib/admin/utils.py


return False  def prepare_lookup_value(key, value):def prepare_lookup_value(key, value, separator=','):     """     Return a lookup value prepared to be used in queryset filtering.     """     # if key ends with __in, split parameter into separate values     if key.endswith('__in'):        value = value.split(',')        value = value.split(separator)     # if key ends with __isnull, special case '' and the string literals 'false' and '0'     elif key.endswith('__isnull'):         value = value.lower() not in ('', 'false', '0')


extra_params['unique'] = True                      if is_relation:                        ref_db_column, ref_db_table = relations[column_name]                         if extra_params.pop('unique', False) or extra_params.get('primary_key'):                             rel_type = 'OneToOneField'                         else:                             rel_type = 'ForeignKey'                            ref_pk_column = connection.introspection.get_primary_key_column(cursor, ref_db_table)                            if ref_pk_column and ref_pk_column != ref_db_column:                                extra_params['to_field'] = ref_db_column                         rel_to = (                            "self" if relations[column_name][1] == table_name                            else table2model(relations[column_name][1])                            'self' if ref_db_table == table_name                            else table2model(ref_db_table)                         )                         if rel_to in known_models:                             field_type = '%s(%s' % (rel_type, rel_to)


<ins>import os</ins> from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError


# Write out the new migration file         writer = MigrationWriter(new_migration, include_header)<ins>        if os.path.exists(writer.path):            raise CommandError(                f'Migration {new_migration.name} already exists. Use a different name.'            )</ins>         with open(writer.path, "w", encoding='utf-8') as fh:             fh.write(writer.as_string())


self.page_timeout = None         self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX         self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS        self.cache = caches[self.cache_alias]    @property    def cache(self):        return caches[self.cache_alias]      def _should_update_cache(self, request, response):         return hasattr(request, '_cache_update_cache') and request._cache_update_cache


super().__init__(get_response)         self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX         self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS        self.cache = caches[self.cache_alias]    @property    def cache(self):        return caches[self.cache_alias]      def process_request(self, request):         """


if cache_alias is None:                 cache_alias = DEFAULT_CACHE_ALIAS             self.cache_alias = cache_alias<del>            self.cache = caches[self.cache_alias]</del>         except KeyError:             pass


sql, sql_params = super().as_sql(compiler, connection, ordering=(                 'ORDER BY ' + ', '.join(ordering_expr_sql)             ))            return sql, sql_params + ordering_params            return sql, (*sql_params, *ordering_params)         return super().as_sql(compiler, connection, ordering='')      def set_source_expressions(self, exprs):diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py-- a/django/db/models/aggregates.py++ b/django/db/models/aggregates.py


compiler, connection, template=template, filter=filter_sql,                     **extra_context                 )                return sql, params + filter_params                return sql, (*params, *filter_params)             else:                 copy = self.copy()                 copy.filter = None


return context      def id_for_label(self, id_):        if id_:            id_ += '_0'        return id_        return ''      def value_from_datadict(self, data, files, name):         return [


return self.as_sql(compiler, connection, **extra_context)  class ExpressionWrapper(Expression):class ExpressionWrapper(SQLiteNumericMixin, Expression):     """     An expression that can wrap another expression so that it can provide     extra context to the inner expression, such as the output_field.


return cols  class Case(Expression):class Case(SQLiteNumericMixin, Expression):     """     An SQL searched CASE expression:


import re from collections import namedtuple  import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import (     BaseDatabaseIntrospection, FieldInfo as BaseFieldInfo, TableInfo, )


"""         cursor.execute('PRAGMA table_info(%s)' % self.connection.ops.quote_name(table_name))         table_info = cursor.fetchall()<ins>        if not table_info:            raise DatabaseError(f'Table {table_name} does not exist (empty pragma).')</ins>         collations = self._get_column_collations(cursor, table_name)         json_columns = set()         if self.connection.features.can_introspect_json_field:


def get_relations(self, cursor, table_name):         """        Return a dictionary of {field_name: (field_name_other_table, other_table)}        Return a dictionary of {column_name: (ref_column_name, ref_table_name)}         representing all foreign keys in the given table.         """        # Dictionary of relations to return        relations = {}        # Schema for this table         cursor.execute(            "SELECT sql, type FROM sqlite_master "            "WHERE tbl_name = %s AND type IN ('table', 'view')",            [table_name]            'PRAGMA foreign_key_list(%s)' % self.connection.ops.quote_name(table_name)         )        create_sql, table_type = cursor.fetchone()        if table_type == 'view':            # It might be a view, then no results will be returned            return relations        results = create_sql[create_sql.index('(') + 1:create_sql.rindex(')')]        # Walk through and look for references to other tables. SQLite doesn't        # really have enforced references, but since it echoes out the SQL used        # to create the table we can look for REFERENCES statements used there.        for field_desc in results.split(','):            field_desc = field_desc.strip()            if field_desc.startswith("UNIQUE"):                continue            m = re.search(r'references (\S*) ?\(["|]?(.*)["|]?\)', field_desc, re.I)            if not m:                continue            table, column = [s.strip('"') for s in m.groups()]            if field_desc.startswith("FOREIGN KEY"):                # Find name of the target FK field                m = re.match(r'FOREIGN KEY\s*\(([^\)]*)\).*', field_desc, re.I)                field_name = m[1].strip('"')            else:                field_name = field_desc.split()[0].strip('"')            cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s", [table])            result = cursor.fetchall()[0]            other_table_results = result[0].strip()            li, ri = other_table_results.index('('), other_table_results.rindex(')')            other_table_results = other_table_results[li + 1:ri]            for other_desc in other_table_results.split(','):                other_desc = other_desc.strip()                if other_desc.startswith('UNIQUE'):                    continue                other_name = other_desc.split(' ', 1)[0].strip('"')                if other_name == column:                    relations[field_name] = (other_name, table)                    break        return relations        return {            column_name: (ref_column_name, ref_table_name)            for _, _, ref_table_name, column_name, ref_column_name, *_ in cursor.fetchall()        }      def get_primary_key_column(self, cursor, table_name):         """Return the column name of the primary key for the given table."""


return name         return None <del>    def _get_foreign_key_constraints(self, cursor, table_name):        constraints = {}        cursor.execute('PRAGMA foreign_key_list(%s)' % self.connection.ops.quote_name(table_name))        for row in cursor.fetchall():            # Remaining on_update/on_delete/match values are of no interest.            id_, _, table, from_, to = row[:5]            constraints['fk_%d' % id_] = {                'columns': [from_],                'primary_key': False,                'unique': False,                'foreign_key': (table, to),                'check': False,                'index': False,            }        return constraints</del>     def _parse_column_or_constraint_definition(self, tokens, columns):         token = None         is_constraint_definition = None


"check": False,                 "index": False,             }        constraints.update(self._get_foreign_key_constraints(cursor, table_name))        relations = enumerate(self.get_relations(cursor, table_name).items())        constraints.update({            f'fk_{index}': {                'columns': [column_name],                'primary_key': False,                'unique': False,                'foreign_key': (ref_table_name, ref_column_name),                'check': False,                'index': False,            }            for index, (column_name, (ref_column_name, ref_table_name)) in relations        })         return constraints      def _get_index_columns_orders(self, sql):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


for other_table in self.connection.introspection.get_table_list(cursor):                 if ignore_self and other_table.name == table_name:                     continue                constraints = self.connection.introspection._get_foreign_key_constraints(cursor, other_table.name)                for constraint in constraints.values():                    constraint_table, constraint_column = constraint['foreign_key']                relations = self.connection.introspection.get_relations(cursor, other_table.name)                for constraint_column, constraint_table in relations.values():                     if (constraint_table == table_name and                             (column_name is None or constraint_column == column_name)):                         return True


re.IGNORECASE ) language_code_prefix_re = _lazy_re_compile(r'^/(\w+([@-]\w+)?)(/|$)')language_code_prefix_re = _lazy_re_compile(r'^/(\w+([@-]\w+){0,2})(/|$)')   @receiver(setting_changed)


if self.verbosity >= 2:                     self.stdout.write('Creating %s' % new_path)                 try:                    shutil.copymode(old_path, new_path)                    self.apply_umask(old_path, new_path)                     self.make_writeable(new_path)                 except OSError:                     self.stderr.write(


scheme = template.split(':', 1)[0].lower()         return scheme in self.url_schemes <ins>    def apply_umask(self, old_path, new_path):        current_umask = os.umask(0)        os.umask(current_umask)        current_mode = stat.S_IMODE(os.stat(old_path).st_mode)        os.chmod(new_path, current_mode & ~current_umask)</ins>     def make_writeable(self, filename):         """         Make sure that the file is writeable.


@register.filter(is_safe=True)def json_script(value, element_id):def json_script(value, element_id=None):     """     Output value JSON-encoded, wrapped in a


}  def json_script(value, element_id):def json_script(value, element_id=None):     """     Escape all the HTML/XML special characters with their unicode escapes, so     value is safe to be output anywhere except for inside a tag attribute. Wrap


"""     from django.core.serializers.json import DjangoJSONEncoder     json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)    return format_html(        '',        element_id, mark_safe(json_str)    )    if element_id:        template = ''        args = (element_id, mark_safe(json_str))    else:        template = ''        args = (mark_safe(json_str),)    return format_html(template, *args)   def conditional_escape(text):


for name, field in sorted(fields.items()):             deconstruction = self.deep_deconstruct(field)             if field.remote_field and field.remote_field.model:                del deconstruction[2]['to']                deconstruction[2].pop('to', None)             fields_def.append(deconstruction)         return fields_def


from django.db.models import F, OrderByfrom django.db.models.expressions import OrderByList   class OrderableAggMixin:      def __init__(self, *expressions, ordering=(), **extra):        if not isinstance(ordering, (list, tuple)):            ordering = [ordering]        ordering = ordering or []        # Transform minus sign prefixed strings into an OrderBy() expression.        ordering = (            (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)            for o in ordering        )        if isinstance(ordering, (list, tuple)):            self.order_by = OrderByList(*ordering)        else:            self.order_by = OrderByList(ordering)         super().__init__(*expressions, **extra)        self.ordering = self._parse_expressions(*ordering)      def resolve_expression(self, *args, **kwargs):        self.ordering = [expr.resolve_expression(*args, **kwargs) for expr in self.ordering]        self.order_by = self.order_by.resolve_expression(*args, **kwargs)         return super().resolve_expression(*args, **kwargs)     def as_sql(self, compiler, connection):        if self.ordering:            ordering_params = []            ordering_expr_sql = []            for expr in self.ordering:                expr_sql, expr_params = compiler.compile(expr)                ordering_expr_sql.append(expr_sql)                ordering_params.extend(expr_params)            sql, sql_params = super().as_sql(compiler, connection, ordering=(                'ORDER BY ' + ', '.join(ordering_expr_sql)            ))            return sql, (*sql_params, *ordering_params)        return super().as_sql(compiler, connection, ordering='')    def get_source_expressions(self):        return super().get_source_expressions() + [self.order_by]      def set_source_expressions(self, exprs):        # Extract the ordering expressions because ORDER BY clause is handled        # in a custom way.        self.ordering = exprs[self._get_ordering_expressions_index():]        return super().set_source_expressions(exprs[:self._get_ordering_expressions_index()])        *exprs, self.order_by = exprs        return super().set_source_expressions(exprs)     def get_source_expressions(self):        return super().get_source_expressions() + self.ordering    def _get_ordering_expressions_index(self):        """Return the index at which the ordering expressions start."""        source_expressions = self.get_source_expressions()        return len(source_expressions) - len(self.ordering)    def as_sql(self, compiler, connection):        order_by_sql, order_by_params = compiler.compile(self.order_by)        sql, sql_params = super().as_sql(compiler, connection, ordering=order_by_sql)        return sql, (*sql_params, *order_by_params)diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py-- a/django/db/models/expressions.py++ b/django/db/models/expressions.py


class ExpressionList(Func):     """     An expression containing multiple expressions. Can be used to provide a    list of expressions as an argument to another expression, like an    ordering clause.    list of expressions as an argument to another expression, like a partition    clause.     """     template = '%(expressions)s'


return self.as_sql(compiler, connection, **extra_context)  <ins>class OrderByList(Func):    template = 'ORDER BY %(expressions)s'    def __init__(self, *expressions, **extra):        expressions = (            (                OrderBy(F(expr[1:]), descending=True)                if isinstance(expr, str) and expr[0] == '-'                else expr            )            for expr in expressions        )        super().__init__(*expressions, **extra)    def as_sql(self, *args, **kwargs):        if not self.source_expressions:            return '', ()        return super().as_sql(*args, **kwargs)</ins> class ExpressionWrapper(SQLiteNumericMixin, Expression):     """     An expression that can wrap another expression so that it can provide


if self.order_by is not None:             if isinstance(self.order_by, (list, tuple)):                self.order_by = ExpressionList(*self.order_by)            elif not isinstance(self.order_by, BaseExpression):                self.order_by = OrderByList(*self.order_by)            elif isinstance(self.order_by, (BaseExpression, str)):                self.order_by = OrderByList(self.order_by)            else:                 raise ValueError(                    'order_by must be either an Expression or a sequence of '                    'expressions.'                    'Window.order_by must be either a string reference to a '                    'field, an expression, or a list or tuple of them.'                 )         super().__init__(output_field=output_field)         self.source_expression = self._parse_expressions(expression)[0]


compiler=compiler, connection=connection,                 template='PARTITION BY %(expressions)s',             )            window_sql.extend(sql_expr)            window_sql.append(sql_expr)             window_params.extend(sql_params)          if self.order_by is not None:            window_sql.append(' ORDER BY ')             order_sql, order_params = compiler.compile(self.order_by)            window_sql.extend(order_sql)            window_sql.append(order_sql)             window_params.extend(order_params)          if self.frame:             frame_sql, frame_params = compiler.compile(self.frame)            window_sql.append(' ' + frame_sql)            window_sql.append(frame_sql)             window_params.extend(frame_params)          params.extend(window_params)


return template % {             'expression': expr_sql,            'window': ''.join(window_sql).strip()            'window': ' '.join(window_sql).strip()         }, params      def as_sqlite(self, compiler, connection):


return '{} OVER ({}{}{})'.format(             str(self.source_expression),             'PARTITION BY ' + str(self.partition_by) if self.partition_by else '',            'ORDER BY ' + str(self.order_by) if self.order_by else '',            str(self.order_by or ''),             str(self.frame or ''),         )


import stat import tempfile from importlib import import_modulefrom urllib.request import urlretrievefrom urllib.request import build_opener  import django from django.conf import settings


if self.verbosity >= 2:             self.stdout.write('Downloading %s' % display_url)        the_path = os.path.join(tempdir, filename)        opener = build_opener()        opener.addheaders = [('User-Agent', f'Django/{django.__version__}')]         try:            the_path, info = urlretrieve(url, os.path.join(tempdir, filename))            with opener.open(url) as source, open(the_path, 'wb') as target:                headers = source.info()                target.write(source.read())         except OSError as e:             raise CommandError("couldn't download URL %s to %s: %s" %                                (url, filename, e))


used_name = the_path.split('/')[-1]          # Trying to get better name from response headers        content_disposition = info.get('content-disposition')        content_disposition = headers['content-disposition']         if content_disposition:             _, params = cgi.parse_header(content_disposition)             guessed_filename = params.get('filename') or used_name


# Falling back to content type guessing         ext = self.splitext(guessed_filename)[1]        content_type = info.get('content-type')        content_type = headers['content-type']         if not ext and content_type:             ext = mimetypes.guess_extension(content_type)             if ext:


from django.apps import AppConfigfrom django.contrib.messages.storage import basefrom django.contrib.messages.utils import get_level_tagsfrom django.test.signals import setting_changed from django.utils.translation import gettext_lazy as _  def update_level_tags(setting, **kwargs):    if setting == 'MESSAGE_TAGS':        base.LEVEL_TAGS = get_level_tags() class MessagesConfig(AppConfig):     name = 'django.contrib.messages'     verbose_name = _("Messages")    def ready(self):        setting_changed.connect(update_level_tags)


if self.distinct_fields != rhs.distinct_fields:             raise TypeError('Cannot combine queries with different distinct fields.') <ins>        # If lhs and rhs shares the same alias prefix, it is possible to have        # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up        # as T4 -> T6 while combining two querysets. To prevent this, change an        # alias prefix of the rhs and update current aliases accordingly,        # except if the alias is the base table since it must be present in the        # query on both sides.        initial_alias = self.get_initial_alias()        rhs.bump_prefix(self, exclude={initial_alias})</ins>         # Work out how to relabel the rhs aliases, if necessary.         change_map = {}         conjunction = (connector == AND)


# the AND case. The results will be correct but this creates too many         # joins. This is something that could be fixed later on.         reuse = set() if conjunction else set(self.alias_map)<del>        # Base table must be present in the query - this is the same        # table on both sides.        self.get_initial_alias()</del>         joinpromoter = JoinPromoter(connector, 2, False)         joinpromoter.add_votes(             j for j in self.alias_map if self.alias_map[j].join_type == INNER)


relabelling any references to them in select columns and the where         clause.         """<ins>        # If keys and values of change_map were to intersect, an alias might be        # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending        # on their order in change_map.</ins>         assert set(change_map).isdisjoint(change_map.values())          # 1. Update references in "select" (normal columns plus aliases),


for alias, aliased in self.external_aliases.items()         }     def bump_prefix(self, outer_query):    def bump_prefix(self, other_query, exclude=None):         """         Change the alias prefix to the next letter in the alphabet in a way        that the outer query's aliases and this query's aliases will not        that the other query's aliases and this query's aliases will not         conflict. Even tables that previously had no alias will get an alias        after this call.        after this call. To prevent changing aliases use the exclude parameter.         """         def prefix_gen():             """


yield ''.join(s)                 prefix = None         if self.alias_prefix != outer_query.alias_prefix:        if self.alias_prefix != other_query.alias_prefix:             # No clashes between self and outer query should be possible.             return


'Maximum recursion depth exceeded: too many subqueries.'                 )         self.subq_aliases = self.subq_aliases.union([self.alias_prefix])        outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)        other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)        if exclude is None:            exclude = {}         self.change_aliases({             alias: '%s%d' % (self.alias_prefix, pos)             for pos, alias in enumerate(self.alias_map)            if alias not in exclude         })      def get_initial_alias(self):


using=using, raw=raw,         )     def _prepare_related_fields_for_save(self, operation_name):    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.         for field in self._meta.concrete_fields:            if fields and field not in fields:                continue             # If the related field isn't cached, then an instance hasn't been             # assigned and there's no need to worry about this check.             if field.is_relation and field.is_cached(self):diff --git a/django/db/models/query.py b/django/db/models/query.py-- a/django/db/models/query.py++ b/django/db/models/query.py


raise ValueError('bulk_update() cannot be used with primary key fields.')         if not objs:             return 0<ins>        for obj in objs:            obj._prepare_related_fields_for_save(operation_name='bulk_update', fields=fields)</ins>         # 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.         connection = connections[self.db]


if not expiry:   # Checks both None and 0 cases             return self.get_session_cookie_age()        if not isinstance(expiry, datetime):        if not isinstance(expiry, (datetime, str)):             return expiry        if isinstance(expiry, str):            expiry = datetime.fromisoformat(expiry)         delta = expiry - modification         return delta.days * 86400 + delta.seconds


if isinstance(expiry, datetime):             return expiry<ins>        elif isinstance(expiry, str):            return datetime.fromisoformat(expiry)</ins>         expiry = expiry or self.get_session_cookie_age()         return modification + timedelta(seconds=expiry)


return         if isinstance(value, timedelta):             value = timezone.now() + value<ins>        if isinstance(value, datetime):            value = value.isoformat()</ins>         self['_session_expiry'] = value      def get_expire_at_browser_close(self):


``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry         date/age, if there is one.         """        if self.get('_session_expiry') is None:        if (expiry := self.get('_session_expiry')) is None:             return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE        return self.get('_session_expiry') == 0        return expiry == 0      def flush(self):         """diff --git a/django/contrib/sessions/serializers.py b/django/contrib/sessions/serializers.py-- a/django/contrib/sessions/serializers.py++ b/django/contrib/sessions/serializers.py


# RemovedInDjango50Warning. from django.core.serializers.base import (     PickleSerializer as BasePickleSerializer, )diff --git a/django/core/cache/backends/redis.py b/django/core/cache/backends/redis.py-- a/django/core/cache/backends/redis.py++ b/django/core/cache/backends/redis.py


"""Redis cache backend.""" import pickle import random import re  from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCachefrom django.core.serializers.base import PickleSerializer from django.utils.functional import cached_property from django.utils.module_loading import import_string  class RedisSerializer(PickleSerializer):    """    Similar to PickSerializer, except integers are serialized as native Redis    integers for better incr() and decr() atomicity.    """class RedisSerializer:    def __init__(self, protocol=None):        self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol     def dumps(self, obj):         # Only skip pickling for integers, a int subclasses as bool should be         # pickled.         if type(obj) is int:             return obj        return super().dumps(obj)        return pickle.dumps(obj, self.protocol)      def loads(self, data):         try:             return int(data)         except ValueError:            return super().loads(data)            return pickle.loads(data)   class RedisCacheClient:diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py-- a/django/core/serializers/base.py++ b/django/core/serializers/base.py


Module for abstract serializer/unserializer base classes. """ import pickleimport warnings from io import StringIO  from django.core.exceptions import ObjectDoesNotExist from django.db import modelsfrom django.utils.deprecation import RemovedInDjango50Warning  DEFER_FIELD = object()


cache backends.     """     def __init__(self, protocol=None):<ins>        warnings.warn(            'PickleSerializer is deprecated due to its security risk. Use '            'JSONSerializer instead.',            RemovedInDjango50Warning,        )</ins>         self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol      def dumps(self, obj):


return [             constraint             for constraint in self.constraints            if isinstance(constraint, UniqueConstraint) and constraint.condition is None            if (                isinstance(constraint, UniqueConstraint) and                constraint.condition is None and                not constraint.contains_expressions            )         ]      @cached_property


return self  <ins>@deconstructible(path='django.db.models.Func')</ins> class Func(SQLiteNumericMixin, Expression):     """An SQL function call."""     function = None


return copy  <ins>@deconstructible(path='django.db.models.Value')</ins> class Value(SQLiteNumericMixin, Expression):     """Represent a wrapped value as a node within an expression."""     # Provide a default value for `for_save` in order to allow unresolved


return super().as_sql(*args, **kwargs)  <ins>@deconstructible(path='django.db.models.ExpressionWrapper')</ins> class ExpressionWrapper(SQLiteNumericMixin, Expression):     """     An expression that can wrap another expression so that it can provide


return "{}({})".format(self.__class__.__name__, self.expression)  <ins>@deconstructible(path='django.db.models.When')</ins> class When(Expression):     template = 'WHEN %(condition)s THEN %(result)s'     # This isn't a complete conditional expression, must be used in Case().


return cols  <ins>@deconstructible(path='django.db.models.Case')</ins> class Case(SQLiteNumericMixin, Expression):     """     An SQL searched CASE expression:


return sql, params  <ins>@deconstructible(path='django.db.models.OrderBy')</ins> class OrderBy(Expression):     template = '%(expression)s %(ordering)s'     conditional = False


with connection.cursor() as cursor:             cursor.execute(                'SELECT %s FROM %s WHERE %s = %%s and expires > %%s' % (                'SELECT %s FROM %s WHERE %s = %%s and %s > %%s' % (                     quote_name('cache_key'),                     quote_name(self._table),                     quote_name('cache_key'),                    quote_name('expires'),                 ),                 [key, connection.ops.adapt_datetimefield_value(now)]             )


else:             connection = connections[db]             table = connection.ops.quote_name(self._table)            cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,                           [connection.ops.adapt_datetimefield_value(now)])            cursor.execute('DELETE FROM %s WHERE %s < %%s' % (                table,                connection.ops.quote_name('expires'),            ), [connection.ops.adapt_datetimefield_value(now)])             deleted_count = cursor.rowcount             remaining_num = num - deleted_count             if remaining_num > self._max_entries:


last_cache_key = cursor.fetchone()                 if last_cache_key:                     cursor.execute(                        'DELETE FROM %s WHERE cache_key < %%s' % table,                        'DELETE FROM %s WHERE %s < %%s' % (                            table,                            connection.ops.quote_name('cache_key'),                        ),                         [last_cache_key[0]],                     ) diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py-- a/django/db/backends/base/operations.py++ b/django/db/backends/base/operations.py


This is used by the 'db' cache backend to determine where to start         culling.         """        return "SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s"        cache_key = self.quote_name('cache_key')        return f'SELECT {cache_key} FROM %s ORDER BY {cache_key} LIMIT 1 OFFSET %%s'      def unification_cast_sql(self, output_field):         """diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py-- a/django/db/backends/oracle/operations.py++ b/django/db/backends/oracle/operations.py


}      def cache_key_culling_sql(self):        return 'SELECT cache_key FROM %s ORDER BY cache_key OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY'        cache_key = self.quote_name('cache_key')        return (            f'SELECT {cache_key} '            f'FROM %s '            f'ORDER BY {cache_key} OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY'        )      def date_extract_sql(self, lookup_type, field_name):         if lookup_type == 'week_day':


def _path(route, view, kwargs=None, name=None, Pattern=None):     from django.views import View <ins>    if kwargs is not None and not isinstance(kwargs, dict):        raise TypeError(            f'kwargs argument must be a dict, but got {kwargs.__class__.__name__}.'        )</ins>     if isinstance(view, (list, tuple)):         # For include(...) processing.         pattern = Pattern(route, is_endpoint=False)


import copy import itertools import operator<ins>import warnings</ins> from functools import total_ordering, wraps


A cached property can be made out of an existing method:     (e.g. ``url = cached_property(get_absolute_url)``).<del>    The optional ``name`` argument is obsolete as of Python 3.6 and will be    deprecated in Django 4.0 (#30127).</del>     """     name = None


)      def __init__(self, func, name=None):<ins>        from django.utils.deprecation import RemovedInDjango50Warning        if name is not None:            warnings.warn(                "The name argument is deprecated as it's unnecessary as of "                "Python 3.6.",                RemovedInDjango50Warning,                stacklevel=2,            )</ins>         self.real_func = func         self.__doc__ = getattr(func, '__doc__')


raise ValidationError(self.message, code=self.code, params={'value': value})          # Then check full URL        try:            splitted_url = urlsplit(value)        except ValueError:            raise ValidationError(self.message, code=self.code, params={'value': value})         try:             super().__call__(value)         except ValidationError as e:             # Trivial case failed. Try for possible IDN domain             if value:                try:                    scheme, netloc, path, query, fragment = urlsplit(value)                except ValueError:  # for example, "Invalid IPv6 URL"                    raise ValidationError(self.message, code=self.code, params={'value': value})                scheme, netloc, path, query, fragment = splitted_url                 try:                     netloc = punycode(netloc)  # IDN -> ACE                 except UnicodeError:  # invalid domain part


raise         else:             # Now verify IPv6 in the netloc part            host_match = re.search(r'^\[(.+)\](?::\d{1,5})?$', urlsplit(value).netloc)            host_match = re.search(r'^\[(.+)\](?::\d{1,5})?$', splitted_url.netloc)             if host_match:                 potential_ip = host_match[1]                 try:


# section 3.1. It's defined to be 255 bytes or less, but this includes         # one byte for the length of the name and one byte for the trailing dot         # that's used to indicate absolute names in DNS.        if len(urlsplit(value).hostname) > 253:        if splitted_url.hostname is None or len(splitted_url.hostname) > 253:             raise ValidationError(self.message, code=self.code, params={'value': value})


iso8601_duration_re = _lazy_re_compile(     r'^(?P<sign>[-+]?)'     r'P'    r'(?:(?P<days>\d+(.\d+)?)D)?'    r'(?:(?P<days>\d+([\.,]\d+)?)D)?'     r'(?:T'    r'(?:(?P<hours>\d+(.\d+)?)H)?'    r'(?:(?P<minutes>\d+(.\d+)?)M)?'    r'(?:(?P<seconds>\d+(.\d+)?)S)?'    r'(?:(?P<hours>\d+([\.,]\d+)?)H)?'    r'(?:(?P<minutes>\d+([\.,]\d+)?)M)?'    r'(?:(?P<seconds>\d+([\.,]\d+)?)S)?'     r')?'     r'$' )


from functools import wraps <del>from django.http import HttpRequest</del> from django.middleware.cache import CacheMiddleware from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.decorators import decorator_from_middleware_with_args


def _cache_controller(viewfunc):         @wraps(viewfunc)         def _cache_controlled(request, *args, **kw):            if not isinstance(request, HttpRequest):            # Ensure argument looks like a request.            if not hasattr(request, 'META'):                 raise TypeError(                     "cache_control didn't receive an HttpRequest. If you are "                     "decorating a classmethod, be sure to use "


"""     @wraps(view_func)     def _wrapped_view_func(request, *args, **kwargs):        if not isinstance(request, HttpRequest):        # Ensure argument looks like a request.        if not hasattr(request, 'META'):             raise TypeError(                 "never_cache didn't receive an HttpRequest. If you are "                 "decorating a classmethod, be sure to use @method_decorator."


defaults = {'form_class': form_class, 'required': False}         return super().formfield(**{**defaults, **kwargs}) <ins>    def select_format(self, compiler, sql, params):        sql, params = super().select_format(compiler, sql, params)        # Filters that match everything are handled as empty strings in the        # WHERE clause, but in SELECT or GROUP BY list they must use a        # predicate that's always True.        if sql == '':            sql = '1'        return sql, params</ins>  class CharField(Field):     description = _("String (up to %(max_length)s)")


'--check', action='store_true', dest='check_unapplied',             help='Exits with a non-zero status if unapplied migrations exist.',         )<ins>        parser.add_argument(            '--prune', action='store_true', dest='prune',            help='Delete nonexistent migrations from the django_migrations table.',        )</ins>      @no_translations     def handle(self, *args, **options):


else:             targets = executor.loader.graph.leaf_nodes() <ins>        if options['prune']:            if not options['app_label']:                raise CommandError(                    'Migrations can be pruned only when an app is specified.'                )            if self.verbosity > 0:                self.stdout.write('Pruning migrations:', self.style.MIGRATE_HEADING)            to_prune = set(executor.loader.applied_migrations) - set(executor.loader.disk_migrations)            squashed_migrations_with_deleted_replaced_migrations = [                migration_key                for migration_key, migration_obj in executor.loader.replacements.items()                if any(replaced in to_prune for replaced in migration_obj.replaces)            ]            if squashed_migrations_with_deleted_replaced_migrations:                self.stdout.write(self.style.NOTICE(                    "  Cannot use --prune because the following squashed "                    "migrations have their 'replaces' attributes and may not "                    "be recorded as applied:"                ))                for migration in squashed_migrations_with_deleted_replaced_migrations:                    app, name = migration                    self.stdout.write(f'    {app}.{name}')                self.stdout.write(self.style.NOTICE(                    "  Re-run 'manage.py migrate' if they are not marked as "                    "applied, and remove 'replaces' attributes in their "                    "Migration classes."                ))            else:                to_prune = sorted(                    migration                    for migration in to_prune                    if migration[0] == app_label                )                if to_prune:                    for migration in to_prune:                        app, name = migration                        if self.verbosity > 0:                            self.stdout.write(self.style.MIGRATE_LABEL(                                f'  Pruning {app}.{name}'                            ), ending='')                        executor.recorder.record_unapplied(app, name)                        if self.verbosity > 0:                            self.stdout.write(self.style.SUCCESS(' OK'))                elif self.verbosity > 0:                    self.stdout.write('  No migrations to prune.')</ins>         plan = executor.migration_plan(targets)         exit_dry = plan and options['check_unapplied']


return         if exit_dry:             sys.exit(1)<ins>        if options['prune']:            return</ins>          # At this point, ignore run_syncdb if there aren't any apps to sync.         run_syncdb = options['run_syncdb'] and executor.loader.unmigrated_apps


return [], {}, set(), []     else:         using = router.db_for_write(obj._meta.model)    collector = NestedObjects(using=using)    collector = NestedObjects(using=using, origin=objs)     collector.collect(objs)     perms_needed = set() diff --git a/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py b/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py-- a/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py++ b/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py


ct_info = []                     for ct in to_remove:                         ct_info.append('    - Content type for %s.%s' % (ct.app_label, ct.model))                        collector = NoFastDeleteCollector(using=using)                        collector = NoFastDeleteCollector(using=using, origin=ct)                         collector.collect([ct])                          for obj_type, objs in collector.data.items():diff --git a/django/db/models/base.py b/django/db/models/base.py-- a/django/db/models/base.py++ b/django/db/models/base.py


"to None." % (self._meta.object_name, self._meta.pk.attname)             )         using = using or router.db_for_write(self.__class__, instance=self)        collector = Collector(using=using)        collector = Collector(using=using, origin=self)         collector.collect([self], keep_parents=keep_parents)         return collector.delete() diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py-- a/django/db/models/deletion.py++ b/django/db/models/deletion.py


class Collector:    def __init__(self, using):    def __init__(self, using, origin=None):         self.using = using        # A Model or QuerySet object.        self.origin = origin         # Initially, {model: {instances}}, later values become lists.         self.data = defaultdict(set)         # {model: {(field, value): {instances}}}


for model, obj in self.instances_with_model():                 if not model._meta.auto_created:                     signals.pre_delete.send(                        sender=model, instance=obj, using=self.using                        sender=model, instance=obj, using=self.using,                        origin=self.origin,                     )              # fast deletes


if not model._meta.auto_created:                     for obj in instances:                         signals.post_delete.send(                            sender=model, instance=obj, using=self.using                            sender=model, instance=obj, using=self.using,                            origin=self.origin,                         )          # update collected instancesdiff --git a/django/db/models/query.py b/django/db/models/query.py-- a/django/db/models/query.py++ b/django/db/models/query.py


del_query.query.select_related = False         del_query.query.clear_ordering(force=True)         collector = Collector(using=del_query.db)        collector = Collector(using=del_query.db, origin=self)         collector.collect(del_query)         deleted, _rows_count = collector.delete()


(un)applied and in a second step run all the database operations.         """         # The django_migrations table must be present to record applied        # migrations.        self.recorder.ensure_schema()        # migrations, but don't create it if there are no migrations to apply.        if plan == []:            if not self.recorder.has_table():                return self._create_project_state(with_applied_migrations=False)        else:            self.recorder.ensure_schema()          if plan is None:             plan = self.migration_plan(targets)


def reduce(self, operation, app_label):         return (             super().reduce(operation, app_label) or            not operation.references_model(self.name, app_label)            self.can_reduce_through(operation, app_label)         )     def can_reduce_through(self, operation, app_label):        return not operation.references_model(self.name, app_label)  class CreateModel(ModelOperation):     """Create a model's table."""


def migration_name_fragment(self):         return 'alter_%s_%s' % (self.name_lower, self.option_name) <ins>    def can_reduce_through(self, operation, app_label):        return (            super().can_reduce_through(operation, app_label) or (                isinstance(operation, AlterTogetherOptionOperation) and                type(operation) is not type(self)            )        )</ins>  class AlterUniqueTogether(AlterTogetherOptionOperation):     """