prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
without a (Django-specific) contribute_to_class() # method to type.__new__() so that they're properly initialized # (i.e. __set_name__()). contributable_attrs = {} for obj_name, obj in attrs.items(): if _has_contribute_to_class(obj): contributable_attrs[obj_na...
p_config = apps.get_containing_app_config(module) if getattr(meta, "app_label", None) is None: if app_config is None: if not abstract: raise RuntimeError( "Model class %s.%s d
lse) meta = attr_meta or getattr(new_class, "Meta", None) base_meta = getattr(new_class, "_meta", None) app_label = None # Look for an application configuration to attach the model to. ap
{ "filepath": "django/db/models/base.py", "language": "python", "file_size": 99353, "cut_index": 3790, "middle_length": 229 }
Enum from enum import property as enum_property from django.utils.functional import Promise __all__ = ["Choices", "IntegerChoices", "TextChoices"] class ChoicesType(EnumType): """A metaclass for creating a enum choices.""" def __new__(metacls, classname, bases, classdict, **kwds): labels = [] ...
label) # Use dict.__setitem__() to suppress defenses against double # assignment in enum's classdict. dict.__setitem__(classdict, key, value) cls = super().__new__(metacls, classname, bases, classdict, **kwds)
nd isinstance(value[-1], (Promise, str)) ): *value, label = value value = tuple(value) else: label = key.replace("_", " ").title() labels.append(
{ "filepath": "django/db/models/enums.py", "language": "python", "file_size": 2367, "cut_index": 563, "middle_length": 229 }
jango.core.exceptions import FieldFetchBlocked class FetchMode: __slots__ = () track_peers = False def fetch(self, fetcher, instance): raise NotImplementedError("Subclasses must implement this method.") class FetchOne(FetchMode): __slots__ = () def fetch(self, fetcher, instance): ...
fetcher.fetch_many(instances) else: fetcher.fetch_one(instance) def __reduce__(self): return "FETCH_PEERS" FETCH_PEERS = FetchPeers() class Raise(FetchMode): __slots__ = () def fetch(self, fetcher, instance)
f fetch(self, fetcher, instance): instances = [ peer for peer_weakref in instance._state.peers if (peer := peer_weakref()) is not None ] if len(instances) > 1:
{ "filepath": "django/db/models/fetch_modes.py", "language": "python", "file_size": 1249, "cut_index": 518, "middle_length": 229 }
self.get_prep_lhs() if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if bilateral_transforms: # Warn the user as soon as possible if they are trying to apply ...
al_transforms(self, value): for transform in self.bilateral_transforms: value = transform(value) return value def __repr__(self): return f"{self.__class__.__name__}({self.lhs!r}, {self.rhs!r})" def batch_proces
raise NotImplementedError( "Bilateral transformations on nested querysets are not implemented." ) self.bilateral_transforms = bilateral_transforms def apply_bilater
{ "filepath": "django/db/models/lookups.py", "language": "python", "file_size": 28513, "cut_index": 1331, "middle_length": 229 }
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. us...
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 = {}
{ "filepath": "django/db/models/manager.py", "language": "python", "file_size": 6866, "cut_index": 716, "middle_length": 229 }
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 ...
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, *
{ "filepath": "django/db/models/query_utils.py", "language": "python", "file_size": 20366, "cut_index": 1331, "middle_length": 229 }
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): ...
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
{ "filepath": "django/db/models/utils.py", "language": "python", "file_size": 2558, "cut_index": 563, "middle_length": 229 }
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_c...
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
{ "filepath": "django/db/models/functions/comparison.py", "language": "python", "file_size": 6848, "cut_index": 716, "middle_length": 229 }
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.support...
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
{ "filepath": "django/db/models/functions/json.py", "language": "python", "file_size": 4668, "cut_index": 614, "middle_length": 229 }
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(NumericOutputFieldMixi...
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
{ "filepath": "django/db/models/functions/math.py", "language": "python", "file_size": 6140, "cut_index": 716, "middle_length": 229 }
# 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 ...
: 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)
{ "filepath": "django/db/backends/base/creation.py", "language": "python", "file_size": 17375, "cut_index": 921, "middle_length": 229 }
.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_...
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,
{ "filepath": "django/db/models/__init__.py", "language": "python", "file_size": 3346, "cut_index": 614, "middle_length": 229 }
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 insta...
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,
{ "filepath": "django/db/models/deletion.py", "language": "python", "file_size": 22132, "cut_index": 1331, "middle_length": 229 }
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=(), c...
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
{ "filepath": "django/db/models/indexes.py", "language": "python", "file_size": 15578, "cut_index": 921, "middle_length": 229 }
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.annotatio...
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
{ "filepath": "django/db/models/query.py", "language": "python", "file_size": 118093, "cut_index": 3790, "middle_length": 229 }
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, ap...
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
{ "filepath": "django/db/models/signals.py", "language": "python", "file_size": 1622, "cut_index": 537, "middle_length": 229 }
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, d...
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
{ "filepath": "django/db/models/functions/mixins.py", "language": "python", "file_size": 2382, "cut_index": 563, "middle_length": 229 }
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 = ( ...
(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 %
{ "filepath": "django/db/backends/base/schema.py", "language": "python", "file_size": 83683, "cut_index": 3790, "middle_length": 229 }
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 NotImple...
), 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(
{ "filepath": "django/db/models/expressions.py", "language": "python", "file_size": 77894, "cut_index": 3790, "middle_length": 229 }
eatest, Least, NullIf from .datetime import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Now, Trunc, TruncDate, TruncDay, Tr...
.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
{ "filepath": "django/db/models/functions/__init__.py", "language": "python", "file_size": 2782, "cut_index": 563, "middle_length": 229 }
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. ...
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
{ "filepath": "django/db/models/functions/datetime.py", "language": "python", "file_size": 12835, "cut_index": 921, "middle_length": 229 }
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...
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
{ "filepath": "django/db/models/options.py", "language": "python", "file_size": 39672, "cut_index": 2151, "middle_length": 229 }
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 ): sel...
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_
{ "filepath": "django/db/models/constraints.py", "language": "python", "file_size": 28470, "cut_index": 1331, "middle_length": 229 }
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_tok...
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
{ "filepath": "django/template/defaulttags.py", "language": "python", "file_size": 55083, "cut_index": 2151, "middle_length": 229 }
_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=Non...
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_
{ "filepath": "django/db/models/fields/related.py", "language": "python", "file_size": 83508, "cut_index": 3790, "middle_length": 229 }
_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 =...
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
{ "filepath": "django/db/models/sql/compiler.py", "language": "python", "file_size": 96049, "cut_index": 3790, "middle_length": 229 }
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, Nod...
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
{ "filepath": "django/db/models/sql/query.py", "language": "python", "file_size": 123905, "cut_index": 3790, "middle_length": 229 }
# 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 Lo...
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
{ "filepath": "django/db/models/sql/where.py", "language": "python", "file_size": 12317, "cut_index": 921, "middle_length": 229 }
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 ...
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
{ "filepath": "django/db/models/fields/composite.py", "language": "python", "file_size": 5731, "cut_index": 716, "middle_length": 229 }
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...
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.")
{ "filepath": "django/db/models/fields/generated.py", "language": "python", "file_size": 8461, "cut_index": 716, "middle_length": 229 }
"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 mus...
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._
{ "filepath": "django/db/models/fields/json.py", "language": "python", "file_size": 27921, "cut_index": 1331, "middle_length": 229 }
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(...
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
{ "filepath": "django/db/models/functions/window.py", "language": "python", "file_size": 2841, "cut_index": 563, "middle_length": 229 }
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...
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.
{ "filepath": "django/db/models/sql/datastructures.py", "language": "python", "file_size": 7280, "cut_index": 716, "middle_length": 229 }
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 typ...
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_
{ "filepath": "django/db/models/fields/__init__.py", "language": "python", "file_size": 103134, "cut_index": 3790, "middle_length": 229 }
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) r...
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
{ "filepath": "django/db/models/functions/uuid.py", "language": "python", "file_size": 3593, "cut_index": 614, "middle_length": 229 }
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_ma...
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
{ "filepath": "django/db/models/sql/subqueries.py", "language": "python", "file_size": 5993, "cut_index": 716, "middle_length": 229 }
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...
_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
{ "filepath": "django/db/models/fields/mixins.py", "language": "python", "file_size": 1947, "cut_index": 537, "middle_length": 229 }
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...
"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(
{ "filepath": "django/db/models/fields/files.py", "language": "python", "file_size": 20242, "cut_index": 1331, "middle_length": 229 }
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 ...
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
{ "filepath": "django/conf/urls/static.py", "language": "python", "file_size": 908, "cut_index": 547, "middle_length": 52 }
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(se...
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
{ "filepath": "django/db/models/fields/related_descriptors.py", "language": "python", "file_size": 69743, "cut_index": 3790, "middle_length": 229 }
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(...
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
{ "filepath": "django/db/models/fields/reverse_related.py", "language": "python", "file_size": 12624, "cut_index": 921, "middle_length": 229 }
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 deconstructi...
_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
{ "filepath": "django/db/migrations/autodetector.py", "language": "python", "file_size": 90088, "cut_index": 3790, "middle_length": 229 }
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-...
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
{ "filepath": "django/db/migrations/exceptions.py", "language": "python", "file_size": 1204, "cut_index": 518, "middle_length": 229 }
= 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 __...
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
{ "filepath": "django/db/migrations/graph.py", "language": "python", "file_size": 13149, "cut_index": 921, "middle_length": 229 }
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, ...
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
{ "filepath": "django/db/migrations/optimizer.py", "language": "python", "file_size": 3255, "cut_index": 614, "middle_length": 229 }
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...
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
{ "filepath": "django/db/migrations/recorder.py", "language": "python", "file_size": 3827, "cut_index": 614, "middle_length": 229 }
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_field...
: """ 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)
{ "filepath": "django/db/migrations/state.py", "language": "python", "file_size": 42119, "cut_index": 2151, "middle_length": 229 }
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 serializ...
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
{ "filepath": "django/db/migrations/writer.py", "language": "python", "file_size": 11933, "cut_index": 921, "middle_length": 229 }
from .fields import AddField, AlterField, RemoveField, RenameField from .models import ( AddConstraint, AddIndex, AlterConstraint, AlterIndexTogether, AlterModelManagers, AlterModelOptions, AlterModelTable, AlterModelTableComment, AlterOrderWithRespectTo, AlterUniqueTogether, ...
ex", "AddField", "RemoveField", "AlterField", "RenameField", "AddConstraint", "RemoveConstraint", "AlterConstraint", "SeparateDatabaseAndState", "RunSQL", "RunPython", "AlterOrderWithRespectTo", "AlterModelMa
ateModel", "DeleteModel", "AlterModelTable", "AlterModelTableComment", "AlterUniqueTogether", "RenameModel", "AlterIndexTogether", "AlterModelOptions", "AddIndex", "RemoveIndex", "RenameInd
{ "filepath": "django/db/migrations/operations/__init__.py", "language": "python", "file_size": 1008, "cut_index": 512, "middle_length": 229 }
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_du...
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):
{ "filepath": "django/db/migrations/operations/models.py", "language": "python", "file_size": 45901, "cut_index": 2151, "middle_length": 229 }
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 ...
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
{ "filepath": "django/template/__init__.py", "language": "python", "file_size": 1865, "cut_index": 537, "middle_length": 229 }
= 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) '<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '<...
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
{ "filepath": "django/template/base.py", "language": "python", "file_size": 44608, "cut_index": 2151, "middle_length": 229 }
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): ...
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
{ "filepath": "django/template/context.py", "language": "python", "file_size": 9482, "cut_index": 921, "middle_length": 229 }
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 rel...
_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
{ "filepath": "django/db/models/fields/related_lookups.py", "language": "python", "file_size": 6094, "cut_index": 716, "middle_length": 229 }
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_ex...
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 )
{ "filepath": "django/db/models/fields/tuple_lookups.py", "language": "python", "file_size": 15377, "cut_index": 921, "middle_length": 229 }
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 load...
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
{ "filepath": "django/db/migrations/loader.py", "language": "python", "file_size": 18744, "cut_index": 1331, "middle_length": 229 }
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_...
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
{ "filepath": "django/db/migrations/questioner.py", "language": "python", "file_size": 13568, "cut_index": 921, "middle_length": 229 }
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, ...
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
{ "filepath": "django/db/migrations/utils.py", "language": "python", "file_size": 4401, "cut_index": 614, "middle_length": 229 }
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...
(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(
{ "filepath": "django/db/migrations/operations/fields.py", "language": "python", "file_size": 12787, "cut_index": 921, "middle_length": 229 }
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 ...
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
{ "filepath": "django/template/autoreload.py", "language": "python", "file_size": 2063, "cut_index": 563, "middle_length": 229 }
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 dj...
""" 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
{ "filepath": "django/template/context_processors.py", "language": "python", "file_size": 2707, "cut_index": 563, "middle_length": 229 }
- 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...
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
{ "filepath": "django/db/migrations/migration.py", "language": "python", "file_size": 9765, "cut_index": 921, "middle_length": 229 }
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 ...
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.
{ "filepath": "django/db/migrations/operations/base.py", "language": "python", "file_size": 5927, "cut_index": 716, "middle_length": 229 }
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() ####################...
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(
{ "filepath": "django/template/defaultfilters.py", "language": "python", "file_size": 28417, "cut_index": 1331, "middle_length": 229 }
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\xa0...
5' ] DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", # '2006-05-15 14:30:57' "%y-%m-%d %H:%M:%S", # '06-05-15 14:30:57' "%Y-%m-%d %H:%M:%S.%f", # '2006-05-15 14:30:57.000200' "%y-%m-%d %H:%M:%S.%f", # '06-05-15 14:30:57.000200' "%Y-
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
{ "filepath": "django/conf/locale/fr_CA/formats.py", "language": "python", "file_size": 1177, "cut_index": 518, "middle_length": 229 }
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 provid...
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
{ "filepath": "django/template/loaders/base.py", "language": "python", "file_size": 1636, "cut_index": 537, "middle_length": 229 }
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): ...
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
{ "filepath": "django/template/loaders/filesystem.py", "language": "python", "file_size": 1506, "cut_index": 524, "middle_length": 229 }
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.t...
actionTestCase", "SimpleTestCase", "LiveServerTestCase", "skipIfDBFeature", "skipUnlessAnyDBFeature", "skipUnlessDBFeature", "ignore_warnings", "modify_settings", "override_settings", "override_system_checks", "tag",
t", "RequestFactory", "TestCase", "Trans
{ "filepath": "django/test/__init__.py", "language": "python", "file_size": 834, "cut_index": 523, "middle_length": 52 }
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 D...
). 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(
{ "filepath": "django/test/runner.py", "language": "python", "file_size": 44605, "cut_index": 2151, "middle_length": 229 }
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 djan...
: 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"
{ "filepath": "django/test/signals.py", "language": "python", "file_size": 7644, "cut_index": 716, "middle_length": 229 }
, 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...
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
{ "filepath": "django/db/migrations/operations/special.py", "language": "python", "file_size": 8146, "cut_index": 716, "middle_length": 229 }
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 _...
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
{ "filepath": "django/template/engine.py", "language": "python", "file_size": 8401, "cut_index": 716, "middle_length": 229 }
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...
@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
{ "filepath": "django/template/library.py", "language": "python", "file_size": 17247, "cut_index": 921, "middle_length": 229 }
__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 IndexErr...
(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__
{ "filepath": "django/template/loader_tags.py", "language": "python", "file_size": 13526, "cut_index": 921, "middle_length": 229 }
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 ...
""" 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):
{ "filepath": "django/template/smartif.py", "language": "python", "file_size": 6478, "cut_index": 716, "middle_length": 229 }
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 o...
}".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: {
{ "filepath": "django/template/backends/base.py", "language": "python", "file_size": 2801, "cut_index": 563, "middle_length": 229 }
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 __in...
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
{ "filepath": "django/template/backends/django.py", "language": "python", "file_size": 5963, "cut_index": 716, "middle_length": 229 }
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...
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
{ "filepath": "django/test/testcases.py", "language": "python", "file_size": 68958, "cut_index": 3790, "middle_length": 229 }
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" ...
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
{ "filepath": "django/conf/__init__.py", "language": "python", "file_size": 14243, "cut_index": 921, "middle_length": 229 }
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...
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
{ "filepath": "django/conf/global_settings.py", "language": "python", "file_size": 23658, "cut_index": 1331, "middle_length": 229 }
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 = {} ...
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
{ "filepath": "django/template/loaders/cached.py", "language": "python", "file_size": 3716, "cut_index": 614, "middle_length": 229 }
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",...
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
{ "filepath": "django/test/html.py", "language": "python", "file_size": 8869, "cut_index": 716, "middle_length": 229 }
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...
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
{ "filepath": "django/db/migrations/executor.py", "language": "python", "file_size": 19029, "cut_index": 1331, "middle_length": 229 }
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 d...
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
{ "filepath": "django/template/exceptions.py", "language": "python", "file_size": 1342, "cut_index": 524, "middle_length": 229 }
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 ...
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
{ "filepath": "django/template/response.py", "language": "python", "file_size": 5584, "cut_index": 716, "middle_length": 229 }
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 __i...
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
{ "filepath": "django/template/backends/dummy.py", "language": "python", "file_size": 1751, "cut_index": 537, "middle_length": 229 }
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", ...
, 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
{ "filepath": "django/test/utils.py", "language": "python", "file_size": 33543, "cut_index": 1331, "middle_length": 229 }
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): sup...
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
{ "filepath": "django/test/client.py", "language": "python", "file_size": 56053, "cut_index": 2151, "middle_length": 229 }
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 mo...
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
{ "filepath": "django/db/migrations/serializer.py", "language": "python", "file_size": 14835, "cut_index": 921, "middle_length": 229 }
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=...
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
{ "filepath": "django/template/utils.py", "language": "python", "file_size": 3571, "cut_index": 614, "middle_length": 229 }
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 ...
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
{ "filepath": "django/conf/urls/i18n.py", "language": "python", "file_size": 1166, "cut_index": 518, "middle_length": 229 }
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 # ...
# 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
{ "filepath": "django/test/selenium.py", "language": "python", "file_size": 10493, "cut_index": 921, "middle_length": 229 }
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): ...
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)
{ "filepath": "django/template/backends/jinja2.py", "language": "python", "file_size": 4036, "cut_index": 614, "middle_length": 229 }
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(te...
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_
{ "filepath": "django/template/loader.py", "language": "python", "file_size": 2054, "cut_index": 563, "middle_length": 229 }
"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": "العربية ال...
"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": {
{ "filepath": "django/conf/locale/__init__.py", "language": "python", "file_size": 14004, "cut_index": 921, "middle_length": 229 }
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일" SH...
Oct 25 2006' # "%b %d, %Y", # 'Oct 25, 2006' # "%d %b %Y", # '25 Oct 2006' # "%d %b, %Y", #'25 Oct, 2006' # "%B %d %Y", # 'October 25 2006' # "%B %d, %Y", #'October 25, 2006' # "%d %B %Y", # '25 October 2006' # "%d %B, %Y"
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", # '
{ "filepath": "django/conf/locale/ko/formats.py", "language": "python", "file_size": 2060, "cut_index": 537, "middle_length": 229 }
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...
# '14:30:59.000200' "%H:%M", # '14:30' ] DATETIME_INPUT_FORMATS = [ "%d.%m.%Y %H:%M:%S", # '25.10.2006 14:30:59' "%d.%m.%Y %H:%M:%S.%f", # '25.10.2006 14:30:59.000200' "%d.%m.%Y %H:%M", # '25.10.2006 14:30' "%d %B %Y %H:%M:%S", # '
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",
{ "filepath": "django/conf/locale/uk/formats.py", "language": "python", "file_size": 1241, "cut_index": 518, "middle_length": 229 }
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...
] DATETIME_INPUT_FORMATS = [ "%d/%m/%Y %H:%M:%S", # '25/10/2006 14:30:59' "%d/%m/%Y %H:%M:%S.%f", # '25/10/2006 14:30:59.000200' "%d/%m/%Y %H:%M", # '25/10/2006 14:30' ] DECIMAL_SEPARATOR = "," THOUSAND_SEPARATOR = "\xa0" # non-breaking sp
m/%Y", # '25/10/2006' "%d/%m/%y", # '25/10/06'
{ "filepath": "django/conf/locale/fr/formats.py", "language": "python", "file_size": 938, "cut_index": 606, "middle_length": 52 }
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...
"%d/%m/%y", # '31/12/09' ] DATETIME_INPUT_FORMATS = [ "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M:%S.%f", "%d/%m/%Y %H:%M", "%d/%m/%y %H:%M:%S", "%d/%m/%y %H:%M:%S.%f", "%d/%m/%y %H:%M", ] DECIMAL_SEPARATOR = "," THOUSAND_SEPARATOR = "."
NPUT_FORMATS = [ "%d/%m/%Y", # '31/12/2009'
{ "filepath": "django/conf/locale/es_AR/formats.py", "language": "python", "file_size": 935, "cut_index": 606, "middle_length": 52 }
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_st...
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
{ "filepath": "django/forms/renderers.py", "language": "python", "file_size": 2141, "cut_index": 563, "middle_length": 229 }