der, track each time a Manager instance is created.
    creation_counter = 0

    # Set to True for the 'objects' managers that are automatically created.
    auto_created = False

    #: If set to True the manager will be serialized into migrations and will
    #: thus be available in e.g. RunPython operations.
    use_in_migrations = False

    def __new__(cls, *args, **kwargs):
        # Capture the arguments to make returning them trivial.
        obj = super().__new__(cls)
        obj._constructor_args

  def __str__(self):
        """Return "app_label.model_label.manager_name"."""
        return "%s.%s" % (self.model._meta.label, self.name)

    def __class_getitem__(cls, *args, **kwargs):
        return cls

    def deconstruct(self):
        """

 = (args, kwargs)
        return obj

    def __init__(self):
        super().__init__()
        self._set_creation_counter()
        self.model = None
        self.name = None
        self._db = None
        self._hints = {}


nverting lookups (fk__somecol). The contents
# describe the relation in Model terms (model Options and Fields for both
# sides of the relation. The join_field is the field backing the relation.
PathInfo = namedtuple(
    "PathInfo",
    "from_opts to_opts target_fields join_field m2m direct filtered_relation",
)

def subclasses(cls):
    yield cls
    for subclass in cls.__subclasses__():
        yield from subclasses(subclass)

class Q(tree.Node):
    """
    Encapsulate filters as objects that can then

args, _connector=None, _negated=False, **kwargs):
        self._check_connector(_connector)
        super().__init__(
            children=[*args, *sorted(kwargs.items())],
            connector=_connector,
            negated=_negated,
        )

    @cla

be combined logically (using
    `&` and `|`).
    """

    # Connection types
    AND = "AND"
    OR = "OR"
    XOR = "XOR"
    default = AND
    conditional = True
    connectors = (None, AND, OR, XOR)

    def __init__(self, *


def make_model_tuple(model):
    """
    Take a model or a string of the form "app_label.ModelName" and return a
    corresponding ("app_label", "modelname") tuple. If a tuple is passed in,
    assume it's a valid model tuple already and return it unchanged.
    """
    try:
        if isinstance(model, tuple):
            model_tuple = model
        elif isinstance(model, str):
            app_label, model_name = model.split(".")
            model_tuple = app_label, model_name.lower()
        else:

erence '%s'. String model references "
            "must be of the form 'app_label.ModelName'." % model
        )

def resolve_callables(mapping):
    """
    Generate key/value pairs for the given mapping where the values are
    evaluated if they're cal

        model_tuple = model._meta.app_label, model._meta.model_name
        assert len(model_tuple) == 2
        return model_tuple
    except (ValueError, AssertionError):
        raise ValueError(
            "Invalid model ref


erce an expression to a new field type."""

    function = "CAST"
    template = "%(function)s(%(expressions)s AS %(db_type)s)"

    def __init__(self, expression, output_field):
        super().__init__(expression, output_field=output_field)

    def as_sql(self, compiler, connection, **extra_context):
        extra_context["db_type"] = self.output_field.cast_db_type(connection)
        return super().as_sql(compiler, connection, **extra_context)

    def as_sqlite(self, compiler, connection, **extra_conte

ns)s)"
            sql, params = super().as_sql(
                compiler, connection, template=template, **extra_context
            )
            format_string = "%H:%M:%f" if db_type == "time" else "%Y-%m-%d %H:%M:%f"
            params = (format_string

xt):
        db_type = self.output_field.db_type(connection)
        if db_type in {"datetime", "time"}:
            # Use strftime as datetime/time don't keep fractional seconds.
            template = "strftime(%%s, %(expressio


go.db.models.fields import TextField
from django.db.models.fields.json import JSONField
from django.db.models.functions import Cast

class JSONArray(Func):
    function = "JSON_ARRAY"
    output_field = JSONField()

    def as_sql(self, compiler, connection, **extra_context):
        if not connection.features.supports_json_field:
            raise NotSupportedError(
                "JSONFields are not supported on this database backend."
            )
        return super().as_sql(compiler, connection, **

LL values in the
        # array, mapping them to JSON null values, which matches the behavior
        # of SQLite.
        null_on_null = "NULL ON NULL" if len(self.get_source_expressions()) > 0 else ""

        return self.as_sql(
            compiler,

extra_context)

    def as_native(self, compiler, connection, *, returning, **extra_context):
        # PostgreSQL 16+ and Oracle remove SQL NULL values from the array by
        # default. Adds the NULL ON NULL clause to keep NU


ixins import (
    FixDecimalInputMixin,
    NumericOutputFieldMixin,
)
from django.db.models.lookups import Transform

class Abs(Transform):
    function = "ABS"
    lookup_name = "abs"

class ACos(NumericOutputFieldMixin, Transform):
    function = "ACOS"
    lookup_name = "acos"

class ASin(NumericOutputFieldMixin, Transform):
    function = "ASIN"
    lookup_name = "asin"

class ATan(NumericOutputFieldMixin, Transform):
    function = "ATAN"
    lookup_name = "atan"

class ATan2(NumericOutputFieldM

n >= (5, 0, 0):
            return self.as_sql(compiler, connection)
        # This function is usually ATan2(y, x), returning the inverse tangent
        # of y / x, but it's ATan2(x, y) on SpatiaLite < 5.0.0.
        # Cast integers to float to avoid inc

ixin, Func):
    function = "ATAN2"
    arity = 2

    def as_sqlite(self, compiler, connection, **extra_context):
        if not getattr(
            connection.ops, "spatialite", False
        ) or connection.ops.spatial_versio


# the test database.
TEST_DATABASE_PREFIX = "test_"

class BaseDatabaseCreation:
    """
    Encapsulate backend-specific differences pertaining to creation and
    destruction of the test database.
    """

    # If this backend's destroy_test_db() closes the database connection, this
    # attribute must be set to the name of the connection closing method (e.g.
    # "close" on Oracle, "close_pool" on MongoDB) to avoid failures in some
    # backends tests.
    destroy_test_db_connection_close_method =

:
        sys.stderr.write(msg + os.linesep)

    # RemovedInDjango70Warning: When the deprecation ends, replace with:
    # def create_test_db(self, verbosity=1, autoclobber=False, keepdb=False):
    def create_test_db(
        self, verbosity=1, autoclob

None

    def __init__(self, connection):
        self.connection = connection

    def __del__(self):
        del self.connection

    def _nodb_cursor(self):
        return self.connection._nodb_cursor()

    def log(self, msg)


.db.models.aggregates import *  # NOQA
from django.db.models.aggregates import __all__ as aggregates_all
from django.db.models.constraints import *  # NOQA
from django.db.models.constraints import __all__ as constraints_all
from django.db.models.deletion import (
    CASCADE,
    DB_CASCADE,
    DB_SET_DEFAULT,
    DB_SET_NULL,
    DO_NOTHING,
    PROTECT,
    RESTRICT,
    SET,
    SET_DEFAULT,
    SET_NULL,
    ProtectedError,
    RestrictedError,
)
from django.db.models.enums import *  # NOQA
from django

  RowRange,
    Subquery,
    Value,
    ValueRange,
    When,
    Window,
    WindowFrame,
    WindowFrameExclusion,
)
from django.db.models.fetch_modes import FETCH_ONE, FETCH_PEERS, RAISE
from django.db.models.fields import *  # NOQA
from django.db.mode

.db.models.enums import __all__ as enums_all
from django.db.models.expressions import (
    Case,
    Exists,
    Expression,
    ExpressionList,
    ExpressionWrapper,
    F,
    Func,
    JSONNull,
    OrderBy,
    OuterRef,


        nullable=field.null,
        fail_on_restricted=False,
    )
    if field.null and not connections[using].features.can_defer_constraint_checks:
        collector.add_field_update(field, None, sub_objs)

def PROTECT(collector, field, sub_objs, using):
    raise ProtectedError(
        "Cannot delete some instances of model '%s' because they are "
        "referenced through a protected foreign key: '%s.%s'"
        % (
            field.remote_field.model.__name__,
            sub_objs[0].__class__

 field.model)

def SET(value):
    if callable(value):

        def set_on_delete(collector, field, sub_objs, using):
            collector.add_field_update(field, value(), sub_objs)

    else:

        def set_on_delete(collector, field, sub_objs, using)

.__name__,
            field.name,
        ),
        sub_objs,
    )

def RESTRICT(collector, field, sub_objs, using):
    collector.add_restricted_objects(field, sub_objs)
    collector.add_dependency(field.remote_field.model,


 Index:
    suffix = "idx"
    # The max length of the name of the index (restricted to 30 for
    # cross-database compatibility with Oracle)
    max_name_length = 30

    def __init__(
        self,
        *expressions,
        fields=(),
        name=None,
        db_tablespace=None,
        opclasses=(),
        condition=None,
        include=None,
    ):
        if opclasses and not name:
            raise ValueError("An index must be named to use opclasses.")
        if not isinstance(condition, (No

t, tuple)):
            raise ValueError("Index.fields must be a list or tuple.")
        if not isinstance(opclasses, (list, tuple)):
            raise ValueError("Index.opclasses must be a list or tuple.")
        if not expressions and not fields:

neType, Q)):
            raise ValueError("Index.condition must be a Q instance.")
        if condition and not name:
            raise ValueError("An index must be named to use condition.")
        if not isinstance(fields, (lis


mpiler.select, klass_info,
        # and annotations.
        results = compiler.execute_sql(
            chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
        )
        select, klass_info, annotation_col_map = (
            compiler.select,
            compiler.klass_info,
            compiler.annotation_col_map,
        )
        model_cls = klass_info["model"]
        select_fields = klass_info["select_fields"]
        model_fields_start, model_fields_end = select_fields[0], select_fields[

lated_objects = [
            (
                field,
                related_objs,
                attnames := [
                    (
                        field.attname
                        if from_field == "self"
                        else quer

-1] + 1
        init_list = [
            f[0].target.attname for f in select[model_fields_start:model_fields_end]
        ]
        related_populators = get_related_populators(klass_info, select, db, fetch_mode)
        known_re


tial

from django.db.models.utils import make_model_tuple
from django.dispatch import Signal

class_prepared = Signal()

class ModelSignal(Signal):
    """
    Signal subclass that allows the sender to be lazily specified as a string
    of the `app_label.ModelName` form.
    """

    def _lazy_method(self, method, apps, receiver, sender, **kwargs):
        from django.db.models.options import Options

        # This partial takes a single optional argument named "sender".
        partial_method = partial(

ial_method(sender)

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None, apps=None):
        self._lazy_method(
            super().connect,
            apps,
            receiver,
            sender,
            weak=weak,

method, receiver, **kwargs)
        if isinstance(sender, str):
            apps = apps or Options.default_apps
            apps.lazy_model_operation(partial_method, make_model_tuple(sender))
        else:
            return part


imalField, FloatField, IntegerField
from django.db.models.functions import Cast

class FixDecimalInputMixin:
    def as_postgresql(self, compiler, connection, **extra_context):
        # Cast FloatField to DecimalField as PostgreSQL doesn't support the
        # following function signatures:
        # - LOG(double, double)
        # - MOD(double, double)
        output_field = DecimalField(decimal_places=sys.float_info.dig, max_digits=1000)
        clone = self.copy()
        clone.set_source_expressions(

expression in self.get_source_expressions()
            ]
        )
        return clone.as_sql(compiler, connection, **extra_context)

class FixDurationInputMixin:
    def as_mysql(self, compiler, connection, **extra_context):
        sql, params = super

            [
                (
                    Cast(expression, output_field)
                    if isinstance(expression.output_field, FloatField)
                    else expression
                )
                for


ql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
    sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
    sql_alter_column_no_default_null = sql_alter_column_no_default
    sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
    sql_rename_column = (
        "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
    )
    sql_update_with_default = (
        "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"

(name)s %(constraint)s"
    sql_pk_constraint = "PRIMARY KEY (%(columns)s)"

    sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
    sql_delete_check = sql_delete_constraint

    sql_create_unique = (
        "ALTER TAB

   )

    sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s"
    sql_check_constraint = "CHECK (%(check)s)"
    sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
    sql_constraint = "CONSTRAINT %


ombine(other, self.BITLEFTSHIFT, False)

    def bitrightshift(self, other):
        return self._combine(other, self.BITRIGHTSHIFT, False)

    def __xor__(self, other):
        if getattr(self, "conditional", False) and getattr(other, "conditional", False):
            return Q(self) ^ Q(other)
        raise NotImplementedError(
            "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
        )

    def bitxor(self, other):
        return self._combine(other, self.BITXOR, False

), and .bitxor() for bitwise logical operations."
        )

    def bitor(self, other):
        return self._combine(other, self.BITOR, False)

    def __radd__(self, other):
        return self._combine(other, self.ADD, True)

    def __rsub__(self, othe

)

    def __or__(self, other):
        if getattr(self, "conditional", False) and getattr(other, "conditional", False):
            return Q(self) | Q(other)
        raise NotImplementedError(
            "Use .bitand(), .bitor(


eatest, Least, NullIf
from .datetime import (
    Extract,
    ExtractDay,
    ExtractHour,
    ExtractIsoWeekDay,
    ExtractIsoYear,
    ExtractMinute,
    ExtractMonth,
    ExtractQuarter,
    ExtractSecond,
    ExtractWeek,
    ExtractWeekDay,
    ExtractYear,
    Now,
    Trunc,
    TruncDate,
    TruncDay,
    TruncHour,
    TruncMinute,
    TruncMonth,
    TruncQuarter,
    TruncSecond,
    TruncTime,
    TruncWeek,
    TruncYear,
)
from .json import JSONArray, JSONObject
from .math import (
    Abs,

.text import (
    MD5,
    SHA1,
    SHA224,
    SHA256,
    SHA384,
    SHA512,
    Chr,
    Concat,
    ConcatPair,
    Left,
    Length,
    Lower,
    LPad,
    LTrim,
    Ord,
    Repeat,
    Replace,
    Reverse,
    Right,
    RPad,
    RTrim,

    ACos,
    ASin,
    ATan,
    ATan2,
    Ceil,
    Cos,
    Cot,
    Degrees,
    Exp,
    Floor,
    Ln,
    Log,
    Mod,
    Pi,
    Power,
    Radians,
    Random,
    Round,
    Sign,
    Sin,
    Sqrt,
    Tan,
)
from


ne

    def get_tzname(self):
        # Timezone conversions must happen to the input datetime *before*
        # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
        # database as 2016-01-01 01:00:00 +00:00. Any results should be
        # based on the input datetime not the stored datetime.
        tzname = None
        if settings.USE_TZ:
            if self.tzinfo is None:
                tzname = timezone.get_current_timezone_name()
            else:
                tzname = timezon

a):
        if self.lookup_name is None:
            self.lookup_name = lookup_name
        if self.lookup_name is None:
            raise ValueError("lookup_name must be provided")
        self.tzinfo = tzinfo
        super().__init__(expression, **extra)

e._get_timezone_name(self.tzinfo)
        return tzname

class Extract(TimezoneMixin, Transform):
    lookup_name = None
    output_field = IntegerField()

    def __init__(self, expression, lookup_name=None, tzinfo=None, **extr


ther a tuple of tuples, or a single
    tuple of two strings. Normalize it to a tuple of tuples, so that
    calling code can uniformly expect that.
    """
    try:
        if not option_together:
            return ()
        if not isinstance(option_together, (tuple, list)):
            raise TypeError
        first_element = option_together[0]
        if not isinstance(first_element, (tuple, list)):
            option_together = (option_together,)
        # Normalize everything to tuples
        return

ther

def make_immutable_fields_list(name, data):
    return ImmutableList(data, warning=IMMUTABLE_WARNING % name)

class Options:
    FORWARD_PROPERTIES = {
        "fields",
        "many_to_many",
        "concrete_fields",
        "local_concrete_fie

tuple(tuple(ot) for ot in option_together)
    except TypeError:
        # If the value of option_together isn't valid, return it
        # verbatim; this will be picked up by the check framework later.
        return option_toge


iolation_error_message = _("Constraint “%(name)s” is violated.")
    violation_error_code = None
    violation_error_message = None

    non_db_attrs = ("violation_error_code", "violation_error_message")

    def __init__(
        self, *, name, violation_error_code=None, violation_error_message=None
    ):
        self.name = name
        if violation_error_code is not None:
            self.violation_error_code = violation_error_code
        if violation_error_message is not None:
            self.violati

sql(self, model, schema_editor):
        raise NotImplementedError("This method must be implemented by a subclass.")

    def create_sql(self, model, schema_editor):
        raise NotImplementedError("This method must be implemented by a subclass.")

    d

on_error_message = violation_error_message
        else:
            self.violation_error_message = self.default_violation_error_message

    @property
    def contains_expressions(self):
        return False

    def constraint_


 return mark_safe(output)
        else:
            return output

class CommentNode(Node):
    child_nodelists = ()

    def render(self, context):
        return ""

class CsrfTokenNode(Node):
    child_nodelists = ()

    def render(self, context):
        csrf_token = context.get("csrf_token")
        if csrf_token:
            if csrf_token == "NOTPROVIDED":
                return format_html("")
            else:
                return format_html(
                    '<input type="hidden" name="csr

   if settings.DEBUG:
                warnings.warn(
                    "A {% csrf_token %} was used in a template, but the context "
                    "did not provide the value. This is usually caused by not "
                    "using RequestContext

fmiddlewaretoken" value="{}">',
                    csrf_token,
                )
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning


_keys)

class RelatedField(FieldCacheMixin, Field):
    """Base class that all relational fields inherit from."""

    # Field flags
    one_to_many = False
    one_to_one = False
    many_to_many = False
    many_to_one = False

    def __init__(
        self,
        related_name=None,
        related_query_name=None,
        limit_choices_to=None,
        **kwargs,
    ):
        self._related_name = related_name
        self._related_query_name = related_query_name
        self._limit_choices_to = limi

field.model

    def check(self, **kwargs):
        return [
            *super().check(**kwargs),
            *self._check_related_name_is_valid(),
            *self._check_related_query_name_is_valid(),
            *self._check_relation_model_exists(),

t_choices_to
        super().__init__(**kwargs)

    @cached_property
    def related_model(self):
        # Can't cache this property until all the models are loaded.
        apps.check_models_ready()
        return self.remote_


_aliases=with_col_aliases)
        order_by = self.get_order_by()
        self.where, self.having, self.qualify = self.query.where.split_having_qualify(
            must_group_by=self.query.group_by is not None
        )
        extra_select = self.get_extra_select(order_by, self.select)
        self.has_extra_select = bool(extra_select)
        group_by = self.get_group_by(self.select + extra_select, order_by)
        return extra_select, order_by, group_by

    def get_group_by(self, select, order_by):

orrect".
        """
        # Some examples:
        #     SomeModel.objects.annotate(Count('somecol'))
        #     GROUP BY: all fields of the model
        #
        #    SomeModel.objects.values('name').annotate(Count('somecol'))
        #    GROUP B

      """
        Return a list of 2-tuples of form (sql, params).

        The logic of what exactly the GROUP BY clause contains is hard
        to describe in other words than "if it passes the test suite,
        then it is c


xpression"):
                yield from get_paths_from_expression(rhs)
        elif hasattr(child, "resolve_expression"):
            yield from get_paths_from_expression(child)

def get_child_with_renamed_prefix(prefix, replacement, child):
    from django.db.models.query import QuerySet

    if isinstance(child, Node):
        return rename_prefix_from_q(prefix, replacement, child)
    if isinstance(child, tuple):
        lhs, rhs = child
        if lhs.startswith(prefix + LOOKUP_SEP):
            lhs =

ild, F):
        child = child.copy()
        if child.name.startswith(prefix + LOOKUP_SEP):
            child.name = child.name.replace(prefix, replacement, 1)
    elif isinstance(child, QuerySet):
        # QuerySet may contain OuterRef() references whic

lhs.replace(prefix, replacement, 1)
        if not isinstance(rhs, F) and hasattr(rhs, "resolve_expression"):
            rhs = get_child_with_renamed_prefix(prefix, replacement, rhs)
        return lhs, rhs

    if isinstance(ch


# Connection types
AND = "AND"
OR = "OR"
XOR = "XOR"

class WhereNode(tree.Node):
    """
    An SQL WHERE clause.

    The class is tied to the Query class that created it (in order to create
    the correct SQL).

    A child is usually an expression producing boolean values. Most likely the
    expression is a Lookup instance.

    However, a child could also be any class with as_sql() and either
    relabeled_clone() method or relabel_aliases() and clone() methods and
    contains_aggregate attribute

hat
        should be included in the WHERE clause, one for those parts of self
        that must be included in the HAVING clause, and one for those parts
        that refer to window functions.
        """
        if not self.contains_aggregate and not s

.
    """

    default = AND
    resolved = False
    conditional = True

    def split_having_qualify(self, negated=False, must_group_by=False):
        """
        Return three possibly None nodes: one for those parts of self t


Exact,
    TupleGreaterThan,
    TupleGreaterThanOrEqual,
    TupleIn,
    TupleIsNull,
    TupleLessThan,
    TupleLessThanOrEqual,
)
from django.utils.functional import cached_property

class AttributeSetter:
    def __init__(self, name, value):
        setattr(self, name, value)

class CompositeAttribute:
    def __init__(self, field):
        self.field = field

    @property
    def attnames(self):
        return [field.attname for field in self.field.fields]

    def __get__(self, instance, cls=None

lues = (None,) * length

        if not isinstance(values, (list, tuple)):
            raise ValueError(f"{self.field.name!r} must be a list or a tuple.")
        if length != len(values):
            raise ValueError(f"{self.field.name!r} must have {lengt

):
        return tuple(getattr(instance, attname) for attname in self.attnames)

    def __set__(self, instance, values):
        attnames = self.attnames
        length = len(attnames)

        if values is None:
            va


l__ = ["GeneratedField"]

class GeneratedField(Field):
    generated = True
    db_returning = True

    _query = None
    output_field = None

    def __init__(self, *, expression, output_field, db_persist, **kwargs):
        if kwargs.setdefault("editable", False):
            raise ValueError("GeneratedField cannot be editable.")
        if not kwargs.setdefault("blank", True):
            raise ValueError("GeneratedField must be blank.")
        if kwargs.get("default", NOT_PROVIDED) is not NOT_PROVIDE

  if db_persist not in (True, False):
            raise ValueError("GeneratedField.db_persist must be True or False.")

        self.expression = expression
        self.output_field = output_field
        self.db_persist = db_persist
        self.has_null

D:
            raise ValueError("GeneratedField cannot have a default.")
        if kwargs.get("db_default", NOT_PROVIDED) is not NOT_PROVIDED:
            raise ValueError("GeneratedField cannot have a database default.")


"Value must be valid JSON."),
    }
    _default_hint = ("dict", "{}")

    def __init__(
        self,
        verbose_name=None,
        name=None,
        encoder=None,
        decoder=None,
        **kwargs,
    ):
        if encoder and not callable(encoder):
            raise ValueError("The encoder parameter must be a callable object.")
        if decoder and not callable(decoder):
            raise ValueError("The decoder parameter must be a callable object.")
        self.encoder = encoder

check_supported(databases))
        return errors

    def _check_supported(self, databases):
        errors = []
        for db in databases:
            if not router.allow_migrate_model(db, self.model):
                continue
            connection =

self.decoder = decoder
        super().__init__(verbose_name, name, **kwargs)

    def check(self, **kwargs):
        errors = super().check(**kwargs)
        databases = kwargs.get("databases") or []
        errors.extend(self._


django.db.models.fields import FloatField, IntegerField

__all__ = [
    "CumeDist",
    "DenseRank",
    "FirstValue",
    "Lag",
    "LastValue",
    "Lead",
    "NthValue",
    "Ntile",
    "PercentRank",
    "Rank",
    "RowNumber",
]

class CumeDist(Func):
    function = "CUME_DIST"
    output_field = FloatField()
    window_compatible = True

class DenseRank(Func):
    function = "DENSE_RANK"
    output_field = IntegerField()
    window_compatible = True

class FirstValue(Func):
    arity = 1
    f

se ValueError(
                "%s requires a non-null source expression." % self.__class__.__name__
            )
        if offset is None or offset <= 0:
            raise ValueError(
                "%s requires a positive integer for the offset."

unction = "FIRST_VALUE"
    window_compatible = True

class LagLeadFunction(Func):
    window_compatible = True

    def __init__(self, expression, offset=1, default=None, **extra):
        if expression is None:
            rai


ER

class MultiJoin(Exception):
    """
    Used by join construction code to indicate the point at which a
    multi-valued join was attempted (if the caller wants to treat that
    exceptionally).
    """

    def __init__(self, names_pos, path_with_names):
        self.level = names_pos
        # The path travelled, this includes the path to the multijoin.
        self.names_with_path = path_with_names

class Empty:
    pass

class Join:
    """
    Used by sql.Query and sql.SQLCompiler to generate JO

All entries in alias_map
    must be Join compatible by providing the following attributes and methods:
        - table_name (string)
        - table_alias (possible alias for the table, can be None)
        - join_type (can be None for those entries that

IN clauses into the
    FROM entry. For example, the SQL generated could be
        LEFT OUTER JOIN "sometable" T1
        ON ("othertable"."sometable_id" = "sometable"."id")

    This class is primarily used in Query.alias_map.


se
# attname. For example, this gets the primary key value of object "obj":
#
#     getattr(obj, opts.pk.attname)

def _empty(of_cls):
    new = Empty()
    new.__class__ = of_cls
    return new

def return_None():
    return None

@total_ordering
class Field(RegisterLookupMixin):
    """Base class for all field types"""

    # Designates whether empty strings fundamentally are allowed at the
    # database level.
    empty_strings_allowed = True
    empty_values = list(validators.EMPTY_VALUES)

    # Th

counter = 0
    auto_creation_counter = -1
    default_validators = []  # Default set of validators
    default_error_messages = {
        "invalid_choice": _("Value %(value)r is not a valid choice."),
        "null": _("This field cannot be null."),

ese track each time a Field instance is created. Used to retain order.
    # The auto_creation_counter is used for fields that Django implicitly
    # creates, creation_counter is used for all user-specified fields.
    creation_


odels.fields import UUIDField

class UUID4(Func):
    function = "UUIDV4"
    arity = 0
    output_field = UUIDField()

    def as_sql(self, compiler, connection, **extra_context):
        if connection.features.supports_uuid4_function:
            return super().as_sql(compiler, connection, **extra_context)
        raise NotSupportedError("UUID4 is not supported on this database backend.")

    def as_postgresql(self, compiler, connection, **extra_context):
        if connection.features.is_postgresql_18:

on, **extra_context):
        if not connection.features.supports_uuid4_function:
            if connection.mysql_is_mariadb:
                raise NotSupportedError("UUID4 requires MariaDB version 11.7 or later.")
            raise NotSupportedError("UUID

            return self.as_sql(compiler, connection, **extra_context)
        return self.as_sql(
            compiler, connection, function="GEN_RANDOM_UUID", **extra_context
        )

    def as_mysql(self, compiler, connecti


SIZE,
    NO_RESULTS,
    ROW_COUNT,
)
from django.db.models.sql.query import Query

__all__ = ["DeleteQuery", "UpdateQuery", "InsertQuery", "AggregateQuery"]

class DeleteQuery(Query):
    """A DELETE SQL query."""

    compiler = "SQLDeleteCompiler"

    def do_query(self, table, where, using):
        self.alias_map = {table: self.alias_map[table]}
        self.where = where
        return self.get_compiler(using).execute_sql(ROW_COUNT)

    def delete_batch(self, pk_list, using):
        """
        Se

leted = 0
        field = self.get_meta().pk
        for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
            self.clear_where()
            self.add_filter(
                f"{field.attname}__in",
                pk_list[offset : offset

t up and execute delete queries for all the objects in pk_list.

        More than one physical query may be executed if there are a
        lot of values in pk_list.
        """
        # number of objects deleted
        num_de


hecks
from django.utils.functional import cached_property

NOT_PROVIDED = object()

class FieldCacheMixin:
    """
    An API for working with the model's fields value cache.

    Subclasses must set self.cache_name to a unique entry for the cache -
    typically the field’s name.
    """

    @cached_property
    def cache_name(self):
        raise NotImplementedError

    def get_cached_value(self, instance, default=NOT_PROVIDED):
        try:
            return instance._state.fields_cache[self.cache_na

_cached_value(self, instance, value):
        instance._state.fields_cache[self.cache_name] = value

    def delete_cached_value(self, instance):
        del instance._state.fields_cache[self.cache_name]

class CheckFieldDefaultMixin:
    _default_hint =

me]
        except KeyError:
            if default is NOT_PROVIDED:
                raise
            return default

    def is_cached(self, instance):
        return self.cache_name in instance._state.fields_cache

    def set


eld = field
        self.storage = field.storage
        self._committed = True

    def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, "name"):
            return self.name == other.name
        return self.name == other

    def __hash__(self):
        return hash(self.name)

    def __bool__(self):
        return bool(self.name)

    # The standard F

                "The '%s' attribute has no file associated with it." % self.field.name
            )

    def _get_file(self):
        self._require_file()
        if getattr(self, "_file", None) is None:
            self._file = self.storage.open(self.nam

ile contains most of the necessary properties, but
    # FieldFiles can be instantiated without a name, so that needs to
    # be checked for here.

    def _require_file(self):
        if not self:
            raise ValueError(


urlsplit

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.urls import re_path
from django.views.static import serve

def static(prefix, view=serve, **kwargs):
    """
    Return a URL pattern for serving files in debug mode.

    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

gured("Empty static prefix not permitted")
    elif not settings.DEBUG or urlsplit(prefix).netloc:
        # No-op if not in debug mode or a non-local prefix.
        return []
    return [
        re_path(
            r"^%s(?P<path>.*)$" % re.escape(prefi

"""
    if not prefix:
        raise ImproperlyConfi


ated_objects
from django.db.models.query_utils import DeferredAttribute
from django.db.models.utils import AltersData, resolve_callables
from django.utils.functional import cached_property

class ForeignKeyDeferredAttribute(DeferredAttribute):
    def __set__(self, instance, value):
        if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(
            instance
        ):
            self.field.delete_cached_value(instance)
        instance.__dict__[self.field.attname] = value

tures.supports_over_clause:
            raise NotSupportedError(
                "Prefetching from a limited queryset is only supported on backends "
                "that support window functions."
            )
        low_mark, high_mark = queryset.quer

def _filter_prefetch_queryset(queryset, field_name, instances):
    predicate = Q(**{f"{field_name}__in": instances})
    db = queryset._db or DEFAULT_DB_ALIAS
    if queryset.query.is_sliced:
        if not connections[db].fea


om django.utils.functional import cached_property
from django.utils.hashable import make_hashable

from ..utils import get_blank_choice_label
from .mixins import FieldCacheMixin

class ForeignObjectRel(FieldCacheMixin):
    """
    Used by ForeignObject to store information about the relation.

    ``_meta.get_fields()`` returns this class to provide access to the field
    flags for the reverse relation.
    """

    # Field flags
    auto_created = True
    concrete = False
    editable = False
    is_re

lf,
        field,
        to,
        related_name=None,
        related_query_name=None,
        limit_choices_to=None,
        parent_link=False,
        on_delete=None,
    ):
        self.field = field
        self.model = to
        self.related_name

lation = True

    # Reverse relations are always nullable (Django can't enforce that a
    # foreign key on the related model points to this model).
    null = True
    empty_strings_allowed = False

    def __init__(
        se


      self.deep_deconstruct(obj.keywords),
            )
        elif isinstance(obj, COMPILED_REGEX_TYPE):
            return RegexObject(obj)
        elif isinstance(obj, type):
            # If this is a type that implements 'deconstruct' as an instance
            # method, avoid treating this as being deconstructible itself - see
            # #22951
            return obj
        elif hasattr(obj, "deconstruct"):
            deconstructed = obj.deconstruct()
            if isinstance(obj, models.Field

_deconstruct(value) for value in args],
                {key: self.deep_deconstruct(value) for key, value in kwargs.items()},
            )
        else:
            return obj

    def only_relation_agnostic_fields(self, fields):
        """
        Retur

):
                # we have a field which also returns a name
                deconstructed = deconstructed[1:]
            path, args, kwargs = deconstructed
            return (
                path,
                [self.deep


jango.db import DatabaseError

class AmbiguityError(Exception):
    """More than one migration matches a name prefix."""

    pass

class BadMigrationError(Exception):
    """There's a bad migration (unreadable/bad format/etc.)."""

    pass

class CircularDependencyError(Exception):
    """There's an impossible-to-resolve circular dependency."""

    pass

class InconsistentMigrationHistory(Exception):
    """An applied migration has some of its dependencies not applied."""

    pass

class InvalidBas

ror):
    """An attempt on a node is made that is not available in the graph."""

    def __init__(self, message, node, origin=None):
        self.message = message
        self.origin = origin
        self.node = node

    def __str__(self):
        retur

esError(ValueError):
    """A model's base classes can't be resolved."""

    pass

class IrreversibleError(RuntimeError):
    """An irreversible migration is about to be reversed."""

    pass

class NodeNotFoundError(LookupEr


= key
        self.children = set()
        self.parents = set()

    def __eq__(self, other):
        return self.key == other

    def __lt__(self, other):
        return self.key < other

    def __hash__(self):
        return hash(self.key)

    def __getitem__(self, item):
        return self.key[item]

    def __str__(self):
        return str(self.key)

    def __repr__(self):
        return "<%s: (%r, %r)>" % (self.__class__.__name__, self.key[0], self.key[1])

    def add_child(self, child):

moved, for example.)

    After the migration graph is processed, all dummy nodes should be removed.
    If there are any left, a nonexistent dependency error is raised.
    """

    def __init__(self, key, origin, error_message):
        super().__init__(

  self.children.add(child)

    def add_parent(self, parent):
        self.parents.add(parent)

class DummyNode(Node):
    """
    A node that doesn't correspond to a migration file on disk.
    (A squashed migration that was re


ations
    and you are returned a list of equal or shorter length - operations
    are merged into one if possible.

    For example, a CreateModel and an AddField can be optimized into a
    new CreateModel, and CreateModel and DeleteModel can be optimized into
    nothing.
    """

    def optimize(self, operations, app_label):
        """
        Main optimization entry point. Pass in a list of Operation instances,
        get out a new list of Operation instances.

        Unfortunately, due to the scop

stead, the optimizer looks at each
        individual operation and scans forwards in the list to see if there
        are any matches, stopping at boundaries - operations which can't
        be optimized over (RunSQL, operations on the same field/model, e

e of the optimization (two combinable
        operations might be separated by several hundred others), this can't be
        done as a peephole optimization with checks/output implemented on
        the Operations themselves; in


nctional import classproperty
from django.utils.timezone import now

from .exceptions import MigrationSchemaMissing

class MigrationRecorder:
    """
    Deal with storing migration records in the database.

    Because this table is actually itself used for dealing with model
    creation, it's the one thing we can't do normally via migrations.
    We manually handle table creation/schema updating (using schema backend)
    and then have a floating model to do queries with.

    If a migration is unapplie

gistryNotReady if installed apps import
        MigrationRecorder.
        """
        if cls._migration_class is None:

            class Migration(models.Model):
                app = models.CharField(max_length=255)
                name = models.CharFie

d its row is removed from the table. Having
    a row in the table always means a migration is applied.
    """

    _migration_class = None

    @classproperty
    def Migration(cls):
        """
        Lazy load to avoid AppRe


   and not isinstance(f.related_model, str)
        ):
            related_fields_models.add(f.model)
            related_models.append(f.related_model)
    # Reverse accessors of foreign keys to proxy models are attached to their
    # concrete proxied model.
    opts = m._meta
    if opts.proxy and m in related_fields_models:
        related_models.append(opts.concrete_model)
    return related_models

def get_related_models_tuples(model):
    """
    Return a list of typical (app_label, model_name) tupl

:
    """
    Return all models that have a direct or indirect relationship
    to the given model.

    Relationships are either defined by explicit relational fields, like
    ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another

es for all related
    models for the given model.
    """
    return {
        (rel_mod._meta.app_label, rel_mod._meta.model_name)
        for rel_mod in _get_related_models(model)
    }

def get_related_models_recursive(model)


django.utils.inspect import get_func_args
from django.utils.module_loading import module_dir
from django.utils.timezone import now

class OperationWriter:
    def __init__(self, operation, indentation=2):
        self.operation = operation
        self.buff = []
        self.indentation = indentation

    def serialize(self):
        def _write(_arg_name, _arg_value):
            if _arg_name in self.operation.serialization_expand_args and isinstance(
                _arg_value, (list, tuple, dict)

ring, key_imports = MigrationWriter.serialize(key)
                        arg_string, arg_imports = MigrationWriter.serialize(value)
                        args = arg_string.splitlines()
                        if len(args) > 1:

     ):
                if isinstance(_arg_value, dict):
                    self.feed("%s={" % _arg_name)
                    self.indent()
                    for key, value in _arg_value.items():
                        key_st


from .fields import AddField, AlterField, RemoveField, RenameField
from .models import (
    AddConstraint,
    AddIndex,
    AlterConstraint,
    AlterIndexTogether,
    AlterModelManagers,
    AlterModelOptions,
    AlterModelTable,
    AlterModelTableComment,
    AlterOrderWithRespectTo,
    AlterUniqueTogether,
    CreateModel,
    DeleteModel,
    RemoveConstraint,
    RemoveIndex,
    RenameIndex,
    RenameModel,
)
from .special import RunPython, RunSQL, SeparateDatabaseAndState

__all__ = [
    "Cre

ex",
    "AddField",
    "RemoveField",
    "AlterField",
    "RenameField",
    "AddConstraint",
    "RemoveConstraint",
    "AlterConstraint",
    "SeparateDatabaseAndState",
    "RunSQL",
    "RunPython",
    "AlterOrderWithRespectTo",
    "AlterModelMa

ateModel",
    "DeleteModel",
    "AlterModelTable",
    "AlterModelTableComment",
    "AlterUniqueTogether",
    "RenameModel",
    "AlterIndexTogether",
    "AlterModelOptions",
    "AddIndex",
    "RemoveIndex",
    "RenameInd


ns or {}
        self.bases = bases or (models.Model,)
        self.managers = managers or []
        super().__init__(name)
        # Sanity-check that there are no duplicated field names, bases, or
        # manager names
        _check_for_duplicates("fields", (name for name, _ in self.fields))
        _check_for_duplicates(
            "bases",
            (
                (
                    base._meta.label_lower
                    if hasattr(base, "_meta")
                    else base.lower() if

 kwargs = {
            "name": self.name,
            "fields": self.fields,
        }
        if self.options:
            kwargs["options"] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs["bases"] = self.bases

 isinstance(base, str) else base
                )
                for base in self.bases
            ),
        )
        _check_for_duplicates("managers", (name for name, _ in self.managers))

    def deconstruct(self):


templates.

The django.template namespace contains two independent subsystems:

1. Multiple Template Engines: support for pluggable template backends,
   built-in backends and backend-independent APIs
2. Django Template Language: Django's own template engine, including its
   built-in loaders, context processors, tags and filters.

Ideally these subsystems would be implemented in distinct packages. However
keeping them together made the implementation of Multiple Template Engines
less disruptive .

Here's a

late.context
- django.template.context_processors
- django.template.loaders.*
- django.template.debug
- django.template.defaultfilters
- django.template.defaulttags
- django.template.engine
- django.template.loader_tags
- django.template.smartif

Shared:

 breakdown of which modules belong to which subsystem.

Multiple Template Engines:

- django.template.backends.*
- django.template.loader
- django.template.response

Django Template Language:

- django.template.base
- django.temp


= template.Template(s)

(t is now a compiled template, and its render() method can be called multiple
times with multiple contexts)

>>> c = template.Context({'test':True, 'varvalue': 'Hello'})
>>> t.render(c)
'
Hello
'
>>> c = template.Context({'test':False, 'varvalue': 'Hello'})
>>> t.render(c)
''
"""

import inspect
import logging
import re
import warnings
from enum import Enum

from django.template.context import BaseContext
from django.utils.deprecation import RemovedIn

zy_re_compile
from django.utils.safestring import SafeData, SafeString, mark_safe
from django.utils.text import get_text_list, smart_split, unescape_string_literal
from django.utils.timezone import template_localtime
from django.utils.translation import ge

Django70Warning, django_file_prefixes
from django.utils.formats import localize
from django.utils.html import conditional_escape
from django.utils.inspect import getfullargspec, signature
from django.utils.regex_helper import _la


rgs)

        context.dicts.append(self)
        self.context = context

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        self.context.pop()

class BaseContext:
    def __init__(self, dict_=None):
        self._reset_dicts(dict_)

    def _reset_dicts(self, value=None):
        builtins = {"True": True, "False": False, "None": None}
        self.dicts = [builtins]
        if isinstance(value, BaseContext):
            self.dicts += value.dicts[1:]
        elif

cts = self.dicts[:]
        return duplicate

    def __repr__(self):
        return repr(self.dicts)

    def __iter__(self):
        return reversed(self.dicts)

    def push(self, *args, **kwargs):
        dicts = []
        for d in args:
            i

value is not None:
            self.dicts.append(value)

    def __copy__(self):
        duplicate = BaseContext()
        duplicate.__class__ = self.__class__
        duplicate.__dict__ = copy(self.__dict__)
        duplicate.di


t (
    Exact,
    GreaterThan,
    GreaterThanOrEqual,
    In,
    IsNull,
    LessThan,
    LessThanOrEqual,
)

def get_normalized_value(value, lhs):
    from django.db.models import Model

    if isinstance(value, Model):
        if not value._is_pk_set():
            raise ValueError("Model instances passed to related filters must be saved.")
        value_list = []
        sources = composite.unnest(lhs.output_field.path_infos[-1].target_fields)
        for source in sources:
            while not isi

_list.append(getattr(value, source.attname))
            except AttributeError:
                # A case like
                # Restaurant.objects.filter(place=restaurant_instance), where
                # place is a OneToOneField and the primary key of Re

nstance(value, source.model) and source.remote_field:
                source = source.remote_field.model._meta.get_field(
                    source.remote_field.field_name
                )
            try:
                value


dels.sql import Query
from django.db.models.sql.where import AND, OR, WhereNode

class Tuple(Func):
    allows_composite_expressions = True
    function = ""
    output_field = models.Field()

    def __len__(self):
        return len(self.source_expressions)

    def __iter__(self):
        return iter(self.source_expressions)

    def as_sqlite(self, compiler, connection):
        if connection.get_database_version() < (3, 37) and isinstance(
            first_expr := self.source_expressions[0], Tuple

return self.as_sql(compiler, connection)

class TupleLookupMixin:
    allows_composite_expressions = True

    def get_prep_lookup(self):
        if self.rhs_is_direct_value():
            self.check_rhs_is_tuple_or_list()
            self.check_rhs_lengt

      ):
            first_expr = first_expr.copy()
            first_expr.function = "VALUES"
            return Tuple(first_expr, *self.source_expressions[1:]).as_sql(
                compiler, connection
            )


those directories, and open and
    read the Python files, looking for a class called Migration, which should
    inherit from django.db.migrations.Migration. See
    django.db.migrations.migration for what that looks like.

    Some migrations will be marked as "replacing" another set of migrations.
    These are loaded into a separate set of migrations away from the main ones.
    If all the migrations they replace are either unapplied or missing from
    disk, then they are injected into the main set, re

probably fine. We're already not just operating
    in memory.
    """

    def __init__(
        self,
        connection,
        load=True,
        ignore_no_migrations=False,
        replace_migrations=True,
    ):
        self.connection = connection

placing the named
    migrations. Any dependency pointers to the replaced migrations are
    re-pointed to the new migration.

    This does mean that this class MUST also talk to the database as well as
    to disk, but this is


s base class has a built-in noninteractive mode, but the
    interactive subclass is what the command-line arguments will use.
    """

    def __init__(self, defaults=None, specified_apps=None, dry_run=None):
        self.defaults = defaults or {}
        self.specified_apps = specified_apps or set()
        self.dry_run = dry_run

    def ask_initial(self, app_label):
        """Should we create an initial migration for the app?"""
        # If it was specified on the command line, definitely true

plate will have these; the Python
        # file check will ensure we skip South ones.
        try:
            app_config = apps.get_app_config(app_label)
        except LookupError:  # It's a fake app.
            return self.defaults.get("ask_initial",

 if app_label in self.specified_apps:
            return True
        # Otherwise, we look to see if it has a migrations module
        # without any Python files in it, apart from __init__.py.
        # Apps from the new app tem


ort RECURSIVE_RELATIONSHIP_CONSTANT

FieldReference = namedtuple("FieldReference", "to through")

COMPILED_REGEX_TYPE = type(re.compile(""))

class RegexObject:
    def __init__(self, obj):
        self.pattern = obj.pattern
        self.flags = obj.flags

    def __eq__(self, other):
        if not isinstance(other, RegexObject):
            return NotImplemented
        return self.pattern == other.pattern and self.flags == other.flags

def get_migration_name_timestamp():
    return datetime.datetime.no

scope of recursive and
    unscoped model relationship.
    """
    if isinstance(model, str):
        if model == RECURSIVE_RELATIONSHIP_CONSTANT:
            if app_label is None or model_name is None:
                raise TypeError(

w().strftime("%Y%m%d_%H%M")

def resolve_relation(model, app_label=None, model_name=None):
    """
    Turn a model class or model reference string and return a model tuple.

    app_label and model_name are used to resolve the


eld = field

    @cached_property
    def model_name_lower(self):
        return self.model_name.lower()

    @cached_property
    def name_lower(self):
        return self.name.lower()

    def is_same_model_operation(self, operation):
        return self.model_name_lower == operation.model_name_lower

    def is_same_field_operation(self, operation):
        return (
            self.is_same_model_operation(operation)
            and self.name_lower == operation.name_lower
        )

    def references_mo

       (app_label, self.model_name_lower),
                    self.field,
                    (app_label, name_lower),
                )
            )
        return False

    def references_field(self, model_name, name, app_label):
        model_name_lo

del(self, name, app_label):
        name_lower = name.lower()
        if name_lower == self.model_name_lower:
            return True
        if self.field:
            return bool(
                field_references(


rt receiver
from django.template import engines
from django.template.backends.django import DjangoTemplates
from django.utils._os import to_path
from django.utils.autoreload import autoreload_started, file_changed, is_django_path

def get_template_directories():
    # Iterate through each template backend and find
    # any template_loader that has a 'get_dirs' method.
    # Collect the directories, filtering out Django templates.
    cwd = Path.cwd()
    items = set()
    for backend in engines.all():

attr(loader, "get_dirs"):
                continue
            items.update(
                cwd / to_path(directory)
                for directory in loader.get_dirs()
                if directory and not is_django_path(directory)
            )
    return

     if not isinstance(backend, DjangoTemplates):
            continue

        items.update(cwd / to_path(dir) for dir in backend.engine.dirs if dir)

        for loader in backend.engine.template_loaders:
            if not has


aries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.

These are referenced from the 'context_processors' option of the configuration
of a DjangoTemplates backend and used by RequestContext.
"""

import itertools

from django.conf import settings
from django.middleware.csp import get_nonce
from django.middleware.csrf import get_token
from django.utils.csp import CONTEXT_KEY as CSP_CONTEXT_KEY
from django.utils

 """

    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an

.functional import SimpleLazyObject, lazy

def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED'
    if it has not been provided by either a view decorator or the middleware


     - operations: A list of Operation instances, probably from
       django.db.migrations.operations
     - dependencies: A list of tuples of (app_path, migration_name)
     - run_before: A list of tuples of (app_path, migration_name)
     - replaces: A list of migration_names

    Note that all migrations come out of migrations and into the Loader or
    Graph as instances, having been initialized with their app label and name.
    """

    # Operations to apply during this migration, in order.
    ope

 migration added to their dependencies). Useful to make third-party
    # apps' migrations run after your AUTH_USER replacement, for example.
    run_before = []

    # Migration names in this app that this migration replaces. If this is
    # non-empty, t

rations = []

    # Other migrations that should be run before this migration.
    # Should be a list of (app, migration_name).
    dependencies = []

    # Other migrations that should be run after this one (i.e. have
    # this


ON = "p"
    SQL = "s"
    MIXED = "?"

class Operation:
    """
    Base class for migration operations.

    It's responsible for both mutating the in-memory model state
    (see db/migrations/state.py) to represent what it performs, as well
    as actually performing it against a live database.

    Note that some operations won't modify memory state at all (e.g. data
    copying operations), and some will need their modifications to be
    optionally specified by the user (e.g. custom Python code snipp

  reversible = True

    # Can this migration be represented as SQL? (things like RunPython cannot)
    reduces_to_sql = True

    # Should this operation be forced as atomic even on backends with no
    # DDL transaction support (i.e., does it have no DDL

ets)

    Due to the way this class deals with deconstruction, it should be
    considered immutable.
    """

    # If this migration can be run in reverse.
    # Some operations are impossible to reverse, like deleting data.


ic
from django.utils.text import slugify as _slugify
from django.utils.text import wrap
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext

from .base import VARIABLE_ATTRIBUTE_SEPARATOR
from .library import Library

register = Library()

#######################
# STRING DECORATOR    #
#######################

def stringfilter(func):
    """
    Decorator for filters which should only receive strings. The object
    passed as the first positional

unwrap(func), "is_safe", False):
            result = mark_safe(result)
        return result

    return _dec

###################
# STRINGS         #
###################

@register.filter(is_safe=True)
@stringfilter
def addslashes(value):
    """
    A

 argument will be converted to a string.
    """

    @wraps(func)
    def _dec(first, *args, **kwargs):
        first = str(first)
        result = func(first, *args, **kwargs)
        if isinstance(first, SafeData) and getattr(


 file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j F Y"  # 31 janvier 2024
TIME_FORMAT = "H\xa0\\h\xa0i"  # 13 h 40
DATETIME_FORMAT = "j F Y, H\xa0\\h\xa0i"  # 31 janvier 2024, 13 h 40
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "Y-m-d"
SHORT_DATETIME_FORMAT = "Y-m-d H\xa0\\h\xa0i"
FIRST_DAY_OF_WEEK = 0  # Dimanche

#

 The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%Y-%m-%d",  # '2006-05-15'
    "%y-%m-%d",  # '06-05-1


rt Template, TemplateDoesNotExist

class Loader:
    def __init__(self, engine):
        self.engine = engine

    def get_template(self, template_name, skip=None):
        """
        Call self.get_template_sources() and return a Template object for
        the first template matching template_name. If skip is provided, ignore
        template origins in skip. This is used to avoid recursion during
        template extending.
        """
        tried = []

        for origin in self.get_template_sources(

in)
            except TemplateDoesNotExist:
                tried.append((origin, "Source does not exist"))
                continue
            else:
                return Template(
                    contents,
                    origin,

template_name):
            if skip is not None and origin in skip:
                tried.append((origin, "Skipped to avoid recursion"))
                continue

            try:
                contents = self.get_contents(orig


for loading templates from the filesystem.
"""

from django.core.exceptions import SuspiciousFileOperation
from django.template import Origin, TemplateDoesNotExist
from django.utils._os import safe_join

from .base import Loader as BaseLoader

class Loader(BaseLoader):
    def __init__(self, engine, dirs=None):
        super().__init__(engine)
        self.dirs = dirs

    def get_dirs(self):
        return self.dirs if self.dirs is not None else self.engine.dirs

    def get_contents(self, origin):

elf, template_name):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set

  try:
            with open(origin.name, encoding=self.engine.file_charset) as fp:
                return fp.read()
        except FileNotFoundError:
            raise TemplateDoesNotExist(origin)

    def get_template_sources(s


nit Test framework."""

from django.test.client import AsyncClient, AsyncRequestFactory, Client, RequestFactory
from django.test.testcases import (
    LiveServerTestCase,
    SimpleTestCase,
    TestCase,
    TransactionTestCase,
    skipIfDBFeature,
    skipUnlessAnyDBFeature,
    skipUnlessDBFeature,
)
from django.test.utils import (
    ignore_warnings,
    modify_settings,
    override_settings,
    override_system_checks,
    tag,
)

__all__ = [
    "AsyncClient",
    "AsyncRequestFactory",
    "Clien

actionTestCase",
    "SimpleTestCase",
    "LiveServerTestCase",
    "skipIfDBFeature",
    "skipUnlessAnyDBFeature",
    "skipUnlessDBFeature",
    "ignore_warnings",
    "modify_settings",
    "override_settings",
    "override_system_checks",
    "tag",

t",
    "RequestFactory",
    "TestCase",
    "Trans


ecord.args["sql"] = formatted_sql = format_sql(sql)

            if extra_sql := getattr(record, "sql", None):
                if extra_sql == sql:
                    record.sql = formatted_sql
                else:
                    record.sql = format_sql(extra_sql)

        return super().format(record)

class DebugSQLTextTestResult(unittest.TextTestResult):
    def __init__(self, stream, descriptions, verbosity):
        self.logger = logging.getLogger("django.db.backends")
        self.logger.setLe

).
            sql = ""
        else:
            self.handler.stream.seek(0)
            sql = self.handler.stream.read()
        return sql

    def startTest(self, test):
        self.handler = logging.StreamHandler(io.StringIO())
        self.handler.s

vel(logging.DEBUG)
        self.handler = None
        super().__init__(stream, descriptions, verbosity)

    def _read_logger_stream(self):
        if self.handler is None:
            # Error before tests e.g. in setUpTestData(


re.signals import setting_changed
from django.db import connections, router
from django.db.utils import ConnectionRouter
from django.dispatch import Signal, receiver
from django.utils import timezone
from django.utils.formats import FORMAT_SETTINGS, reset_format_cache
from django.utils.functional import empty
from django.utils.log import configure_logging

template_rendered = Signal()

# Most setting_changed receivers are supposed to be added below,
# except for cases where the receiver is related to a cont

:
        from django.core.cache import caches, close_caches

        close_caches()
        caches._settings = caches.settings = caches.configure_settings(None)
        caches._connections = Local()

@receiver(setting_changed)
def update_installed_apps(*

rib app.

# Settings that may not work well when using 'override_settings' (#19031)
COMPLEX_OVERRIDE_SETTINGS = {"DATABASES"}

@receiver(setting_changed)
def clear_cache_handlers(*, setting, **kwargs):
    if setting == "CACHES"


,
    and ones that will be used for the state change. This allows operations
    that don't support state change to have it applied, or have operations
    that affect the state or not the database, or so on.
    """

    category = OperationCategory.MIXED
    serialization_expand_args = ["database_operations", "state_operations"]

    def __init__(self, database_operations=None, state_operations=None):
        self.database_operations = database_operations or []
        self.state_operations = state_opera

rations"] = self.state_operations
        return (self.__class__.__qualname__, [], kwargs)

    def state_forwards(self, app_label, state):
        for state_operation in self.state_operations:
            state_operation.state_forwards(app_label, state)

tions or []

    def deconstruct(self):
        kwargs = {}
        if self.database_operations:
            kwargs["database_operations"] = self.database_operations
        if self.state_operations:
            kwargs["state_ope


ate
from .context import Context, _builtin_context_processors
from .exceptions import TemplateDoesNotExist
from .library import import_library

class Engine:
    default_builtins = [
        "django.template.defaulttags",
        "django.template.defaultfilters",
        "django.template.loader_tags",
    ]

    def __init__(
        self,
        dirs=None,
        app_dirs=False,
        context_processors=None,
        debug=False,
        loaders=None,
        string_if_invalid="",
        file_charset

 is None:
            loaders = ["django.template.loaders.filesystem.Loader"]
            if app_dirs:
                loaders += ["django.template.loaders.app_directories.Loader"]
            loaders = [("django.template.loaders.cached.Loader", loaders)]

="utf-8",
        libraries=None,
        builtins=None,
        autoescape=True,
    ):
        if dirs is None:
            dirs = []
        if context_processors is None:
            context_processors = []
        if loaders


r registering template tags and filters. Compiled filter and
    template tag functions are stored in the filters and tags attributes.
    The filter, simple_tag, and inclusion_tag methods provide a convenient
    way to register callables as tags.
    """

    def __init__(self):
        self.filters = {}
        self.tags = {}

    def tag(self, name=None, compile_function=None):
        if name is None and compile_function is None:
            # @register.tag()
            return self.tag_function

@register.tag(name='somename')
                def dec(func):
                    return self.tag(name, func)

                return dec
        elif name is not None and compile_function is not None:
            # register.tag('somename', somefunc)

  elif name is not None and compile_function is None:
            if callable(name):
                # @register.tag
                return self.tag_function(name)
            else:
                # @register.tag('somename') or


__repr__(self):
        return f"<{self.__class__.__qualname__}: blocks={self.blocks!r}>"

    def add_blocks(self, blocks):
        for name, block in blocks.items():
            self.blocks[name].insert(0, block)

    def pop(self, name):
        try:
            return self.blocks[name].pop()
        except IndexError:
            return None

    def push(self, name, block):
        self.blocks[name].append(block)

    def get_block(self, name):
        try:
            return self.blocks[name][-1]

(self):
        return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist)

    def render(self, context):
        block_context = context.render_context.get(BLOCK_CONTEXT_KEY)
        with context.push():
            if block_context is None:

    except IndexError:
            return None

class BlockNode(Node):
    def __init__(self, name, nodelist, parent=None):
        self.name = name
        self.nodelist = nodelist
        self.parent = parent

    def __repr__


enotation
# 'bp' = binding power (left = lbp, right = rbp)

class TokenBase:
    """
    Base class for operators and literals, mainly for debugging and for
    throwing syntax errors.
    """

    id = None  # node/token type name
    value = None  # used by literals
    first = second = None  # used by tree nodes

    def nud(self, parser):
        # Null denotation - called in prefix context
        raise parser.error_class(
            "Not expecting '%s' in this position in if tag." % self.id

       """
        Return what to display in error messages for this node
        """
        return self.id

    def __repr__(self):
        out = [str(x) for x in [self.id, self.first, self.second] if x is not None]
        return "(" + " ".join(out) + "

)

    def led(self, left, parser):
        # Left denotation - called in infix context
        raise parser.error_class(
            "Not expecting '%s' as infix operator in if tag." % self.id
        )

    def display(self):


ured, SuspiciousFileOperation
from django.template.utils import get_app_template_dirs
from django.utils._os import safe_join
from django.utils.functional import cached_property

class BaseEngine:
    # Core methods: engines have to provide their own implementation
    #               (except for from_string which is optional).

    def __init__(self, params):
        """
        Initialize the template engine.

        `params` is a dict of configuration settings.
        """
        params = params.copy()

}".format(", ".join(params))
            )

    def check(self, **kwargs):
        return []

    @property
    def app_dirname(self):
        raise ImproperlyConfigured(
            "{} doesn't support loading templates from installed "
            "appli

        self.name = params.pop("NAME")
        self.dirs = list(params.pop("DIRS"))
        self.app_dirs = params.pop("APP_DIRS")
        if params:
            raise ImproperlyConfigured(
                "Unknown parameters: {


r, Warning
from django.template import TemplateDoesNotExist
from django.template.context import make_context
from django.template.engine import Engine
from django.template.library import InvalidTemplateLibrary

from .base import BaseEngine

class DjangoTemplates(BaseEngine):
    app_dirname = "templates"

    def __init__(self, params):
        params = params.copy()
        options = params.pop("OPTIONS").copy()
        options.setdefault("autoescape", True)
        options.setdefault("debug", settings.DE

ne = Engine(self.dirs, self.app_dirs, **options)

    def check(self, **kwargs):
        return [
            *self._check_string_if_invalid_is_string(),
            *self._check_for_template_tags_with_the_same_name(),
        ]

    def _check_string_if_i

BUG)
        options.setdefault("file_charset", "utf-8")
        libraries = options.get("libraries", {})
        options["libraries"] = self.get_templatetag_libraries(libraries)
        super().__init__(params)
        self.engi


ssertEqual(
            executed,
            self.num,
            "%d queries executed, %d expected\nCaptured queries were:\n%s"
            % (
                executed,
                self.num,
                "\n".join(
                    "%d. %s" % (i, query["sql"])
                    for i, query in enumerate(self.captured_queries, start=1)
                ),
            ),
        )

class _AssertTemplateUsedContext:
    def __init__(self, test_case, template_name, msg_prefix="", count=None):

mplate_render(self, sender, signal, template, context, **kwargs):
        self.rendered_templates.append(template)
        self.context.append(copy(context))

    @property
    def rendered_template_names(self):
        return [
            (

      self.test_case = test_case
        self.template_name = template_name
        self.msg_prefix = msg_prefix
        self.count = count

        self.rendered_templates = []
        self.context = ContextList()

    def on_te


erlyConfigured
from django.utils.deprecation import (
    RemovedInDjango70Warning,
    django_file_prefixes,
    warn_about_external_use,
)
from django.utils.functional import LazyObject, empty

ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
DEFAULT_STORAGE_ALIAS = "default"
STATICFILES_STORAGE_ALIAS = "staticfiles"

# RemovedInDjango70Warning.
USE_BLANK_CHOICE_DASH_DEPRECATED_MSG = (
    "The USE_BLANK_CHOICE_DASH setting is deprecated. If you wish to define "
    "your own default blank choice label, ov

SSWORD",
    "EMAIL_HOST_USER",
    "EMAIL_PORT",
    "EMAIL_SSL_CERTFILE",
    "EMAIL_SSL_KEYFILE",
    "EMAIL_TIMEOUT",
    "EMAIL_USE_SSL",
    "EMAIL_USE_TLS",
}
EMAIL_SETTING_DEPRECATED_MSG = (
    "The {name} setting is deprecated. Migrate to MAILERS

erride "
    "django.db.models.fields.BLANK_CHOICE_LABEL in your app's ready() method."
)

# RemovedInDjango70Warning.
DEPRECATED_EMAIL_SETTINGS = {
    "EMAIL_BACKEND",
    "EMAIL_FILE_PATH",
    "EMAIL_HOST",
    "EMAIL_HOST_PA


is true
#   * Receive x-headers
INTERNAL_IPS = []

# Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS = []

# Local time zone for this installation. All choices can be found here:
# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE = "America/Chicago"

# If you set this

ed in LANGUAGES (below), the project must
# provide the necessary translations and locale definitions.
LANGUAGE_CODE = "en-us"

# Languages we provide translations for, out of the box.
LANGUAGES = [
    ("af", gettext_noop("Afrikaans")),
    ("ar", gettext

to True, Django will use timezone-aware datetimes.
USE_TZ = True

# Language code for this installation. Valid choices can be found here:
# https://www.iana.org/assignments/language-subtag-registry/
# If LANGUAGE_CODE is not list


from them in order, caching the result.
"""

import hashlib

from django.template import TemplateDoesNotExist
from django.template.backends.django import copy_exception

from .base import Loader as BaseLoader

class Loader(BaseLoader):
    def __init__(self, engine, loaders):
        self.get_template_cache = {}
        self.loaders = engine.get_template_loaders(loaders)
        super().__init__(engine)

    def get_dirs(self):
        for loader in self.loaders:
            if hasattr(loader, "get_dirs"):

hat gives this loader its name. Often many of the
        templates attempted will be missing, so memory use is of concern here.
        To keep it in check, caching behavior is a little complicated when a
        template is not found. See ticket #26306 f

                yield from loader.get_dirs()

    def get_contents(self, origin):
        return origin.loader.get_contents(origin)

    def get_template(self, template_name, skip=None):
        """
        Perform the caching t


 U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020
# SPACE.
# https://infra.spec.whatwg.org/#ascii-whitespace
ASCII_WHITESPACE = _lazy_re_compile(r"[\t\n\f\r ]+")

# https://html.spec.whatwg.org/#attributes-3
BOOLEAN_ATTRIBUTES = {
    "allowfullscreen",
    "async",
    "autofocus",
    "autoplay",
    "checked",
    "controls",
    "default",
    "defer ",
    "disabled",
    "formnovalidate",
    "hidden",
    "ismap",
    "itemscope",
    "loop",
    "multiple",
    "muted",
    "nomodule",
    "no

b(" ", string)

def normalize_attributes(attributes):
    normalized = []
    for name, value in attributes:
        if name == "class" and value:
            # Special case handling of 'class' attribute, so that comparisons
            # of DOM instances

validate",
    "open",
    "playsinline",
    "readonly",
    "required",
    "reversed",
    "selected",
    # Attributes for deprecated tags.
    "truespeed",
}

def normalize_whitespace(string):
    return ASCII_WHITESPACE.su


wards?).
        """
        plan = []
        if clean_start:
            applied = {}
        else:
            applied = dict(self.loader.applied_migrations)
        for target in targets:
            # If the target is (app_label, None), that means unmigrate
            # everything
            if target[1] is None:
                for root in self.loader.graph.root_nodes():
                    if root[0] == target[0]:
                        for migration in self.loader.graph.backwards_plan(root):

g, it's likely a replaced migration.
            # Reload the graph without replacements.
            elif (
                self.loader.replace_migrations
                and target not in self.loader.graph.node_map
            ):
                self.loa

                        if migration in applied:
                                plan.append((self.loader.graph.nodes[migration], True))
                                applied.pop(migration)
            # If the target is missin


ule contains generic exceptions used by template backends. Although,
due to historical reasons, the Django template language also internally uses
these exceptions, other exceptions specific to the DTL should not be added
here.
"""

class TemplateDoesNotExist(Exception):
    """
    The exception used when a template does not exist. Optional arguments:

    backend
        The template backend class used when raising this exception.

    tried
        A list of sources that were tried when finding the templ

list of intermediate TemplateDoesNotExist exceptions. This is used to
        encapsulate multiple exceptions when loading templates from multiple
        engines.
    """

    def __init__(self, msg, tried=None, backend=None, chain=None):
        self.bac

ate. This
        is formatted as a list of tuples containing (origin, status), where
        origin is an Origin object or duck type and status is a string with the
        reason the template wasn't found.

    chain
        A


rs = ["template_name", "context_data", "_post_render_callbacks"]

    def __init__(
        self,
        template,
        context=None,
        content_type=None,
        status=None,
        charset=None,
        using=None,
        headers=None,
    ):
        # It would seem obvious to call these next two members 'template' and
        # 'context', but those names are reserved as part of the test Client
        # API. To avoid the name collision, we use different names.
        self.template_name = tem

Response. It's defined in the base class
        # to minimize code duplication.
        # It's called self._request because self.request gets overwritten by
        # django.test.client.Client. Unlike template_name and context_data,
        # _request sho

plate
        self.context_data = context

        self.using = using

        self._post_render_callbacks = []

        # _request stores the current request object in subclasses that know
        # about requests, like Template


o.core.exceptions import ImproperlyConfigured
from django.template import Origin, TemplateDoesNotExist
from django.utils.html import conditional_escape

from .base import BaseEngine
from .utils import csrf_input_lazy, csrf_token_lazy

class TemplateStrings(BaseEngine):
    app_dirname = "template_strings"

    def __init__(self, params):
        params = params.copy()
        options = params.pop("OPTIONS").copy()
        if options:
            raise ImproperlyConfigured("Unknown options: {}".format(", ".

ter_template_filenames(template_name):
            try:
                with open(template_file, encoding="utf-8") as fp:
                    template_code = fp.read()
            except FileNotFoundError:
                tried.append(

join(options)))
        super().__init__(params)

    def from_string(self, template_code):
        return Template(template_code)

    def get_template(self, template_name):
        tried = []
        for template_file in self.i


Template
from django.test.signals import template_rendered
from django.urls import get_script_prefix, set_script_prefix
from django.utils.translation import deactivate
from django.utils.version import PYPY

try:
    import jinja2
except ImportError:
    jinja2 = None

__all__ = (
    "Approximate",
    "ContextList",
    "isolate_lru_cache",
    "garbage_collect",
    "get_runner",
    "CaptureQueriesContext",
    "ignore_warnings",
    "isolate_apps",
    "modify_settings",
    "override_settings",
    "o

, val, places=7):
        self.val = val
        self.places = places

    def __repr__(self):
        return repr(self.val)

    def __eq__(self, other):
        return self.val == other or round(abs(self.val - other), self.places) == 0

class ContextLis

verride_system_checks",
    "tag",
    "requires_tz_support",
    "setup_databases",
    "setup_test_environment",
    "teardown_test_environment",
)

TZ_SUPPORT = hasattr(time, "tzset")

class Approximate:
    def __init__(self


RMANENTLY,
        HTTPStatus.FOUND,
        HTTPStatus.SEE_OTHER,
        HTTPStatus.TEMPORARY_REDIRECT,
        HTTPStatus.PERMANENT_REDIRECT,
    ]
)

class RedirectCycleError(Exception):
    """The test client has been asked to follow a redirect loop."""

    def __init__(self, message, last_response):
        super().__init__(message)
        self.last_response = last_response
        self.redirect_chain = last_response.redirect_chain

class FakePayload(IOBase):
    """
    A wrapper around BytesIO t

l life.
    """

    def __init__(self, initial_bytes=None):
        self.__content = BytesIO()
        self.__len = 0
        self.read_started = False
        if initial_bytes is not None:
            self.write(initial_bytes)

    def __len__(self):

hat restricts what can be read since data from
    the network can't be sought and cannot be read outside of its content
    length. This makes sure that views can't do anything under the test client
    that wouldn't work in rea


ls.deletion import DatabaseOnDelete
from django.utils.functional import LazyObject, Promise
from django.utils.version import get_docs_version

FUNCTION_TYPES = (types.FunctionType, types.BuiltinFunctionType, types.MethodType)

if isinstance(functools._lru_cache_wrapper, type):
    # When using CPython's _functools C module, LRU cache function decorators
    # present as a class and not a function, so add that class to the list of
    # function types. In the pure Python implementation and PyPy they present

NotImplementedError(
            "Subclasses of BaseSerializer must implement the serialize() method."
        )

class BaseSequenceSerializer(BaseSerializer):
    def _format(self):
        raise NotImplementedError(
            "Subclasses of BaseSequen

    # as normal functions which are already handled.
    FUNCTION_TYPES += (functools._lru_cache_wrapper,)

class BaseSerializer:
    def __init__(self, value):
        self.value = value

    def serialize(self):
        raise


s
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_string

class InvalidTemplateEngineError(ImproperlyConfigured):
    pass

class EngineHandler:
    def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        se

lates:
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl["BACKEND"].rsplit(".", 2)[-2]
            except Exception

lf._engines = {}

    @cached_property
    def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        templates = {}
        backend_names = []
        for tpl in self._temp


 functools

from django.conf import settings
from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path
from django.views.i18n import set_language

def i18n_patterns(*urls, prefix_default_language=True):
    """
    Add the language code prefix to every URL pattern within this function.
    This may only be used in the root URLconf, not in an included URLconf.
    """
    if not settings.USE_I18N:
        return list(urls)
    return [
        URLResolver(
            LocalePrefixPattern(

erns() (LocalePrefixPattern) is used in the URLconf,
        `True` if the default language should be prefixed
    )
    """
    for url_pattern in get_resolver(urlconf).url_patterns:
        if isinstance(url_pattern.pattern, LocalePrefixPattern):

prefix_default_language=prefix_default_language),
            list(urls),
        )
    ]

@functools.cache
def is_language_prefix_patterns_used(urlconf):
    """
    Return a tuple of two booleans: (
        `True` if i18n_patt


tCase)):
    # List of browsers to dynamically create test classes for.
    browsers = []
    # A selenium hub URL to test against.
    selenium_hub = None
    # The external host Selenium Hub can reach.
    external_host = None
    # Sentinel value to differentiate browser-specific instances.
    browser = None
    # Run browsers in headless mode.
    headless = False

    def __new__(cls, name, bases, attrs):
        """
        Dynamically create new classes and add them to the test module when
        m

 # it.
        if test_class.browser or not any(
            name.startswith("test") and callable(value) for name, value in attrs.items()
        ):
            return test_class
        elif test_class.browsers:
            # Reuse the created test class

ultiple browsers specs are provided (e.g. --selenium=firefox,chrome).
        """
        test_class = super().__new__(cls, name, bases, attrs)
        # If the test class is either browser-specific or a test base, return


TemplateDoesNotExist, TemplateSyntaxError
from django.utils.functional import cached_property
from django.utils.module_loading import import_string

from .base import BaseEngine
from .utils import csrf_input_lazy, csrf_token_lazy

class Jinja2(BaseEngine):
    app_dirname = "jinja2"

    def __init__(self, params):
        params = params.copy()
        options = params.pop("OPTIONS").copy()
        super().__init__(params)

        self.context_processors = options.pop("context_processors", [])

        e

       options.setdefault("autoescape", True)
        options.setdefault("auto_reload", settings.DEBUG)
        options.setdefault(
            "undefined", jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined
        )

        self.env = environ

nvironment = options.pop("environment", "jinja2.Environment")
        environment_cls = import_string(environment)

        if "loader" not in options:
            options["loader"] = jinja2.FileSystemLoader(self.template_dirs)


ateDoesNotExist

def get_template(template_name, using=None):
    """
    Load and return a template for the given name.

    Raise TemplateDoesNotExist if no such template exists.
    """
    chain = []
    engines = _engine_list(using)
    for engine in engines:
        try:
            return engine.get_template(template_name)
        except TemplateDoesNotExist as e:
            chain.append(e)

    raise TemplateDoesNotExist(template_name, chain=chain)

def select_template(template_name_list, using=N

name_list, str):
        raise TypeError(
            "select_template() takes an iterable of template names but got a "
            "string: %r. Use get_template() if you want to load a single "
            "template by name." % template_name_list

one):
    """
    Load and return a template for one of the given names.

    Try names in order and return the first template found.

    Raise TemplateDoesNotExist if no such template exists.
    """
    if isinstance(template_


    "name": "Afrikaans",
        "name_local": "Afrikaans",
    },
    "ar": {
        "bidi": True,
        "code": "ar",
        "name": "Arabic",
        "name_local": "العربيّة",
    },
    "ar-dz": {
        "bidi": True,
        "code": "ar-dz",
        "name": "Algerian Arabic",
        "name_local": "العربية الجزائرية",
    },
    "ast": {
        "bidi": False,
        "code": "ast",
        "name": "Asturian",
        "name_local": "asturianu",
    },
    "az": {
        "bidi": True,
        "cod

       "bidi": False,
        "code": "bg",
        "name": "Bulgarian",
        "name_local": "български",
    },
    "bn": {
        "bidi": False,
        "code": "bn",
        "name": "Bengali",
        "name_local": "বাংলা",
    },
    "br": {

e": "az",
        "name": "Azerbaijani",
        "name_local": "Azərbaycanca",
    },
    "be": {
        "bidi": False,
        "code": "be",
        "name": "Belarusian",
        "name_local": "беларуская",
    },
    "bg": {


d under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "Y년 n월 j일"
TIME_FORMAT = "A g:i"
DATETIME_FORMAT = "Y년 n월 j일 g:i A"
YEAR_MONTH_FORMAT = "Y년 n월"
MONTH_DAY_FORMAT = "n월 j일"
SHORT_DATE_FORMAT = "Y-n-j"
SHORT_DATETIME_FORMAT = "Y-n-j H:i"
# FIRST_DAY_OF_WEEK =

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/

datetime.html#strftime-strptime-behavior
# Kept ISO formats as they are in first position
DATE_INPUT_FORMATS = [
    "%Y-%m-%d",  # '2006-10-25'
    "%m/%d/%Y",  # '10/25/2006'
    "%m/%d/%y",  # '10/25/06'
    # "%b %d %Y",  # '


 file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "d E Y р."
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "d E Y р. H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "d F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y H:i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://doc

s.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d.%m.%Y",  # '25.10.2006'
    "%d %B %Y",  # '25 October 2006'
]
TIME_INPUT_FORMATS = [
    "%H:%M:%S",  # '14:30:59'
    "%H:%M:%S.%f",


ngs use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "j F Y H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "d/m/Y"
SHORT_DATETIME_FORMAT = "d/m/Y H:i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d/%


ngs use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = r"j N Y"
TIME_FORMAT = r"H:i"
DATETIME_FORMAT = r"j N Y H:i"
YEAR_MONTH_FORMAT = r"F Y"
MONTH_DAY_FORMAT = r"j \d\e F"
SHORT_DATE_FORMAT = r"d/m/Y"
SHORT_DATETIME_FORMAT = r"d/m/Y H:i"
FIRST_DAY_OF_WEEK = 0  # 0: Sunday, 1: Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_I


ngo.conf import settings
from django.template.backends.django import DjangoTemplates
from django.template.loader import get_template
from django.utils.functional import cached_property
from django.utils.module_loading import import_string

@functools.lru_cache
def get_default_renderer():
    renderer_class = import_string(settings.FORM_RENDERER)
    return renderer_class()

class BaseRenderer:
    form_template_name = "django/forms/div.html"
    formset_template_name = "django/forms/formsets/div.html"

te_name, context, request=None):
        template = self.get_template(template_name)
        return template.render(context, request=request).strip()

class EngineMixin:
    def get_template(self, template_name):
        return self.engine.get_template(te

 field_template_name = "django/forms/field.html"

    bound_field_class = None

    def get_template(self, template_name):
        raise NotImplementedError("subclasses must implement get_template()")

    def render(self, templa


ngs use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "j F Y, H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y, H:i"
FIRST_DAY_OF_WEEK = 1

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d.%m.%Y",

TIME_INPUT_FORMATS = [
    "%H:%M",
    "%H:%M:%S",
    "%H:%M:%S.%f",
]
DATETIME_INPUT_FORMATS = [
    "%d.%m.%Y, %H:%M",
    "%d.%m.%Y, %H:%M:%S",
    "%d.%B.%Y, %H:%M",
    "%d.%B.%Y, %H:%M:%S",
]
DECIMAL_SEPARATOR = ","
THOUSAND_SEPARATOR = "."
NUMBER


is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "j F Y H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "Y-m-d"
SHORT_DATETIME_FORMAT = "Y-m-d H:i"
FIRST_DAY_OF_WEEK = 1

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/d

atetime.html#strftime-strptime-behavior
# Kept ISO formats as they are in first position
DATE_INPUT_FORMATS = [
    "%Y-%m-%d",  # '2006-10-25'
    "%m/%d/%Y",  # '10/25/2006'
    "%m/%d/%y",  # '10/25/06'
]
DATETIME_INPUT_FORMAT


d under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j. E Y"
TIME_FORMAT = "G:i"
DATETIME_FORMAT = "j. E Y G:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j. F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y G:i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/d


# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "Y. F j."
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "Y. F j. H:i"
YEAR_MONTH_FORMAT = "Y. F"
MONTH_DAY_FORMAT = "F j."
SHORT_DATE_FORMAT = "Y.m.d."
SHORT_DATETIME_FORMAT = "Y.m.d. H:i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see htt

ps://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%Y.%m.%d.",  # '2006.10.25.'
]
TIME_INPUT_FORMATS = [
    "%H:%M:%S",  # '14:30:59'
    "%H:%M",  # '14:30'
]
DATETIME_INPUT_FORMAT


 file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j. E Y"
TIME_FORMAT = "G.i"
DATETIME_FORMAT = r"j. E Y \k\e\l\l\o G.i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j. F"
SHORT_DATE_FORMAT = "j.n.Y"
SHORT_DATETIME_FORMAT = "j.n.Y G.i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see ht

tps://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d.%m.%Y",  # '20.3.2014'
    "%d.%m.%y",  # '20.3.14'
]
DATETIME_INPUT_FORMATS = [
    "%d.%m.%Y %H.%M.%S",  # '20.3.2014 14.30.5


d under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "d F Y"  # 25 Ottobre 2006
TIME_FORMAT = "H:i"  # 14:30
DATETIME_FORMAT = "l d F Y H:i"  # Mercoledì 25 Ottobre 2006 14:30
YEAR_MONTH_FORMAT = "F Y"  # Ottobre 2006
MONTH_DAY_FORMAT = "j F"  # 25 Ottobre
SHORT_DATE_FORMAT = "d/m/Y"  # 25/12/2009
SHORT_DATETIME_FORMAT = "d/m/Y H:i"  # 25/10/2009 14:30
FIRST_DAY_OF_WE

EK = 1  # Lunedì

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d/%m/%Y",  # '25/10/2006'
    "%Y/


 file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "j F Y H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y H:i"
FIRST_DAY_OF_WEEK = 1  # Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.pyth

on.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d.%m.%Y",  # '25.10.2006'
    "%d.%m.%y",  # '25.10.06'
    "%d/%m/%Y",  # '25/10/2006'
    "%d/%m/%y",  # '25/10/06'
]
DATETIME_INPUT_FORMATS =


 file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j E Y ж."
TIME_FORMAT = "G:i"
DATETIME_FORMAT = "j E Y ж. G:i"
YEAR_MONTH_FORMAT = "F Y ж."
MONTH_DAY_FORMAT = "j F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y H:i"
FIRST_DAY_OF_WEEK = 1  # Дүйшөмбү, Monday

# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# se

e https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
    "%d.%m.%Y",  # '25.10.2006'
    "%d.%m.%y",  # '25.10.06'
]
DATETIME_INPUT_FORMATS = [
    "%d.%m.%Y %H:%M:%S",  # '25.10.2006