hash
stringlengths
64
64
content
stringlengths
0
1.51M
842647fd9f3465a68d38c27ad3002f019dcd0b5d05a044aab4078de9e736cd8e
""" Useful auxiliary data structures for query construction. Not useful outside the SQL domain. """ import warnings from django.core.exceptions import FullResultSet from django.db.models.sql.constants import INNER, LOUTER from django.utils.deprecation import RemovedInDjango60Warning 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 JOIN 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. 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 aren't joined from anything) - parent_alias (which table is this join's parent, can be None similarly to join_type) - as_sql() - relabeled_clone() """ def __init__( self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, ): # Join table self.table_name = table_name self.parent_alias = parent_alias # Note: table_alias is not necessarily known at instantiation time. self.table_alias = table_alias # LOUTER or INNER self.join_type = join_type # A list of 2-tuples to use in the ON clause of the JOIN. # Each 2-tuple will create one join condition in the ON clause. if hasattr(join_field, "get_joining_fields"): self.join_fields = join_field.get_joining_fields() self.join_cols = tuple( (lhs_field.column, rhs_field.column) for lhs_field, rhs_field in self.join_fields ) else: warnings.warn( "The usage of get_joining_columns() in Join is deprecated. Implement " "get_joining_fields() instead.", RemovedInDjango60Warning, ) self.join_fields = None self.join_cols = join_field.get_joining_columns() # Along which field (or ForeignObjectRel in the reverse join case) self.join_field = join_field # Is this join nullabled? self.nullable = nullable self.filtered_relation = filtered_relation def as_sql(self, compiler, connection): """ Generate the full LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params clause for this join. """ join_conditions = [] params = [] qn = compiler.quote_name_unless_alias qn2 = connection.ops.quote_name # Add a join condition for each pair of joining columns. # RemovedInDjango60Warning: when the depraction ends, replace with: # for lhs, rhs in self.join_field: join_fields = self.join_fields or self.join_cols for lhs, rhs in join_fields: if isinstance(lhs, str): # RemovedInDjango60Warning: when the depraction ends, remove # the branch for strings. lhs_full_name = "%s.%s" % (qn(self.parent_alias), qn2(lhs)) rhs_full_name = "%s.%s" % (qn(self.table_alias), qn2(rhs)) else: lhs, rhs = connection.ops.prepare_join_on_clause( self.parent_alias, lhs, self.table_alias, rhs ) lhs_sql, lhs_params = compiler.compile(lhs) lhs_full_name = lhs_sql % lhs_params rhs_sql, rhs_params = compiler.compile(rhs) rhs_full_name = rhs_sql % rhs_params join_conditions.append(f"{lhs_full_name} = {rhs_full_name}") # Add a single condition inside parentheses for whatever # get_extra_restriction() returns. extra_cond = self.join_field.get_extra_restriction( self.table_alias, self.parent_alias ) if extra_cond: extra_sql, extra_params = compiler.compile(extra_cond) join_conditions.append("(%s)" % extra_sql) params.extend(extra_params) if self.filtered_relation: try: extra_sql, extra_params = compiler.compile(self.filtered_relation) except FullResultSet: pass else: join_conditions.append("(%s)" % extra_sql) params.extend(extra_params) if not join_conditions: # This might be a rel on the other end of an actual declared field. declared_field = getattr(self.join_field, "field", self.join_field) raise ValueError( "Join generated an empty ON clause. %s did not yield either " "joining columns or extra restrictions." % declared_field.__class__ ) on_clause_sql = " AND ".join(join_conditions) alias_str = ( "" if self.table_alias == self.table_name else (" %s" % self.table_alias) ) sql = "%s %s%s ON (%s)" % ( self.join_type, qn(self.table_name), alias_str, on_clause_sql, ) return sql, params def relabeled_clone(self, change_map): new_parent_alias = change_map.get(self.parent_alias, self.parent_alias) new_table_alias = change_map.get(self.table_alias, self.table_alias) if self.filtered_relation is not None: filtered_relation = self.filtered_relation.relabeled_clone(change_map) else: filtered_relation = None return self.__class__( self.table_name, new_parent_alias, new_table_alias, self.join_type, self.join_field, self.nullable, filtered_relation=filtered_relation, ) @property def identity(self): return ( self.__class__, self.table_name, self.parent_alias, self.join_field, self.filtered_relation, ) def __eq__(self, other): if not isinstance(other, Join): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(self.identity) def demote(self): new = self.relabeled_clone({}) new.join_type = INNER return new def promote(self): new = self.relabeled_clone({}) new.join_type = LOUTER return new class BaseTable: """ The BaseTable class is used for base table references in FROM clause. For example, the SQL "foo" in SELECT * FROM "foo" WHERE somecond could be generated by this class. """ join_type = None parent_alias = None filtered_relation = None def __init__(self, table_name, alias): self.table_name = table_name self.table_alias = alias def as_sql(self, compiler, connection): alias_str = ( "" if self.table_alias == self.table_name else (" %s" % self.table_alias) ) base_sql = compiler.quote_name_unless_alias(self.table_name) return base_sql + alias_str, [] def relabeled_clone(self, change_map): return self.__class__( self.table_name, change_map.get(self.table_alias, self.table_alias) ) @property def identity(self): return self.__class__, self.table_name, self.table_alias def __eq__(self, other): if not isinstance(other, BaseTable): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(self.identity)
1c0f120ec7c3ecdd9de59d70c706d5d54714bb79e98f158286f8fb9a221cb171
from django.db import DatabaseError, InterfaceError from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (19,) # Oracle crashes with "ORA-00932: inconsistent datatypes: expected - got # BLOB" when grouping by LOBs (#24096). allows_group_by_lob = False allows_group_by_select_index = False interprets_empty_strings_as_nulls = True has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_skip_locked = True has_select_for_update_of = True select_for_update_of_column = True can_return_columns_from_insert = True supports_subqueries_in_group_by = False ignores_unnecessary_order_by_in_subqueries = False supports_transactions = True supports_timezones = False has_native_duration_field = True can_defer_constraint_checks = True supports_partially_nullable_unique_constraints = False supports_deferrable_unique_constraints = True truncates_names = True supports_comments = True supports_tablespaces = True supports_sequence_reset = False can_introspect_materialized_views = True atomic_transactions = False nulls_order_largest = True requires_literal_defaults = True closed_cursor_error_class = InterfaceError bare_select_suffix = " FROM DUAL" # Select for update with limit can be achieved on Oracle, but not with the # current backend. supports_select_for_update_with_limit = False supports_temporal_subtraction = True # Oracle doesn't ignore quoted identifiers case but the current backend # does by uppercasing all identifiers. ignores_table_name_case = True supports_index_on_text_field = False create_test_procedure_without_params_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" AS V_I INTEGER; BEGIN V_I := 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" (P_I INTEGER) AS V_I INTEGER; BEGIN V_I := P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 NUMBER(11) NOT NULL, column_2 NUMBER(11) NOT NULL, PRIMARY KEY (column_1, column_2) ) """ supports_callproc_kwargs = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_ignore_conflicts = False max_query_params = 2**16 - 1 supports_partial_indexes = False can_rename_index = True supports_slicing_ordering_in_compound = True requires_compound_order_by_subquery = True allows_multiple_constraints_on_same_fields = False supports_boolean_expr_in_select_clause = False supports_comparing_boolean_expr = False supports_primitives_in_json_field = False supports_json_field_contains = False supports_collation_on_textfield = False test_collations = { "ci": "BINARY_CI", "cs": "BINARY", "non_default": "SWEDISH_CI", "swedish_ci": "SWEDISH_CI", } test_now_utc_template = "CURRENT_TIMESTAMP AT TIME ZONE 'UTC'" django_test_skips = { "Oracle doesn't support SHA224.": { "db_functions.text.test_sha224.SHA224Tests.test_basic", "db_functions.text.test_sha224.SHA224Tests.test_transform", }, "Oracle doesn't correctly calculate ISO 8601 week numbering before " "1583 (the Gregorian calendar was introduced in 1582).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_trunc_week_before_1000", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_trunc_week_before_1000", }, "Oracle extracts seconds including fractional seconds (#33517).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_extract_second_func_no_fractional", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_extract_second_func_no_fractional", }, "Oracle doesn't support bitwise XOR.": { "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor", "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor_null", "expressions.tests.ExpressionOperatorTests." "test_lefthand_bitwise_xor_right_null", }, "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't.": { "expressions_window.tests.WindowFunctionTests.test_row_number_no_ordering", }, "Raises ORA-00600: internal error code.": { "model_fields.test_jsonfield.TestQuerying.test_usage_in_subquery", }, "Oracle doesn't support changing collations on indexed columns (#33671).": { "migrations.test_operations.OperationTests." "test_alter_field_pk_fk_db_collation", }, "Oracle doesn't support comparing NCLOB to NUMBER.": { "generic_relations_regress.tests.GenericRelationTests.test_textlink_filter", }, } django_test_expected_failures = { # A bug in Django/cx_Oracle with respect to string handling (#23843). "annotations.tests.NonAggregateAnnotationTestCase.test_custom_functions", "annotations.tests.NonAggregateAnnotationTestCase." "test_custom_functions_can_ref_other_functions", } @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "GenericIPAddressField": "CharField", "PositiveBigIntegerField": "BigIntegerField", "PositiveIntegerField": "IntegerField", "PositiveSmallIntegerField": "IntegerField", "SmallIntegerField": "IntegerField", "TimeField": "DateTimeField", } @cached_property def supports_collation_on_charfield(self): with self.connection.cursor() as cursor: try: cursor.execute("SELECT CAST('a' AS VARCHAR2(4001)) FROM dual") except DatabaseError as e: if e.args[0].code == 910: return False raise return True
d45d3d44989974c321d1a45864e88f0adc07fbaa59baf7b8685ec06b9d82bf62
from django.db import ProgrammingError from django.utils.functional import cached_property class BaseDatabaseFeatures: # An optional tuple indicating the minimum supported database version. minimum_database_version = None gis_enabled = False # Oracle can't group by LOB (large object) data types. allows_group_by_lob = True allows_group_by_selected_pks = False allows_group_by_select_index = True empty_fetchmany_value = [] update_can_self_select = True # Does the backend support self-reference subqueries in the DELETE # statement? delete_can_self_reference_subquery = True # Does the backend distinguish between '' and None? interprets_empty_strings_as_nulls = False # Does the backend allow inserting duplicate NULL rows in a nullable # unique field? All core backends implement this correctly, but other # databases such as SQL Server do not. supports_nullable_unique_constraints = True # Does the backend allow inserting duplicate rows when a unique_together # constraint exists and some fields are nullable but not all of them? supports_partially_nullable_unique_constraints = True # Does the backend support initially deferrable unique constraints? supports_deferrable_unique_constraints = False can_use_chunked_reads = True can_return_columns_from_insert = False can_return_rows_from_bulk_insert = False has_bulk_insert = True uses_savepoints = True can_release_savepoints = False # If True, don't use integer foreign keys referring to, e.g., positive # integer primary keys. related_fields_match_type = False allow_sliced_subqueries_with_in = True has_select_for_update = False has_select_for_update_nowait = False has_select_for_update_skip_locked = False has_select_for_update_of = False has_select_for_no_key_update = False # Does the database's SELECT FOR UPDATE OF syntax require a column rather # than a table? select_for_update_of_column = False # Does the default test database allow multiple connections? # Usually an indication that the test database is in-memory test_db_allows_multiple_connections = True # Can an object be saved without an explicit primary key? supports_unspecified_pk = False # Can a fixture contain forward references? i.e., are # FK constraints checked at the end of transaction, or # at the end of each save operation? supports_forward_references = True # Does the backend truncate names properly when they are too long? truncates_names = False # Is there a REAL datatype in addition to floats/doubles? has_real_datatype = False supports_subqueries_in_group_by = True # Does the backend ignore unnecessary ORDER BY clauses in subqueries? ignores_unnecessary_order_by_in_subqueries = True # Is there a true datatype for uuid? has_native_uuid_field = False # Is there a true datatype for timedeltas? has_native_duration_field = False # Does the database driver supports same type temporal data subtraction # by returning the type used to store duration field? supports_temporal_subtraction = False # Does the __regex lookup support backreferencing and grouping? supports_regex_backreferencing = True # Can date/datetime lookups be performed using a string? supports_date_lookup_using_string = True # Can datetimes with timezones be used? supports_timezones = True # Does the database have a copy of the zoneinfo database? has_zoneinfo_database = True # When performing a GROUP BY, is an ORDER BY NULL required # to remove any ordering? requires_explicit_null_ordering_when_grouping = False # Does the backend order NULL values as largest or smallest? nulls_order_largest = False # Does the backend support NULLS FIRST and NULLS LAST in ORDER BY? supports_order_by_nulls_modifier = True # Does the backend orders NULLS FIRST by default? order_by_nulls_first = False # The database's limit on the number of query parameters. max_query_params = None # Can an object have an autoincrement primary key of 0? allows_auto_pk_0 = True # Do we need to NULL a ForeignKey out, or can the constraint check be # deferred can_defer_constraint_checks = False # Does the backend support tablespaces? Default to False because it isn't # in the SQL standard. supports_tablespaces = False # Does the backend reset sequences between tests? supports_sequence_reset = True # Can the backend introspect the default value of a column? can_introspect_default = True # Confirm support for introspected foreign keys # Every database can do this reliably, except MySQL, # which can't do it for MyISAM tables can_introspect_foreign_keys = True # Map fields which some backends may not be able to differentiate to the # field it's introspected as. introspected_field_types = { "AutoField": "AutoField", "BigAutoField": "BigAutoField", "BigIntegerField": "BigIntegerField", "BinaryField": "BinaryField", "BooleanField": "BooleanField", "CharField": "CharField", "DurationField": "DurationField", "GenericIPAddressField": "GenericIPAddressField", "IntegerField": "IntegerField", "PositiveBigIntegerField": "PositiveBigIntegerField", "PositiveIntegerField": "PositiveIntegerField", "PositiveSmallIntegerField": "PositiveSmallIntegerField", "SmallAutoField": "SmallAutoField", "SmallIntegerField": "SmallIntegerField", "TimeField": "TimeField", } # Can the backend introspect the column order (ASC/DESC) for indexes? supports_index_column_ordering = True # Does the backend support introspection of materialized views? can_introspect_materialized_views = False # Support for the DISTINCT ON clause can_distinct_on_fields = False # Does the backend prevent running SQL queries in broken transactions? atomic_transactions = True # Can we roll back DDL in a transaction? can_rollback_ddl = False schema_editor_uses_clientside_param_binding = False # Does it support operations requiring references rename in a transaction? supports_atomic_references_rename = True # Can we issue more than one ALTER COLUMN clause in an ALTER TABLE? supports_combined_alters = False # Does it support foreign keys? supports_foreign_keys = True # Can it create foreign key constraints inline when adding columns? can_create_inline_fk = True # Can an index be renamed? can_rename_index = False # Does it automatically index foreign keys? indexes_foreign_keys = True # Does it support CHECK constraints? supports_column_check_constraints = True supports_table_check_constraints = True # Does the backend support introspection of CHECK constraints? can_introspect_check_constraints = True # Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value}) # parameter passing? Note this can be provided by the backend even if not # supported by the Python driver supports_paramstyle_pyformat = True # Does the backend require literal defaults, rather than parameterized ones? requires_literal_defaults = False # Does the backend require a connection reset after each material schema change? connection_persists_old_columns = False # What kind of error does the backend throw when accessing closed cursor? closed_cursor_error_class = ProgrammingError # Does 'a' LIKE 'A' match? has_case_insensitive_like = False # Suffix for backends that don't support "SELECT xxx;" queries. bare_select_suffix = "" # If NULL is implied on columns without needing to be explicitly specified implied_column_null = False # Does the backend support "select for update" queries with limit (and offset)? supports_select_for_update_with_limit = True # Does the backend ignore null expressions in GREATEST and LEAST queries unless # every expression is null? greatest_least_ignores_nulls = False # Can the backend clone databases for parallel test execution? # Defaults to False to allow third-party backends to opt-in. can_clone_databases = False # Does the backend consider table names with different casing to # be equal? ignores_table_name_case = False # Place FOR UPDATE right after FROM clause. Used on MSSQL. for_update_after_from = False # Combinatorial flags supports_select_union = True supports_select_intersection = True supports_select_difference = True supports_slicing_ordering_in_compound = False supports_parentheses_in_compound = True requires_compound_order_by_subquery = False # Does the database support SQL 2003 FILTER (WHERE ...) in aggregate # expressions? supports_aggregate_filter_clause = False # Does the backend support indexing a TextField? supports_index_on_text_field = True # Does the backend support window expressions (expression OVER (...))? supports_over_clause = False supports_frame_range_fixed_distance = False only_supports_unbounded_with_preceding_and_following = False # Does the backend support CAST with precision? supports_cast_with_precision = True # How many second decimals does the database return when casting a value to # a type with time? time_cast_precision = 6 # SQL to create a procedure for use by the Django test suite. The # functionality of the procedure isn't important. create_test_procedure_without_params_sql = None create_test_procedure_with_int_param_sql = None # SQL to create a table with a composite primary key for use by the Django # test suite. create_test_table_with_composite_primary_key = None # Does the backend support keyword parameters for cursor.callproc()? supports_callproc_kwargs = False # What formats does the backend EXPLAIN syntax support? supported_explain_formats = set() # Does the backend support the default parameter in lead() and lag()? supports_default_in_lead_lag = True # Does the backend support ignoring constraint or uniqueness errors during # INSERT? supports_ignore_conflicts = True # Does the backend support updating rows on constraint or uniqueness errors # during INSERT? supports_update_conflicts = False supports_update_conflicts_with_target = False # Does this backend require casting the results of CASE expressions used # in UPDATE statements to ensure the expression has the correct type? requires_casted_case_in_updates = False # Does the backend support partial indexes (CREATE INDEX ... WHERE ...)? supports_partial_indexes = True supports_functions_in_partial_indexes = True # Does the backend support covering indexes (CREATE INDEX ... INCLUDE ...)? supports_covering_indexes = False # Does the backend support indexes on expressions? supports_expression_indexes = True # Does the backend treat COLLATE as an indexed expression? collate_as_index_expression = False # Does the database allow more than one constraint or index on the same # field(s)? allows_multiple_constraints_on_same_fields = True # Does the backend support boolean expressions in SELECT and GROUP BY # clauses? supports_boolean_expr_in_select_clause = True # Does the backend support comparing boolean expressions in WHERE clauses? # Eg: WHERE (price > 0) IS NOT NULL supports_comparing_boolean_expr = True # Does the backend support JSONField? supports_json_field = True # Can the backend introspect a JSONField? can_introspect_json_field = True # Does the backend support primitives in JSONField? supports_primitives_in_json_field = True # Is there a true datatype for JSON? has_native_json_field = False # Does the backend use PostgreSQL-style JSON operators like '->'? has_json_operators = False # Does the backend support __contains and __contained_by lookups for # a JSONField? supports_json_field_contains = True # Does value__d__contains={'f': 'g'} (without a list around the dict) match # {'d': [{'f': 'g'}]}? json_key_contains_list_matching_requires_list = False # Does the backend support JSONObject() database function? has_json_object_function = True # Does the backend support column collations? supports_collation_on_charfield = True supports_collation_on_textfield = True # Does the backend support non-deterministic collations? supports_non_deterministic_collations = True # Does the backend support column and table comments? supports_comments = False # Does the backend support column comments in ADD COLUMN statements? supports_comments_inline = False # Does the backend support the logical XOR operator? supports_logical_xor = False # Set to (exception, message) if null characters in text are disallowed. prohibits_null_characters_in_text_exception = None # Does the backend support unlimited character columns? supports_unlimited_charfield = False # Collation names for use by the Django test suite. test_collations = { "ci": None, # Case-insensitive. "cs": None, # Case-sensitive. "non_default": None, # Non-default. "swedish_ci": None, # Swedish case-insensitive. } # SQL template override for tests.aggregation.tests.NowUTC test_now_utc_template = None # A set of dotted paths to tests in Django's test suite that are expected # to fail on this database. django_test_expected_failures = set() # A map of reasons to sets of dotted paths to tests in Django's test suite # that should be skipped for this database. django_test_skips = {} def __init__(self, connection): self.connection = connection @cached_property def supports_explaining_query_execution(self): """Does this backend support explaining query execution?""" return self.connection.ops.explain_prefix is not None @cached_property def supports_transactions(self): """Confirm support for transactions.""" with self.connection.cursor() as cursor: cursor.execute("CREATE TABLE ROLLBACK_TEST (X INT)") self.connection.set_autocommit(False) cursor.execute("INSERT INTO ROLLBACK_TEST (X) VALUES (8)") self.connection.rollback() self.connection.set_autocommit(True) cursor.execute("SELECT COUNT(X) FROM ROLLBACK_TEST") (count,) = cursor.fetchone() cursor.execute("DROP TABLE ROLLBACK_TEST") return count == 0 def allows_group_by_selected_pks_on_model(self, model): if not self.allows_group_by_selected_pks: return False return model._meta.managed
f8134e1904a98d9ed7ac0d24721678ebc2f05797ba61dea2e08d5332ccf06160
import datetime import decimal import json from importlib import import_module import sqlparse from django.conf import settings from django.db import NotSupportedError, transaction from django.db.backends import utils from django.db.models.expressions import Col from django.utils import timezone from django.utils.encoding import force_str class BaseDatabaseOperations: """ Encapsulate backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. """ compiler_module = "django.db.models.sql.compiler" # Integer field safe ranges by `internal_type` as documented # in docs/ref/models/fields.txt. integer_field_ranges = { "SmallIntegerField": (-32768, 32767), "IntegerField": (-2147483648, 2147483647), "BigIntegerField": (-9223372036854775808, 9223372036854775807), "PositiveBigIntegerField": (0, 9223372036854775807), "PositiveSmallIntegerField": (0, 32767), "PositiveIntegerField": (0, 2147483647), "SmallAutoField": (-32768, 32767), "AutoField": (-2147483648, 2147483647), "BigAutoField": (-9223372036854775808, 9223372036854775807), } set_operators = { "union": "UNION", "intersection": "INTERSECT", "difference": "EXCEPT", } # Mapping of Field.get_internal_type() (typically the model field's class # name) to the data type to use for the Cast() function, if different from # DatabaseWrapper.data_types. cast_data_types = {} # CharField data type if the max_length argument isn't provided. cast_char_field_without_max_length = None # Start and end points for window expressions. PRECEDING = "PRECEDING" FOLLOWING = "FOLLOWING" UNBOUNDED_PRECEDING = "UNBOUNDED " + PRECEDING UNBOUNDED_FOLLOWING = "UNBOUNDED " + FOLLOWING CURRENT_ROW = "CURRENT ROW" # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None def __init__(self, connection): self.connection = connection self._cache = None def autoinc_sql(self, table, column): """ Return any SQL needed to support auto-incrementing primary keys, or None if no SQL is necessary. This SQL is executed when a table is created. """ return None def bulk_batch_size(self, fields, objs): """ Return the maximum allowed batch size for the backend. The fields are the fields going to be inserted in the batch, the objs contains all the objects to be inserted. """ return len(objs) def format_for_duration_arithmetic(self, sql): raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "format_for_duration_arithmetic() method." ) def cache_key_culling_sql(self): """ Return an SQL query that retrieves the first cache key greater than the n smallest. This is used by the 'db' cache backend to determine where to start culling. """ cache_key = self.quote_name("cache_key") return f"SELECT {cache_key} FROM %s ORDER BY {cache_key} LIMIT 1 OFFSET %%s" def unification_cast_sql(self, output_field): """ Given a field instance, return the SQL that casts the result of a union to that type. The resulting string should contain a '%s' placeholder for the expression being cast. """ return "%s" def date_extract_sql(self, lookup_type, sql, params): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that extracts a value from the given date field field_name. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a date_extract_sql() " "method" ) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that truncates the given date or datetime field field_name to a date object with only the given specificity. If `tzname` is provided, the given value is truncated in a specific timezone. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a date_trunc_sql() " "method." ) def datetime_cast_date_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to date value. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "datetime_cast_date_sql() method." ) def datetime_cast_time_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to time value. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "datetime_cast_time_sql() method" ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that extracts a value from the given datetime field field_name. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() " "method" ) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that truncates the given datetime field field_name to a datetime object with only the given specificity. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() " "method" ) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'hour', 'minute' or 'second', return the SQL that truncates the given time or datetime field field_name to a time object with only the given specificity. If `tzname` is provided, the given value is truncated in a specific timezone. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a time_trunc_sql() method" ) def time_extract_sql(self, lookup_type, sql, params): """ Given a lookup_type of 'hour', 'minute', or 'second', return the SQL that extracts a value from the given time field field_name. """ return self.date_extract_sql(lookup_type, sql, params) def deferrable_sql(self): """ Return the SQL to make a constraint "initially deferred" during a CREATE TABLE statement. """ return "" def distinct_sql(self, fields, params): """ Return an SQL DISTINCT clause which removes duplicate rows from the result set. If any fields are given, only check the given fields for duplicates. """ if fields: raise NotSupportedError( "DISTINCT ON fields is not supported by this database backend" ) else: return ["DISTINCT"], [] def fetch_returned_insert_columns(self, cursor, returning_params): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the newly created data. """ return cursor.fetchone() def field_cast_sql(self, db_type, internal_type): """ Given a column type (e.g. 'BLOB', 'VARCHAR') and an internal type (e.g. 'GenericIPAddressField'), return the SQL to cast it before using it in a WHERE statement. The resulting string should contain a '%s' placeholder for the column being searched against. """ return "%s" def force_no_ordering(self): """ Return a list used in the "ORDER BY" clause to force no ordering at all. Return an empty list to include nothing in the ordering. """ return [] def for_update_sql(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return the FOR UPDATE SQL clause to lock rows for an update operation. """ return "FOR%s UPDATE%s%s%s" % ( " NO KEY" if no_key else "", " OF %s" % ", ".join(of) if of else "", " NOWAIT" if nowait else "", " SKIP LOCKED" if skip_locked else "", ) def _get_limit_offset_params(self, low_mark, high_mark): offset = low_mark or 0 if high_mark is not None: return (high_mark - offset), offset elif offset: return self.connection.ops.no_limit_value(), offset return None, offset def limit_offset_sql(self, low_mark, high_mark): """Return LIMIT/OFFSET SQL clause.""" limit, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( ("LIMIT %d" % limit) if limit else None, ("OFFSET %d" % offset) if offset else None, ) if sql ) def last_executed_query(self, cursor, sql, params): """ Return a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide a better implementation according to their own quoting schemes. """ # Convert params to contain string values. def to_string(s): return force_str(s, strings_only=True, errors="replace") if isinstance(params, (list, tuple)): u_params = tuple(to_string(val) for val in params) elif params is None: u_params = () else: u_params = {to_string(k): to_string(v) for k, v in params.items()} return "QUERY = %r - PARAMS = %r" % (sql, u_params) def last_insert_id(self, cursor, table_name, pk_name): """ Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, return the newly created ID. `pk_name` is the name of the primary-key column. """ return cursor.lastrowid def lookup_cast(self, lookup_type, internal_type=None): """ Return the string to use in a query when performing lookups ("contains", "like", etc.). It should contain a '%s' placeholder for the column being searched against. """ return "%s" def max_in_list_size(self): """ Return the maximum number of items that can be passed in a single 'IN' list condition, or None if the backend does not impose a limit. """ return None def max_name_length(self): """ Return the maximum length of table and column names, or None if there is no limit. """ return None def no_limit_value(self): """ Return the value to use for the LIMIT when we are wanting "LIMIT infinity". Return None if the limit clause can be omitted in this case. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a no_limit_value() method" ) def pk_default_value(self): """ Return the value to use during an INSERT statement to specify that the field should use its default value. """ return "DEFAULT" def prepare_sql_script(self, sql): """ Take an SQL script that may contain multiple lines and return a list of statements to feed to successive cursor.execute() calls. Since few databases are able to process raw SQL scripts in a single cursor.execute() call and PEP 249 doesn't talk about this use case, the default implementation is conservative. """ return [ sqlparse.format(statement, strip_comments=True) for statement in sqlparse.split(sql) if statement ] def process_clob(self, value): """ Return the value of a CLOB column, for backends that return a locator object that requires additional processing. """ return value def return_insert_columns(self, fields): """ For backends that support returning columns as part of an insert query, return the SQL and params to append to the INSERT query. The returned fragment should contain a format string to hold the appropriate column. """ pass def compiler(self, compiler_name): """ Return the SQLCompiler class corresponding to the given name, in the namespace corresponding to the `compiler_module` attribute on this backend. """ if self._cache is None: self._cache = import_module(self.compiler_module) return getattr(self._cache, compiler_name) def quote_name(self, name): """ Return a quoted version of the given table, index, or column name. Do not quote the given name if it's already been quoted. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a quote_name() method" ) def regex_lookup(self, lookup_type): """ Return the string to use in a query when performing regular expression lookups (using "regex" or "iregex"). It should contain a '%s' placeholder for the column being searched against. If the feature is not supported (or part of it is not supported), raise NotImplementedError. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a regex_lookup() method" ) def savepoint_create_sql(self, sid): """ Return the SQL for starting a new savepoint. Only required if the "uses_savepoints" feature is True. The "sid" parameter is a string for the savepoint id. """ return "SAVEPOINT %s" % self.quote_name(sid) def savepoint_commit_sql(self, sid): """ Return the SQL for committing the given savepoint. """ return "RELEASE SAVEPOINT %s" % self.quote_name(sid) def savepoint_rollback_sql(self, sid): """ Return the SQL for rolling back the given savepoint. """ return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid) def set_time_zone_sql(self): """ Return the SQL that will set the connection's time zone. Return '' if the backend doesn't support time zones. """ return "" def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): """ Return a list of SQL statements required to remove all data from the given database tables (without actually removing the tables themselves). The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. If `reset_sequences` is True, the list includes SQL statements required to reset the sequences. The `allow_cascade` argument determines whether truncation may cascade to tables with foreign keys pointing the tables being truncated. PostgreSQL requires a cascade even if these tables are empty. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations must provide an sql_flush() method" ) def execute_sql_flush(self, sql_list): """Execute a list of SQL statements to flush the database.""" with transaction.atomic( using=self.connection.alias, savepoint=self.connection.features.can_rollback_ddl, ): with self.connection.cursor() as cursor: for sql in sql_list: cursor.execute(sql) def sequence_reset_by_name_sql(self, style, sequences): """ Return a list of the SQL statements required to reset sequences passed in `sequences`. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] def sequence_reset_sql(self, style, model_list): """ Return a list of the SQL statements required to reset sequences for the given models. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] # No sequence reset required by default. def start_transaction_sql(self): """Return the SQL statement required to start a transaction.""" return "BEGIN;" def end_transaction_sql(self, success=True): """Return the SQL statement required to end a transaction.""" if not success: return "ROLLBACK;" return "COMMIT;" def tablespace_sql(self, tablespace, inline=False): """ Return the SQL that will be used in a query to define the tablespace. Return '' if the backend doesn't support tablespaces. If `inline` is True, append the SQL to a row; otherwise append it to the entire CREATE TABLE or CREATE INDEX statement. """ return "" def prep_for_like_query(self, x): """Prepare a value for use in a LIKE query.""" return str(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_") # Same as prep_for_like_query(), but called for "iexact" matches, which # need not necessarily be implemented using "LIKE" in the backend. prep_for_iexact_query = prep_for_like_query def validate_autopk_value(self, value): """ Certain backends do not accept some values for "serial" fields (for example zero in MySQL). Raise a ValueError if the value is invalid, otherwise return the validated value. """ return value def adapt_unknown_value(self, value): """ Transform a value to something compatible with the backend driver. This method only depends on the type of the value. It's designed for cases where the target type isn't known, such as .raw() SQL queries. As a consequence it may not work perfectly in all circumstances. """ if isinstance(value, datetime.datetime): # must be before date return self.adapt_datetimefield_value(value) elif isinstance(value, datetime.date): return self.adapt_datefield_value(value) elif isinstance(value, datetime.time): return self.adapt_timefield_value(value) elif isinstance(value, decimal.Decimal): return self.adapt_decimalfield_value(value) else: return value def adapt_integerfield_value(self, value, internal_type): return value def adapt_datefield_value(self, value): """ Transform a date value to an object compatible with what is expected by the backend driver for date columns. """ if value is None: return None return str(value) def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value return str(value) def adapt_timefield_value(self, value): """ Transform a time value to an object compatible with what is expected by the backend driver for time columns. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value if timezone.is_aware(value): raise ValueError("Django does not support timezone-aware times.") return str(value) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): """ Transform a decimal.Decimal value to an object compatible with what is expected by the backend driver for decimal (numeric) columns. """ return utils.format_number(value, max_digits, decimal_places) def adapt_ipaddressfield_value(self, value): """ Transform a string representation of an IP address into the expected type for the backend driver. """ return value or None def adapt_json_value(self, value, encoder): return json.dumps(value, cls=encoder) def year_lookup_bounds_for_date_field(self, value, iso_year=False): """ Return a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateField value using a year lookup. `value` is an int, containing the looked-up year. If `iso_year` is True, return bounds for ISO-8601 week-numbering years. """ if iso_year: first = datetime.date.fromisocalendar(value, 1, 1) second = datetime.date.fromisocalendar( value + 1, 1, 1 ) - datetime.timedelta(days=1) else: first = datetime.date(value, 1, 1) second = datetime.date(value, 12, 31) first = self.adapt_datefield_value(first) second = self.adapt_datefield_value(second) return [first, second] def year_lookup_bounds_for_datetime_field(self, value, iso_year=False): """ Return a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateTimeField value using a year lookup. `value` is an int, containing the looked-up year. If `iso_year` is True, return bounds for ISO-8601 week-numbering years. """ if iso_year: first = datetime.datetime.fromisocalendar(value, 1, 1) second = datetime.datetime.fromisocalendar( value + 1, 1, 1 ) - datetime.timedelta(microseconds=1) else: first = datetime.datetime(value, 1, 1) second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999) if settings.USE_TZ: tz = timezone.get_current_timezone() first = timezone.make_aware(first, tz) second = timezone.make_aware(second, tz) first = self.adapt_datetimefield_value(first) second = self.adapt_datetimefield_value(second) return [first, second] def get_db_converters(self, expression): """ Return a list of functions needed to convert field data. Some field types on some backends do not provide data in the correct format, this is the hook for converter functions. """ return [] def convert_durationfield_value(self, value, expression, connection): if value is not None: return datetime.timedelta(0, 0, value) def check_expression_support(self, expression): """ Check that the backend supports the provided expression. This is used on specific backends to rule out known expressions that have problematic or nonexistent implementations. If the expression has a known problem, the backend should raise NotSupportedError. """ pass def conditional_expression_supported_in_where_clause(self, expression): """ Return True, if the conditional expression is supported in the WHERE clause. """ return True def combine_expression(self, connector, sub_expressions): """ Combine a list of subexpressions into a single expression, using the provided connecting operator. This is required because operators can vary between backends (e.g., Oracle with %% and &) and between subexpression types (e.g., date expressions). """ conn = " %s " % connector return conn.join(sub_expressions) def combine_duration_expression(self, connector, sub_expressions): return self.combine_expression(connector, sub_expressions) def binary_placeholder_sql(self, value): """ Some backends require special syntax to insert binary content (MySQL for example uses '_binary %s'). """ return "%s" def modify_insert_params(self, placeholder, params): """ Allow modification of insert parameters. Needed for Oracle Spatial backend due to #10888. """ return params def integer_field_range(self, internal_type): """ Given an integer field internal type (e.g. 'PositiveIntegerField'), return a tuple of the (min_value, max_value) form representing the range of the column type bound to the field. """ return self.integer_field_ranges[internal_type] def subtract_temporals(self, internal_type, lhs, rhs): if self.connection.features.supports_temporal_subtraction: lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs return "(%s - %s)" % (lhs_sql, rhs_sql), (*lhs_params, *rhs_params) raise NotSupportedError( "This backend does not support %s subtraction." % internal_type ) def window_frame_start(self, start): if isinstance(start, int): if start < 0: return "%d %s" % (abs(start), self.PRECEDING) elif start == 0: return self.CURRENT_ROW elif start is None: return self.UNBOUNDED_PRECEDING raise ValueError( "start argument must be a negative integer, zero, or None, but got '%s'." % start ) def window_frame_end(self, end): if isinstance(end, int): if end == 0: return self.CURRENT_ROW elif end > 0: return "%d %s" % (end, self.FOLLOWING) elif end is None: return self.UNBOUNDED_FOLLOWING raise ValueError( "end argument must be a positive integer, zero, or None, but got '%s'." % end ) def window_frame_rows_start_end(self, start=None, end=None): """ Return SQL for start and end points in an OVER clause window frame. """ if not self.connection.features.supports_over_clause: raise NotSupportedError("This backend does not support window expressions.") return self.window_frame_start(start), self.window_frame_end(end) def window_frame_range_start_end(self, start=None, end=None): start_, end_ = self.window_frame_rows_start_end(start, end) features = self.connection.features if features.only_supports_unbounded_with_preceding_and_following and ( (start and start < 0) or (end and end > 0) ): raise NotSupportedError( "%s only supports UNBOUNDED together with PRECEDING and " "FOLLOWING." % self.connection.display_name ) return start_, end_ def explain_query_prefix(self, format=None, **options): if not self.connection.features.supports_explaining_query_execution: raise NotSupportedError( "This backend does not support explaining query execution." ) if format: supported_formats = self.connection.features.supported_explain_formats normalized_format = format.upper() if normalized_format not in supported_formats: msg = "%s is not a recognized format." % normalized_format if supported_formats: msg += " Allowed formats: %s" % ", ".join(sorted(supported_formats)) else: msg += ( f" {self.connection.display_name} does not support any formats." ) raise ValueError(msg) if options: raise ValueError("Unknown options: %s" % ", ".join(sorted(options.keys()))) return self.explain_prefix def insert_statement(self, on_conflict=None): return "INSERT INTO" def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): return "" def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field): lhs_expr = Col(lhs_table, lhs_field) rhs_expr = Col(rhs_table, rhs_field) return lhs_expr, rhs_expr
5cd3f404aa026b968121bb0a295800bc770adcde5ade576eb4df324c04fd1808
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_selected_pks = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True atomic_transactions = False can_clone_databases = True supports_comments = True supports_comments_inline = True supports_temporal_subtraction = True supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True delete_can_self_reference_subquery = False create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (8,) @cached_property def test_collations(self): charset = "utf8" if ( self.connection.mysql_is_mariadb and self.connection.mysql_version >= (10, 6) ) or ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 30) ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+ and MySQL 8.0.30+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP(6)" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, "UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by" "related fields.": { "update.tests.AdvancedTests." "test_update_ordered_by_inline_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation_desc", }, } if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY cannot contain nonaggregated column when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #34262.": { "aggregation.tests.AggregateTestCase." "test_group_by_nested_expression_with_params", }, } ) if self.connection.mysql_version < (8, 0, 31): skips.update( { "Nesting of UNIONs at the right-hand side is not supported on " "MySQL < 8.0.31": { "queries.test_qs_combinators.QuerySetSetOperationTests." "test_union_nested" }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.can_introspect_check_constraints return True @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def supports_select_intersection(self): is_mariadb = self.connection.mysql_is_mariadb return is_mariadb or self.connection.mysql_version >= (8, 0, 31) supports_select_difference = property( operator.attrgetter("supports_select_intersection") ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
50bf5059b268ddbce87ed0060423e45550836302f74535cec342ef65d48bb985
""" PostgreSQL database backend for Django. Requires psycopg2 >= 2.8.4 or psycopg >= 3.1.8 """ import asyncio import threading import warnings from contextlib import contextmanager from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import DatabaseError as WrappedDatabaseError from django.db import connections from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.utils import CursorDebugWrapper as BaseCursorDebugWrapper from django.utils.asyncio import async_unsafe from django.utils.functional import cached_property from django.utils.safestring import SafeString from django.utils.version import get_version_tuple try: try: import psycopg as Database except ImportError: import psycopg2 as Database except ImportError: raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") def psycopg_version(): version = Database.__version__.split(" ", 1)[0] return get_version_tuple(version) if psycopg_version() < (2, 8, 4): raise ImproperlyConfigured( f"psycopg2 version 2.8.4 or newer is required; you have {Database.__version__}" ) if (3,) <= psycopg_version() < (3, 1, 8): raise ImproperlyConfigured( f"psycopg version 3.1.8 or newer is required; you have {Database.__version__}" ) from .psycopg_any import IsolationLevel, is_psycopg3 # NOQA isort:skip if is_psycopg3: from psycopg import adapters, sql from psycopg.pq import Format from .psycopg_any import get_adapters_template, register_tzloader TIMESTAMPTZ_OID = adapters.types["timestamptz"].oid else: import psycopg2.extensions import psycopg2.extras psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString) psycopg2.extras.register_uuid() # Register support for inet[] manually so we don't have to handle the Inet() # object on load all the time. INETARRAY_OID = 1041 INETARRAY = psycopg2.extensions.new_array_type( (INETARRAY_OID,), "INETARRAY", psycopg2.extensions.UNICODE, ) psycopg2.extensions.register_type(INETARRAY) # Some of these import psycopg, so import them after checking if it's installed. from .client import DatabaseClient # NOQA isort:skip from .creation import DatabaseCreation # NOQA isort:skip from .features import DatabaseFeatures # NOQA isort:skip from .introspection import DatabaseIntrospection # NOQA isort:skip from .operations import DatabaseOperations # NOQA isort:skip from .schema import DatabaseSchemaEditor # NOQA isort:skip def _get_varchar_column(data): if data["max_length"] is None: return "varchar" return "varchar(%(max_length)s)" % data class DatabaseWrapper(BaseDatabaseWrapper): vendor = "postgresql" display_name = "PostgreSQL" # This dictionary maps Field objects to their associated PostgreSQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. data_types = { "AutoField": "integer", "BigAutoField": "bigint", "BinaryField": "bytea", "BooleanField": "boolean", "CharField": _get_varchar_column, "DateField": "date", "DateTimeField": "timestamp with time zone", "DecimalField": "numeric(%(max_digits)s, %(decimal_places)s)", "DurationField": "interval", "FileField": "varchar(%(max_length)s)", "FilePathField": "varchar(%(max_length)s)", "FloatField": "double precision", "IntegerField": "integer", "BigIntegerField": "bigint", "IPAddressField": "inet", "GenericIPAddressField": "inet", "JSONField": "jsonb", "OneToOneField": "integer", "PositiveBigIntegerField": "bigint", "PositiveIntegerField": "integer", "PositiveSmallIntegerField": "smallint", "SlugField": "varchar(%(max_length)s)", "SmallAutoField": "smallint", "SmallIntegerField": "smallint", "TextField": "text", "TimeField": "time", "UUIDField": "uuid", } data_type_check_constraints = { "PositiveBigIntegerField": '"%(column)s" >= 0', "PositiveIntegerField": '"%(column)s" >= 0', "PositiveSmallIntegerField": '"%(column)s" >= 0', } data_types_suffix = { "AutoField": "GENERATED BY DEFAULT AS IDENTITY", "BigAutoField": "GENERATED BY DEFAULT AS IDENTITY", "SmallAutoField": "GENERATED BY DEFAULT AS IDENTITY", } operators = { "exact": "= %s", "iexact": "= UPPER(%s)", "contains": "LIKE %s", "icontains": "LIKE UPPER(%s)", "regex": "~ %s", "iregex": "~* %s", "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", "startswith": "LIKE %s", "endswith": "LIKE %s", "istartswith": "LIKE UPPER(%s)", "iendswith": "LIKE UPPER(%s)", } # The patterns below are used to generate SQL pattern lookup clauses when # the right-hand side of the lookup isn't a raw string (it might be an expression # or the result of a bilateral transformation). # In those cases, special characters for LIKE operators (e.g. \, *, _) should be # escaped on database side. # # Note: we use str.format() here for readability as '%' is used as a wildcard for # the LIKE operator. pattern_esc = ( r"REPLACE(REPLACE(REPLACE({}, E'\\', E'\\\\'), E'%%', E'\\%%'), E'_', E'\\_')" ) pattern_ops = { "contains": "LIKE '%%' || {} || '%%'", "icontains": "LIKE '%%' || UPPER({}) || '%%'", "startswith": "LIKE {} || '%%'", "istartswith": "LIKE UPPER({}) || '%%'", "endswith": "LIKE '%%' || {}", "iendswith": "LIKE '%%' || UPPER({})", } Database = Database SchemaEditorClass = DatabaseSchemaEditor # Classes instantiated in __init__(). client_class = DatabaseClient creation_class = DatabaseCreation features_class = DatabaseFeatures introspection_class = DatabaseIntrospection ops_class = DatabaseOperations # PostgreSQL backend-specific attributes. _named_cursor_idx = 0 def get_database_version(self): """ Return a tuple of the database's version. E.g. for pg_version 120004, return (12, 4). """ return divmod(self.pg_version, 10000) def get_connection_params(self): settings_dict = self.settings_dict # None may be used to connect to the default 'postgres' db if settings_dict["NAME"] == "" and not settings_dict.get("OPTIONS", {}).get( "service" ): raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME or OPTIONS['service'] value." ) if len(settings_dict["NAME"] or "") > self.ops.max_name_length(): raise ImproperlyConfigured( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %d characters. Supply a shorter NAME " "in settings.DATABASES." % ( settings_dict["NAME"], len(settings_dict["NAME"]), self.ops.max_name_length(), ) ) if settings_dict["NAME"]: conn_params = { "dbname": settings_dict["NAME"], **settings_dict["OPTIONS"], } elif settings_dict["NAME"] is None: # Connect to the default 'postgres' db. settings_dict.get("OPTIONS", {}).pop("service", None) conn_params = {"dbname": "postgres", **settings_dict["OPTIONS"]} else: conn_params = {**settings_dict["OPTIONS"]} conn_params["client_encoding"] = "UTF8" conn_params.pop("assume_role", None) conn_params.pop("isolation_level", None) server_side_binding = conn_params.pop("server_side_binding", None) conn_params.setdefault( "cursor_factory", ServerBindingCursor if is_psycopg3 and server_side_binding is True else Cursor, ) if settings_dict["USER"]: conn_params["user"] = settings_dict["USER"] if settings_dict["PASSWORD"]: conn_params["password"] = settings_dict["PASSWORD"] if settings_dict["HOST"]: conn_params["host"] = settings_dict["HOST"] if settings_dict["PORT"]: conn_params["port"] = settings_dict["PORT"] if is_psycopg3: conn_params["context"] = get_adapters_template( settings.USE_TZ, self.timezone ) # Disable prepared statements by default to keep connection poolers # working. Can be reenabled via OPTIONS in the settings dict. conn_params["prepare_threshold"] = conn_params.pop( "prepare_threshold", None ) return conn_params @async_unsafe def get_new_connection(self, conn_params): # self.isolation_level must be set: # - after connecting to the database in order to obtain the database's # default when no value is explicitly specified in options. # - before calling _set_autocommit() because if autocommit is on, that # will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT. options = self.settings_dict["OPTIONS"] set_isolation_level = False try: isolation_level_value = options["isolation_level"] except KeyError: self.isolation_level = IsolationLevel.READ_COMMITTED else: # Set the isolation level to the value from OPTIONS. try: self.isolation_level = IsolationLevel(isolation_level_value) set_isolation_level = True except ValueError: raise ImproperlyConfigured( f"Invalid transaction isolation level {isolation_level_value} " f"specified. Use one of the psycopg.IsolationLevel values." ) connection = self.Database.connect(**conn_params) if set_isolation_level: connection.isolation_level = self.isolation_level if not is_psycopg3: # Register dummy loads() to avoid a round trip from psycopg2's # decode to json.dumps() to json.loads(), when using a custom # decoder in JSONField. psycopg2.extras.register_default_jsonb( conn_or_curs=connection, loads=lambda x: x ) return connection def ensure_timezone(self): if self.connection is None: return False conn_timezone_name = self.connection.info.parameter_status("TimeZone") timezone_name = self.timezone_name if timezone_name and conn_timezone_name != timezone_name: with self.connection.cursor() as cursor: cursor.execute(self.ops.set_time_zone_sql(), [timezone_name]) return True return False def ensure_role(self): if self.connection is None: return False if new_role := self.settings_dict.get("OPTIONS", {}).get("assume_role"): with self.connection.cursor() as cursor: sql = self.ops.compose_sql("SET ROLE %s", [new_role]) cursor.execute(sql) return True return False def init_connection_state(self): super().init_connection_state() # Commit after setting the time zone. commit_tz = self.ensure_timezone() # Set the role on the connection. This is useful if the credential used # to login is not the same as the role that owns database resources. As # can be the case when using temporary or ephemeral credentials. commit_role = self.ensure_role() if (commit_role or commit_tz) and not self.get_autocommit(): self.connection.commit() @async_unsafe def create_cursor(self, name=None): if name: # In autocommit mode, the cursor will be used outside of a # transaction, hence use a holdable cursor. cursor = self.connection.cursor( name, scrollable=False, withhold=self.connection.autocommit ) else: cursor = self.connection.cursor() if is_psycopg3: # Register the cursor timezone only if the connection disagrees, to # avoid copying the adapter map. tzloader = self.connection.adapters.get_loader(TIMESTAMPTZ_OID, Format.TEXT) if self.timezone != tzloader.timezone: register_tzloader(self.timezone, cursor) else: cursor.tzinfo_factory = self.tzinfo_factory if settings.USE_TZ else None return cursor def tzinfo_factory(self, offset): return self.timezone @async_unsafe def chunked_cursor(self): self._named_cursor_idx += 1 # Get the current async task # Note that right now this is behind @async_unsafe, so this is # unreachable, but in future we'll start loosening this restriction. # For now, it's here so that every use of "threading" is # also async-compatible. try: current_task = asyncio.current_task() except RuntimeError: current_task = None # Current task can be none even if the current_task call didn't error if current_task: task_ident = str(id(current_task)) else: task_ident = "sync" # Use that and the thread ident to get a unique name return self._cursor( name="_django_curs_%d_%s_%d" % ( # Avoid reusing name in other threads / tasks threading.current_thread().ident, task_ident, self._named_cursor_idx, ) ) def _set_autocommit(self, autocommit): with self.wrap_database_errors: self.connection.autocommit = autocommit def check_constraints(self, table_names=None): """ Check constraints by setting them to immediate. Return them to deferred afterward. """ with self.cursor() as cursor: cursor.execute("SET CONSTRAINTS ALL IMMEDIATE") cursor.execute("SET CONSTRAINTS ALL DEFERRED") def is_usable(self): try: # Use a psycopg cursor directly, bypassing Django's utilities. with self.connection.cursor() as cursor: cursor.execute("SELECT 1") except Database.Error: return False else: return True @contextmanager def _nodb_cursor(self): cursor = None try: with super()._nodb_cursor() as cursor: yield cursor except (Database.DatabaseError, WrappedDatabaseError): if cursor is not None: raise warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the first PostgreSQL database instead.", RuntimeWarning, ) for connection in connections.all(): if ( connection.vendor == "postgresql" and connection.settings_dict["NAME"] != "postgres" ): conn = self.__class__( { **self.settings_dict, "NAME": connection.settings_dict["NAME"], }, alias=self.alias, ) try: with conn.cursor() as cursor: yield cursor finally: conn.close() break else: raise @cached_property def pg_version(self): with self.temporary_connection(): return self.connection.info.server_version def make_debug_cursor(self, cursor): return CursorDebugWrapper(cursor, self) if is_psycopg3: class CursorMixin: """ A subclass of psycopg cursor implementing callproc. """ def callproc(self, name, args=None): if not isinstance(name, sql.Identifier): name = sql.Identifier(name) qparts = [sql.SQL("SELECT * FROM "), name, sql.SQL("(")] if args: for item in args: qparts.append(sql.Literal(item)) qparts.append(sql.SQL(",")) del qparts[-1] qparts.append(sql.SQL(")")) stmt = sql.Composed(qparts) self.execute(stmt) return args class ServerBindingCursor(CursorMixin, Database.Cursor): pass class Cursor(CursorMixin, Database.ClientCursor): pass class CursorDebugWrapper(BaseCursorDebugWrapper): def copy(self, statement): with self.debug_sql(statement): return self.cursor.copy(statement) else: Cursor = psycopg2.extensions.cursor class CursorDebugWrapper(BaseCursorDebugWrapper): def copy_expert(self, sql, file, *args): with self.debug_sql(sql): return self.cursor.copy_expert(sql, file, *args) def copy_to(self, file, table, *args, **kwargs): with self.debug_sql(sql="COPY %s TO STDOUT" % table): return self.cursor.copy_to(file, table, *args, **kwargs)
6734b69f008d482f5ec607741cbac0e0bb5e3b70f3379813fd98197f4e7b5f9d
import json from functools import lru_cache, partial from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.postgresql.psycopg_any import ( Inet, Jsonb, errors, is_psycopg3, mogrify, ) from django.db.backends.utils import split_tzname_delta from django.db.models.constants import OnConflict from django.db.models.functions import Cast from django.utils.regex_helper import _lazy_re_compile @lru_cache def get_json_dumps(encoder): if encoder is None: return json.dumps return partial(json.dumps, cls=encoder) class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", "SETTINGS", "SUMMARY", "TIMING", "VERBOSE", "WAL", ] ) cast_data_types = { "AutoField": "integer", "BigAutoField": "bigint", "SmallAutoField": "smallint", } if is_psycopg3: from psycopg.types import numeric integerfield_type_map = { "SmallIntegerField": numeric.Int2, "IntegerField": numeric.Int4, "BigIntegerField": numeric.Int8, "PositiveSmallIntegerField": numeric.Int2, "PositiveIntegerField": numeric.Int4, "PositiveBigIntegerField": numeric.Int8, } def unification_cast_sql(self, output_field): internal_type = output_field.get_internal_type() if internal_type in ( "GenericIPAddressField", "IPAddressField", "TimeField", "UUIDField", ): # PostgreSQL will resolve a union as type 'text' if input types are # 'unknown'. # https://www.postgresql.org/docs/current/typeconv-union-case.html # These fields cannot be implicitly cast back in the default # PostgreSQL configuration so we need to explicitly cast them. # We must also remove components of the type within brackets: # varchar(255) -> varchar. return ( "CAST(%%s AS %s)" % output_field.db_type(self.connection).split("(")[0] ) return "%s" # EXTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT if lookup_type == "week_day": # For consistency across backends, we return Sunday=1, Saturday=7. return f"EXTRACT(DOW FROM {sql}) + 1", params elif lookup_type == "iso_week_day": return f"EXTRACT(ISODOW FROM {sql})", params elif lookup_type == "iso_year": return f"EXTRACT(ISOYEAR FROM {sql})", params lookup_type = lookup_type.upper() if not self._extract_format_re.fullmatch(lookup_type): raise ValueError(f"Invalid lookup type: {lookup_type!r}") return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params) def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) if offset: sign = "-" if sign == "+" else "+" return f"{tzname}{sign}{offset}" return tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ: tzname_param = self._prepare_tzname_delta(tzname) return f"{sql} AT TIME ZONE %s", (*params, tzname_param) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"({sql})::date", params def datetime_cast_time_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"({sql})::time", params def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) if lookup_type == "second": # Truncate fractional seconds. return f"EXTRACT(SECOND FROM DATE_TRUNC(%s, {sql}))", ("second", *params) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params) def time_extract_sql(self, lookup_type, sql, params): if lookup_type == "second": # Truncate fractional seconds. return f"EXTRACT(SECOND FROM DATE_TRUNC(%s, {sql}))", ("second", *params) return self.date_extract_sql(lookup_type, sql, params) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE_TRUNC(%s, {sql})::time", (lookup_type, *params) def deferrable_sql(self): return " DEFERRABLE INITIALLY DEFERRED" def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the tuple of returned data. """ return cursor.fetchall() def lookup_cast(self, lookup_type, internal_type=None): lookup = "%s" if lookup_type == "isnull" and internal_type in ( "CharField", "EmailField", "TextField", "CICharField", "CIEmailField", "CITextField", ): return "%s::text" # Cast text lookups to text to allow things like filter(x__contains=4) if lookup_type in ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ): if internal_type in ("IPAddressField", "GenericIPAddressField"): lookup = "HOST(%s)" # RemovedInDjango51Warning. elif internal_type in ("CICharField", "CIEmailField", "CITextField"): lookup = "%s::citext" else: lookup = "%s::text" # Use UPPER(x) for case-insensitive lookups; it's faster. if lookup_type in ("iexact", "icontains", "istartswith", "iendswith"): lookup = "UPPER(%s)" % lookup return lookup def no_limit_value(self): return None def prepare_sql_script(self, sql): return [sql] def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def compose_sql(self, sql, params): return mogrify(sql, params, self.connection) def set_time_zone_sql(self): return "SELECT set_config('TimeZone', %s, false)" def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows us # to truncate tables referenced by a foreign key in any other table. sql_parts = [ style.SQL_KEYWORD("TRUNCATE"), ", ".join(style.SQL_FIELD(self.quote_name(table)) for table in tables), ] if reset_sequences: sql_parts.append(style.SQL_KEYWORD("RESTART IDENTITY")) if allow_cascade: sql_parts.append(style.SQL_KEYWORD("CASCADE")) return ["%s;" % " ".join(sql_parts)] def sequence_reset_by_name_sql(self, style, sequences): # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements # to reset sequence indices sql = [] for sequence_info in sequences: table_name = sequence_info["table"] # 'id' will be the case if it's an m2m using an autogenerated # intermediate table (see BaseDatabaseIntrospection.sequence_list). column_name = sequence_info["column"] or "id" sql.append( "%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % ( style.SQL_KEYWORD("SELECT"), style.SQL_TABLE(self.quote_name(table_name)), style.SQL_FIELD(column_name), ) ) return sql def tablespace_sql(self, tablespace, inline=False): if inline: return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace) else: return "TABLESPACE %s" % self.quote_name(tablespace) def sequence_reset_sql(self, style, model_list): from django.db import models output = [] qn = self.quote_name for model in model_list: # Use `coalesce` to set the sequence for each model to the max pk # value if there are records, or 1 if there are none. Set the # `is_called` property (the third argument to `setval`) to true if # there are records (as the max pk value is already in use), # otherwise set it to false. Use pg_get_serial_sequence to get the # underlying sequence name from the table name and column name. for f in model._meta.local_fields: if isinstance(f, models.AutoField): output.append( "%s setval(pg_get_serial_sequence('%s','%s'), " "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % ( style.SQL_KEYWORD("SELECT"), style.SQL_TABLE(qn(model._meta.db_table)), style.SQL_FIELD(f.column), style.SQL_FIELD(qn(f.column)), style.SQL_FIELD(qn(f.column)), style.SQL_KEYWORD("IS NOT"), style.SQL_KEYWORD("FROM"), style.SQL_TABLE(qn(model._meta.db_table)), ) ) # Only one AutoField is allowed per model, so don't bother # continuing. break return output def prep_for_iexact_query(self, x): return x def max_name_length(self): """ Return the maximum length of an identifier. The maximum length of an identifier is 63 by default, but can be changed by recompiling PostgreSQL after editing the NAMEDATALEN macro in src/include/pg_config_manual.h. This implementation returns 63, but can be overridden by a custom database backend that inherits most of its behavior from this one. """ return 63 def distinct_sql(self, fields, params): if fields: params = [param for param_list in params for param in param_list] return (["DISTINCT ON (%s)" % ", ".join(fields)], params) else: return ["DISTINCT"], [] if is_psycopg3: def last_executed_query(self, cursor, sql, params): try: return self.compose_sql(sql, params) except errors.DataError: return None else: def last_executed_query(self, cursor, sql, params): # https://www.psycopg.org/docs/cursor.html#cursor.query # The query attribute is a Psycopg extension to the DB API 2.0. if cursor.query is not None: return cursor.query.decode() return None def return_insert_columns(self, fields): if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql) return "VALUES " + values_sql if is_psycopg3: def adapt_integerfield_value(self, value, internal_type): if value is None or hasattr(value, "resolve_expression"): return value return self.integerfield_type_map[internal_type](value) def adapt_datefield_value(self, value): return value def adapt_datetimefield_value(self, value): return value def adapt_timefield_value(self, value): return value def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def adapt_ipaddressfield_value(self, value): if value: return Inet(value) return None def adapt_json_value(self, value, encoder): return Jsonb(value, dumps=get_json_dumps(encoder)) def subtract_temporals(self, internal_type, lhs, rhs): if internal_type == "DateField": lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) return "(interval '1 day' * (%s - %s))" % (lhs_sql, rhs_sql), params return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else "false" for name, value in options.items() } for valid_option in self.explain_options: value = options.pop(valid_option, None) if value is not None: extra[valid_option] = value prefix = super().explain_query_prefix(format, **options) if format: extra["FORMAT"] = format if extra: prefix += " (%s)" % ", ".join("%s %s" % i for i in extra.items()) return prefix def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if on_conflict == OnConflict.IGNORE: return "ON CONFLICT DO NOTHING" if on_conflict == OnConflict.UPDATE: return "ON CONFLICT(%s) DO UPDATE SET %s" % ( ", ".join(map(self.quote_name, unique_fields)), ", ".join( [ f"{field} = EXCLUDED.{field}" for field in map(self.quote_name, update_fields) ] ), ) return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, ) def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field): lhs_expr, rhs_expr = super().prepare_join_on_clause( lhs_table, lhs_field, rhs_table, rhs_field ) if lhs_field.db_type(self.connection) != rhs_field.db_type(self.connection): rhs_expr = Cast(rhs_expr, lhs_field) return lhs_expr, rhs_expr
96e5e107a8b635f5e5d1c2ea5a389a865a8dd2215b62b8163c0308ad1a3636b0
from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.ddl_references import IndexColumns from django.db.backends.postgresql.psycopg_any import sql from django.db.backends.utils import strip_quotes class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): # Setting all constraints to IMMEDIATE to allow changing data in the same # transaction. sql_update_with_default = ( "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL" "; SET CONSTRAINTS ALL IMMEDIATE" ) sql_alter_sequence_type = "ALTER SEQUENCE IF EXISTS %(sequence)s AS %(type)s" sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE" sql_create_index = ( "CREATE INDEX %(name)s ON %(table)s%(using)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_create_index_concurrently = ( "CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_delete_index = "DROP INDEX IF EXISTS %(name)s" sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)s" # Setting the constraint to IMMEDIATE to allow changing data in the same # transaction. sql_create_column_inline_fk = ( "CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(deferrable)s" "; SET CONSTRAINTS %(namespace)s%(name)s IMMEDIATE" ) # Setting the constraint to IMMEDIATE runs any deferred checks to allow # dropping it in the same transaction. sql_delete_fk = ( "SET CONSTRAINTS %(name)s IMMEDIATE; " "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" ) sql_delete_procedure = "DROP FUNCTION %(procedure)s(%(param_types)s)" def execute(self, sql, params=()): # Merge the query client-side, as PostgreSQL won't do it server-side. if params is None: return super().execute(sql, params) sql = self.connection.ops.compose_sql(str(sql), params) # Don't let the superclass touch anything. return super().execute(sql, None) sql_add_identity = ( "ALTER TABLE %(table)s ALTER COLUMN %(column)s ADD " "GENERATED BY DEFAULT AS IDENTITY" ) sql_drop_indentity = ( "ALTER TABLE %(table)s ALTER COLUMN %(column)s DROP IDENTITY IF EXISTS" ) def quote_value(self, value): if isinstance(value, str): value = value.replace("%", "%%") return sql.quote(value, self.connection.connection) def _field_indexes_sql(self, model, field): output = super()._field_indexes_sql(model, field) like_index_statement = self._create_like_index_sql(model, field) if like_index_statement is not None: output.append(like_index_statement) return output def _field_data_type(self, field): if field.is_relation: return field.rel_db_type(self.connection) return self.connection.data_types.get( field.get_internal_type(), field.db_type(self.connection), ) def _field_base_data_types(self, field): # Yield base data types for array fields. if field.base_field.get_internal_type() == "ArrayField": yield from self._field_base_data_types(field.base_field) else: yield self._field_data_type(field.base_field) def _create_like_index_sql(self, model, field): """ Return the statement to create an index with varchar operator pattern when the column type is 'varchar' or 'text', otherwise return None. """ db_type = field.db_type(connection=self.connection) if db_type is not None and (field.db_index or field.unique): # Fields with database column types of `varchar` and `text` need # a second index that specifies their operator class, which is # needed when performing correct LIKE queries outside the # C locale. See #12234. # # The same doesn't apply to array fields such as varchar[size] # and text[size], so skip them. if "[" in db_type: return None # Non-deterministic collations on Postgresql don't support indexes # for operator classes varchar_pattern_ops/text_pattern_ops. if getattr(field, "db_collation", None) or ( field.is_relation and getattr(field.target_field, "db_collation", None) ): return None if db_type.startswith("varchar"): return self._create_index_sql( model, fields=[field], suffix="_like", opclasses=["varchar_pattern_ops"], ) elif db_type.startswith("text"): return self._create_index_sql( model, fields=[field], suffix="_like", opclasses=["text_pattern_ops"], ) return None def _using_sql(self, new_field, old_field): using_sql = " USING %(column)s::%(type)s" new_internal_type = new_field.get_internal_type() old_internal_type = old_field.get_internal_type() if new_internal_type == "ArrayField" and new_internal_type == old_internal_type: # Compare base data types for array fields. if list(self._field_base_data_types(old_field)) != list( self._field_base_data_types(new_field) ): return using_sql elif self._field_data_type(old_field) != self._field_data_type(new_field): return using_sql return "" def _get_sequence_name(self, table, column): with self.connection.cursor() as cursor: for sequence in self.connection.introspection.get_sequences(cursor, table): if sequence["column"] == column: return sequence["name"] return None def _alter_column_type_sql( self, model, old_field, new_field, new_type, old_collation, new_collation ): # Drop indexes on varchar/text/citext columns that are changing to a # different type. old_db_params = old_field.db_parameters(connection=self.connection) old_type = old_db_params["type"] if (old_field.db_index or old_field.unique) and ( (old_type.startswith("varchar") and not new_type.startswith("varchar")) or (old_type.startswith("text") and not new_type.startswith("text")) or (old_type.startswith("citext") and not new_type.startswith("citext")) ): index_name = self._create_index_name( model._meta.db_table, [old_field.column], suffix="_like" ) self.execute(self._delete_index_sql(model, index_name)) self.sql_alter_column_type = ( "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s" ) # Cast when data type changed. if using_sql := self._using_sql(new_field, old_field): self.sql_alter_column_type += using_sql new_internal_type = new_field.get_internal_type() old_internal_type = old_field.get_internal_type() # Make ALTER TYPE with IDENTITY make sense. table = strip_quotes(model._meta.db_table) auto_field_types = { "AutoField", "BigAutoField", "SmallAutoField", } old_is_auto = old_internal_type in auto_field_types new_is_auto = new_internal_type in auto_field_types if new_is_auto and not old_is_auto: column = strip_quotes(new_field.column) return ( ( self.sql_alter_column_type % { "column": self.quote_name(column), "type": new_type, "collation": "", }, [], ), [ ( self.sql_add_identity % { "table": self.quote_name(table), "column": self.quote_name(column), }, [], ), ], ) elif old_is_auto and not new_is_auto: # Drop IDENTITY if exists (pre-Django 4.1 serial columns don't have # it). self.execute( self.sql_drop_indentity % { "table": self.quote_name(table), "column": self.quote_name(strip_quotes(new_field.column)), } ) column = strip_quotes(new_field.column) fragment, _ = super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) # Drop the sequence if exists (Django 4.1+ identity columns don't # have it). other_actions = [] if sequence_name := self._get_sequence_name(table, column): other_actions = [ ( self.sql_delete_sequence % { "sequence": self.quote_name(sequence_name), }, [], ) ] return fragment, other_actions elif new_is_auto and old_is_auto and old_internal_type != new_internal_type: fragment, _ = super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) column = strip_quotes(new_field.column) db_types = { "AutoField": "integer", "BigAutoField": "bigint", "SmallAutoField": "smallint", } # Alter the sequence type if exists (Django 4.1+ identity columns # don't have it). other_actions = [] if sequence_name := self._get_sequence_name(table, column): other_actions = [ ( self.sql_alter_sequence_type % { "sequence": self.quote_name(sequence_name), "type": db_types[new_internal_type], }, [], ), ] return fragment, other_actions else: return super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) def _alter_column_collation_sql( self, model, new_field, new_type, new_collation, old_field ): sql = self.sql_alter_column_collate # Cast when data type changed. if using_sql := self._using_sql(new_field, old_field): sql += using_sql return ( sql % { "column": self.quote_name(new_field.column), "type": new_type, "collation": " " + self._collate_sql(new_collation) if new_collation else "", }, [], ) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): super()._alter_field( model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict, ) # Added an index? Create any PostgreSQL-specific indexes. if (not (old_field.db_index or old_field.unique) and new_field.db_index) or ( not old_field.unique and new_field.unique ): like_index_statement = self._create_like_index_sql(model, new_field) if like_index_statement is not None: self.execute(like_index_statement) # Removed an index? Drop any PostgreSQL-specific indexes. if old_field.unique and not (new_field.db_index or new_field.unique): index_to_remove = self._create_index_name( model._meta.db_table, [old_field.column], suffix="_like" ) self.execute(self._delete_index_sql(model, index_to_remove)) def _index_columns(self, table, columns, col_suffixes, opclasses): if opclasses: return IndexColumns( table, columns, self.quote_name, col_suffixes=col_suffixes, opclasses=opclasses, ) return super()._index_columns(table, columns, col_suffixes, opclasses) def add_index(self, model, index, concurrently=False): self.execute( index.create_sql(model, self, concurrently=concurrently), params=None ) def remove_index(self, model, index, concurrently=False): self.execute(index.remove_sql(model, self, concurrently=concurrently)) def _delete_index_sql(self, model, name, sql=None, concurrently=False): sql = ( self.sql_delete_index_concurrently if concurrently else self.sql_delete_index ) return super()._delete_index_sql(model, name, sql) def _create_index_sql( self, model, *, fields=None, name=None, suffix="", using="", db_tablespace=None, col_suffixes=(), sql=None, opclasses=(), condition=None, concurrently=False, include=None, expressions=None, ): sql = sql or ( self.sql_create_index if not concurrently else self.sql_create_index_concurrently ) return super()._create_index_sql( model, fields=fields, name=name, suffix=suffix, using=using, db_tablespace=db_tablespace, col_suffixes=col_suffixes, sql=sql, opclasses=opclasses, condition=condition, include=include, expressions=expressions, )
d3e0f03af756a795aebb45e546efcb3cb4abd6ad448edce0652d993b2893c178
import ipaddress from functools import lru_cache try: from psycopg import ClientCursor, IsolationLevel, adapt, adapters, errors, sql from psycopg.postgres import types from psycopg.types.datetime import TimestamptzLoader from psycopg.types.json import Jsonb from psycopg.types.range import Range, RangeDumper from psycopg.types.string import TextLoader Inet = ipaddress.ip_address DateRange = DateTimeRange = DateTimeTZRange = NumericRange = Range RANGE_TYPES = (Range,) TSRANGE_OID = types["tsrange"].oid TSTZRANGE_OID = types["tstzrange"].oid def mogrify(sql, params, connection): with connection.cursor() as cursor: return ClientCursor(cursor.connection).mogrify(sql, params) # Adapters. class BaseTzLoader(TimestamptzLoader): """ Load a PostgreSQL timestamptz using the a specific timezone. The timezone can be None too, in which case it will be chopped. """ timezone = None def load(self, data): res = super().load(data) return res.replace(tzinfo=self.timezone) def register_tzloader(tz, context): class SpecificTzLoader(BaseTzLoader): timezone = tz context.adapters.register_loader("timestamptz", SpecificTzLoader) class DjangoRangeDumper(RangeDumper): """A Range dumper customized for Django.""" def upgrade(self, obj, format): # Dump ranges containing naive datetimes as tstzrange, because # Django doesn't use tz-aware ones. dumper = super().upgrade(obj, format) if dumper is not self and dumper.oid == TSRANGE_OID: dumper.oid = TSTZRANGE_OID return dumper @lru_cache def get_adapters_template(use_tz, timezone): # Create at adapters map extending the base one. ctx = adapt.AdaptersMap(adapters) # Register a no-op dumper to avoid a round trip from psycopg version 3 # decode to json.dumps() to json.loads(), when using a custom decoder # in JSONField. ctx.register_loader("jsonb", TextLoader) # Don't convert automatically from PostgreSQL network types to Python # ipaddress. ctx.register_loader("inet", TextLoader) ctx.register_loader("cidr", TextLoader) ctx.register_dumper(Range, DjangoRangeDumper) # Register a timestamptz loader configured on self.timezone. # This, however, can be overridden by create_cursor. register_tzloader(timezone, ctx) return ctx is_psycopg3 = True except ImportError: from enum import IntEnum from psycopg2 import errors, extensions, sql # NOQA from psycopg2.extras import DateRange, DateTimeRange, DateTimeTZRange, Inet # NOQA from psycopg2.extras import Json as Jsonb # NOQA from psycopg2.extras import NumericRange, Range # NOQA RANGE_TYPES = (DateRange, DateTimeRange, DateTimeTZRange, NumericRange) class IsolationLevel(IntEnum): READ_UNCOMMITTED = extensions.ISOLATION_LEVEL_READ_UNCOMMITTED READ_COMMITTED = extensions.ISOLATION_LEVEL_READ_COMMITTED REPEATABLE_READ = extensions.ISOLATION_LEVEL_REPEATABLE_READ SERIALIZABLE = extensions.ISOLATION_LEVEL_SERIALIZABLE def _quote(value, connection=None): adapted = extensions.adapt(value) if hasattr(adapted, "encoding"): adapted.encoding = "utf8" # getquoted() returns a quoted bytestring of the adapted value. return adapted.getquoted().decode() sql.quote = _quote def mogrify(sql, params, connection): with connection.cursor() as cursor: return cursor.mogrify(sql, params).decode() is_psycopg3 = False
d4a18540021d50b48f590f1d9891206c20d8d85eb260cdc132b6d144cef1c943
import sys from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.postgresql.psycopg_any import errors from django.db.backends.utils import strip_quotes class DatabaseCreation(BaseDatabaseCreation): def _quote_name(self, name): return self.connection.ops.quote_name(name) def _get_database_create_suffix(self, encoding=None, template=None): suffix = "" if encoding: suffix += " ENCODING '{}'".format(encoding) if template: suffix += " TEMPLATE {}".format(self._quote_name(template)) return suffix and "WITH" + suffix def sql_table_creation_suffix(self): test_settings = self.connection.settings_dict["TEST"] if test_settings.get("COLLATION") is not None: raise ImproperlyConfigured( "PostgreSQL does not support collation setting at database " "creation time." ) return self._get_database_create_suffix( encoding=test_settings["CHARSET"], template=test_settings.get("TEMPLATE"), ) def _database_exists(self, cursor, database_name): cursor.execute( "SELECT 1 FROM pg_catalog.pg_database WHERE datname = %s", [strip_quotes(database_name)], ) return cursor.fetchone() is not None def _execute_create_test_db(self, cursor, parameters, keepdb=False): try: if keepdb and self._database_exists(cursor, parameters["dbname"]): # If the database should be kept and it already exists, don't # try to create a new one. return super()._execute_create_test_db(cursor, parameters, keepdb) except Exception as e: if not isinstance(e.__cause__, errors.DuplicateDatabase): # All errors except "database already exists" cancel tests. self.log("Got an error creating the test database: %s" % e) sys.exit(2) elif not keepdb: # If the database should be kept, ignore "database already # exists". raise def _clone_test_db(self, suffix, verbosity, keepdb=False): # CREATE DATABASE ... WITH TEMPLATE ... requires closing connections # to the template database. self.connection.close() source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] test_db_params = { "dbname": self._quote_name(target_database_name), "suffix": self._get_database_create_suffix(template=source_database_name), } with self._nodb_cursor() as cursor: try: self._execute_create_test_db(cursor, test_db_params, keepdb) except Exception: try: if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) cursor.execute("DROP DATABASE %(dbname)s" % test_db_params) self._execute_create_test_db(cursor, test_db_params, keepdb) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2)
8245e02aea88a7215aba4dbe9203a053e203c5cc3c4e300a33f314f9eaeb684d
import functools import os import pkgutil import sys from argparse import ( _AppendConstAction, _CountAction, _StoreConstAction, _SubParsersAction, ) from collections import defaultdict from difflib import get_close_matches from importlib import import_module import django from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management.base import ( BaseCommand, CommandError, CommandParser, handle_default_options, ) from django.core.management.color import color_style from django.utils import autoreload def find_commands(management_dir): """ Given a path to a management directory, return a list of all the command names that are available. """ command_dir = os.path.join(management_dir, "commands") return [ name for _, name, is_pkg in pkgutil.iter_modules([command_dir]) if not is_pkg and not name.startswith("_") ] def load_command_class(app_name, name): """ Given a command name and an application name, return the Command class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate. """ module = import_module("%s.management.commands.%s" % (app_name, name)) return module.Command() @functools.cache def get_commands(): """ Return a dictionary mapping command names to their callback applications. Look for a management.commands package in django.core, and in each installed application -- if a commands package exists, register all commands in that package. Core commands are always included. If a settings module has been specified, also include user-defined commands. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) The dictionary is cached on the first call and reused on subsequent calls. """ commands = {name: "django.core" for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(apps.get_app_configs()): path = os.path.join(app_config.path, "management") commands.update({name: app_config.name for name in find_commands(path)}) return commands def call_command(command_name, *args, **options): """ Call the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. `command_name` may be a string or a command object. Using a string is preferred unless the command object is required for further processing or testing. Some examples: call_command('migrate') call_command('shell', plain=True) call_command('sqlmigrate', 'myapp') from django.core.management.commands import flush cmd = flush.Command() call_command(cmd, verbosity=0, interactive=False) # Do something with cmd ... """ if isinstance(command_name, BaseCommand): # Command object passed in. command = command_name command_name = command.__class__.__module__.split(".")[-1] else: # Load the command object by name. try: app_name = get_commands()[command_name] except KeyError: raise CommandError("Unknown command: %r" % command_name) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. command = app_name else: command = load_command_class(app_name, command_name) # Simulate argument parsing to get the option defaults (see #10080 for details). parser = command.create_parser("", command_name) # Use the `dest` option name from the parser option opt_mapping = { min(s_opt.option_strings).lstrip("-").replace("-", "_"): s_opt.dest for s_opt in parser._actions if s_opt.option_strings } arg_options = {opt_mapping.get(key, key): value for key, value in options.items()} parse_args = [] for arg in args: if isinstance(arg, (list, tuple)): parse_args += map(str, arg) else: parse_args.append(str(arg)) def get_actions(parser): # Parser actions and actions from sub-parser choices. for opt in parser._actions: if isinstance(opt, _SubParsersAction): for sub_opt in opt.choices.values(): yield from get_actions(sub_opt) else: yield opt parser_actions = list(get_actions(parser)) mutually_exclusive_required_options = { opt for group in parser._mutually_exclusive_groups for opt in group._group_actions if group.required } # Any required arguments which are passed in via **options must be passed # to parse_args(). for opt in parser_actions: if opt.dest in options and ( opt.required or opt in mutually_exclusive_required_options ): opt_dest_count = sum(v == opt.dest for v in opt_mapping.values()) if opt_dest_count > 1: raise TypeError( f"Cannot pass the dest {opt.dest!r} that matches multiple " f"arguments via **options." ) parse_args.append(min(opt.option_strings)) if isinstance(opt, (_AppendConstAction, _CountAction, _StoreConstAction)): continue value = arg_options[opt.dest] if isinstance(value, (list, tuple)): parse_args += map(str, value) else: parse_args.append(str(value)) defaults = parser.parse_args(args=parse_args) defaults = dict(defaults._get_kwargs(), **arg_options) # Raise an error if any unknown options were passed. stealth_options = set(command.base_stealth_options + command.stealth_options) dest_parameters = {action.dest for action in parser_actions} valid_options = (dest_parameters | stealth_options).union(opt_mapping) unknown_options = set(options) - valid_options if unknown_options: raise TypeError( "Unknown option(s) for %s command: %s. " "Valid options are: %s." % ( command_name, ", ".join(sorted(unknown_options)), ", ".join(sorted(valid_options)), ) ) # Move positional args out of options to mimic legacy optparse args = defaults.pop("args", ()) if "skip_checks" not in options: defaults["skip_checks"] = True return command.execute(*args, **defaults) class ManagementUtility: """ Encapsulate the logic of the django-admin and manage.py utilities. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) if self.prog_name == "__main__.py": self.prog_name = "python -m django" self.settings_exception = None def main_help_text(self, commands_only=False): """Return the script's main help text, as a string.""" if commands_only: usage = sorted(get_commands()) else: usage = [ "", "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name, "", "Available subcommands:", ] commands_dict = defaultdict(lambda: []) for name, app in get_commands().items(): if app == "django.core": app = "django" else: app = app.rpartition(".")[-1] commands_dict[app].append(name) style = color_style() for app in sorted(commands_dict): usage.append("") usage.append(style.NOTICE("[%s]" % app)) for name in sorted(commands_dict[app]): usage.append(" %s" % name) # Output an extra note if settings are not properly configured if self.settings_exception is not None: usage.append( style.NOTICE( "Note that only Django core commands are listed " "as settings are not properly configured (error: %s)." % self.settings_exception ) ) return "\n".join(usage) def fetch_command(self, subcommand): """ Try to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin" or "manage.py") if it can't be found. """ # Get commands outside of try block to prevent swallowing exceptions commands = get_commands() try: app_name = commands[subcommand] except KeyError: if os.environ.get("DJANGO_SETTINGS_MODULE"): # If `subcommand` is missing due to misconfigured settings, the # following line will retrigger an ImproperlyConfigured exception # (get_commands() swallows the original one) so the user is # informed about it. settings.INSTALLED_APPS elif not settings.configured: sys.stderr.write("No Django settings specified.\n") possible_matches = get_close_matches(subcommand, commands) sys.stderr.write("Unknown command: %r" % subcommand) if possible_matches: sys.stderr.write(". Did you mean %s?" % possible_matches[0]) sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name) sys.exit(1) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, subcommand) return klass def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMPREPLY` variable and treated as completion suggestions. `COMPREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Please refer to the BASH man-page for more information about this variables. Subcommand options are saved as pairs. A pair consists of the long option string (e.g. '--exclude') and a boolean value indicating if the option requires arguments. When printing to stdout, an equal sign is appended to options which require arguments. Note: If debugging this function, it is recommended to write the debug output in a separate file. Otherwise the debug output will be treated and formatted as potential completion suggestions. """ # Don't complete if user hasn't sourced bash_completion file. if "DJANGO_AUTO_COMPLETE" not in os.environ: return cwords = os.environ["COMP_WORDS"].split()[1:] cword = int(os.environ["COMP_CWORD"]) try: curr = cwords[cword - 1] except IndexError: curr = "" subcommands = [*get_commands(), "help"] options = [("--help", False)] # subcommand if cword == 1: print(" ".join(sorted(filter(lambda x: x.startswith(curr), subcommands)))) # subcommand options # special case: the 'help' subcommand has no options elif cwords[0] in subcommands and cwords[0] != "help": subcommand_cls = self.fetch_command(cwords[0]) # special case: add the names of installed apps to options if cwords[0] in ("dumpdata", "sqlmigrate", "sqlsequencereset", "test"): try: app_configs = apps.get_app_configs() # Get the last part of the dotted path as the app name. options.extend((app_config.label, 0) for app_config in app_configs) except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass parser = subcommand_cls.create_parser("", cwords[0]) options.extend( (min(s_opt.option_strings), s_opt.nargs != 0) for s_opt in parser._actions if s_opt.option_strings ) # filter out previously specified options from available options prev_opts = {x.split("=")[0] for x in cwords[1 : cword - 1]} options = (opt for opt in options if opt[0] not in prev_opts) # filter options by current input options = sorted((k, v) for k, v in options if k.startswith(curr)) for opt_label, require_arg in options: # append '=' to options which require args if require_arg: opt_label += "=" print(opt_label) # Exit code of the bash completion function is never passed back to # the user, so it's safe to always exit with 0. # For more details see #25420. sys.exit(0) def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = "help" # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser( prog=self.prog_name, usage="%(prog)s subcommand [options] [args]", add_help=False, allow_abbrev=False, ) parser.add_argument("--settings") parser.add_argument("--pythonpath") parser.add_argument("args", nargs="*") # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. try: settings.INSTALLED_APPS except ImproperlyConfigured as exc: self.settings_exception = exc except ImportError as exc: self.settings_exception = exc if settings.configured: # Start the auto-reloading dev server even if the code is broken. # The hardcoded condition is a code smell but we can't rely on a # flag on the command class because we haven't located it yet. if subcommand == "runserver" and "--noreload" not in self.argv: try: autoreload.check_errors(django.setup)() except Exception: # The exception will be raised later in the child process # started by the autoreloader. Pretend it didn't happen by # loading an empty list of applications. apps.all_models = defaultdict(dict) apps.app_configs = {} apps.apps_ready = apps.models_ready = apps.ready = True # Remove options not compatible with the built-in runserver # (e.g. options for the contrib.staticfiles' runserver). # Changes here require manually testing as described in # #27522. _parser = self.fetch_command("runserver").create_parser( "django", "runserver" ) _options, _args = _parser.parse_known_args(self.argv[2:]) for _arg in _args: self.argv.remove(_arg) # In all other cases, django.setup() is required to succeed. else: django.setup() self.autocomplete() if subcommand == "help": if "--commands" in args: sys.stdout.write(self.main_help_text(commands_only=True) + "\n") elif not options.args: sys.stdout.write(self.main_help_text() + "\n") else: self.fetch_command(options.args[0]).print_help( self.prog_name, options.args[0] ) # Special-cases: We want 'django-admin --version' and # 'django-admin --help' to work, for backwards compatibility. elif subcommand == "version" or self.argv[1:] == ["--version"]: sys.stdout.write(django.get_version() + "\n") elif self.argv[1:] in (["--help"], ["-h"]): sys.stdout.write(self.main_help_text() + "\n") else: self.fetch_command(subcommand).run_from_argv(self.argv) def execute_from_command_line(argv=None): """Run a ManagementUtility.""" utility = ManagementUtility(argv) utility.execute()
77beea66aa2bd027c44df2c6bd9bc58fe73d8c0230a8e7a18bdb67aa670039f6
import asyncio import logging import sys import tempfile import traceback from contextlib import aclosing from asgiref.sync import ThreadSensitiveContext, sync_to_async from django.conf import settings from django.core import signals from django.core.exceptions import RequestAborted, RequestDataTooBig from django.core.handlers import base from django.http import ( FileResponse, HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseServerError, QueryDict, parse_cookie, ) from django.urls import set_script_prefix from django.utils.functional import cached_property logger = logging.getLogger("django.request") def get_script_prefix(scope): """ Return the script prefix to use from either the scope or a setting. """ if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get("root_path", "") or "" class ASGIRequest(HttpRequest): """ Custom request subclass that decodes from an ASGI-standard request dict and wraps request body handling. """ # Number of seconds until a Request gives up on trying to read a request # body and aborts. body_receive_timeout = 60 def __init__(self, scope, body_file): self.scope = scope self._post_parse_error = False self._read_started = False self.resolver_match = None self.script_name = get_script_prefix(scope) if self.script_name: # TODO: Better is-prefix checking, slash handling? self.path_info = scope["path"].removeprefix(self.script_name) else: self.path_info = scope["path"] # The Django path is different from ASGI scope path args, it should # combine with script name. if self.script_name: self.path = "%s/%s" % ( self.script_name.rstrip("/"), self.path_info.replace("/", "", 1), ) else: self.path = scope["path"] # HTTP basics. self.method = self.scope["method"].upper() # Ensure query string is encoded correctly. query_string = self.scope.get("query_string", "") if isinstance(query_string, bytes): query_string = query_string.decode() self.META = { "REQUEST_METHOD": self.method, "QUERY_STRING": query_string, "SCRIPT_NAME": self.script_name, "PATH_INFO": self.path_info, # WSGI-expecting code will need these for a while "wsgi.multithread": True, "wsgi.multiprocess": True, } if self.scope.get("client"): self.META["REMOTE_ADDR"] = self.scope["client"][0] self.META["REMOTE_HOST"] = self.META["REMOTE_ADDR"] self.META["REMOTE_PORT"] = self.scope["client"][1] if self.scope.get("server"): self.META["SERVER_NAME"] = self.scope["server"][0] self.META["SERVER_PORT"] = str(self.scope["server"][1]) else: self.META["SERVER_NAME"] = "unknown" self.META["SERVER_PORT"] = "0" # Headers go into META. for name, value in self.scope.get("headers", []): name = name.decode("latin1") if name == "content-length": corrected_name = "CONTENT_LENGTH" elif name == "content-type": corrected_name = "CONTENT_TYPE" else: corrected_name = "HTTP_%s" % name.upper().replace("-", "_") # HTTP/2 say only ASCII chars are allowed in headers, but decode # latin1 just in case. value = value.decode("latin1") if corrected_name in self.META: value = self.META[corrected_name] + "," + value self.META[corrected_name] = value # Pull out request encoding, if provided. self._set_content_type_params(self.META) # Directly assign the body file to be our stream. self._stream = body_file # Other bits. self.resolver_match = None @cached_property def GET(self): return QueryDict(self.META["QUERY_STRING"]) def _get_scheme(self): return self.scope.get("scheme") or super()._get_scheme() def _get_post(self): if not hasattr(self, "_post"): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_files(self): if not hasattr(self, "_files"): self._load_post_and_files() return self._files POST = property(_get_post, _set_post) FILES = property(_get_files) @cached_property def COOKIES(self): return parse_cookie(self.META.get("HTTP_COOKIE", "")) def close(self): super().close() self._stream.close() class ASGIHandler(base.BaseHandler): """Handler for ASGI requests.""" request_class = ASGIRequest # Size to chunk response bodies into for multiple response messages. chunk_size = 2**16 def __init__(self): super().__init__() self.load_middleware(is_async=True) async def __call__(self, scope, receive, send): """ Async entrypoint - parses the request and hands off to get_response. """ # Serve only HTTP connections. # FIXME: Allow to override this. if scope["type"] != "http": raise ValueError( "Django can only handle ASGI/HTTP connections, not %s." % scope["type"] ) async with ThreadSensitiveContext(): await self.handle(scope, receive, send) async def handle(self, scope, receive, send): """ Handles the ASGI request. Called via the __call__ method. """ # Receive the HTTP request body as a stream object. try: body_file = await self.read_body(receive) except RequestAborted: return # Request is complete and can be served. set_script_prefix(get_script_prefix(scope)) await signals.request_started.asend(sender=self.__class__, scope=scope) # Get the request and check for basic issues. request, error_response = self.create_request(scope, body_file) if request is None: body_file.close() await self.send_response(error_response, send) return # Try to catch a disconnect while getting response. tasks = [ asyncio.create_task(self.run_get_response(request)), asyncio.create_task(self.listen_for_disconnect(receive)), ] done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) done, pending = done.pop(), pending.pop() # Allow views to handle cancellation. pending.cancel() try: await pending except asyncio.CancelledError: # Task re-raised the CancelledError as expected. pass try: response = done.result() except RequestAborted: body_file.close() return except AssertionError: body_file.close() raise # Send the response. await self.send_response(response, send) async def listen_for_disconnect(self, receive): """Listen for disconnect from the client.""" message = await receive() if message["type"] == "http.disconnect": raise RequestAborted() # This should never happen. assert False, "Invalid ASGI message after request body: %s" % message["type"] async def run_get_response(self, request): """Get async response.""" # Use the async mode of BaseHandler. response = await self.get_response_async(request) response._handler_class = self.__class__ # Increase chunk size on file responses (ASGI servers handles low-level # chunking). if isinstance(response, FileResponse): response.block_size = self.chunk_size return response async def read_body(self, receive): """Reads an HTTP body from an ASGI connection.""" # Use the tempfile that auto rolls-over to a disk file as it fills up. body_file = tempfile.SpooledTemporaryFile( max_size=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, mode="w+b" ) while True: message = await receive() if message["type"] == "http.disconnect": body_file.close() # Early client disconnect. raise RequestAborted() # Add a body chunk from the message, if provided. if "body" in message: body_file.write(message["body"]) # Quit out if that's the end. if not message.get("more_body", False): break body_file.seek(0) return body_file def create_request(self, scope, body_file): """ Create the Request object and returns either (request, None) or (None, response) if there is an error response. """ try: return self.request_class(scope, body_file), None except UnicodeDecodeError: logger.warning( "Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400}, ) return None, HttpResponseBadRequest() except RequestDataTooBig: return None, HttpResponse("413 Payload too large", status=413) def handle_uncaught_exception(self, request, resolver, exc_info): """Last-chance handler for exceptions.""" # There's no WSGI server to catch the exception further up # if this fails, so translate it into a plain text response. try: return super().handle_uncaught_exception(request, resolver, exc_info) except Exception: return HttpResponseServerError( traceback.format_exc() if settings.DEBUG else "Internal Server Error", content_type="text/plain", ) async def send_response(self, response, send): """Encode and send a response out over ASGI.""" # Collect cookies into headers. Have to preserve header case as there # are some non-RFC compliant clients that require e.g. Content-Type. response_headers = [] for header, value in response.items(): if isinstance(header, str): header = header.encode("ascii") if isinstance(value, str): value = value.encode("latin1") response_headers.append((bytes(header), bytes(value))) for c in response.cookies.values(): response_headers.append( (b"Set-Cookie", c.output(header="").encode("ascii").strip()) ) # Initial response message. await send( { "type": "http.response.start", "status": response.status_code, "headers": response_headers, } ) # Streaming responses need to be pinned to their iterator. if response.streaming: # - Consume via `__aiter__` and not `streaming_content` directly, to # allow mapping of a sync iterator. # - Use aclosing() when consuming aiter. # See https://github.com/python/cpython/commit/6e8dcda async with aclosing(aiter(response)) as content: async for part in content: for chunk, _ in self.chunk_bytes(part): await send( { "type": "http.response.body", "body": chunk, # Ignore "more" as there may be more parts; instead, # use an empty final closing message with False. "more_body": True, } ) # Final closing message. await send({"type": "http.response.body"}) # Other responses just need chunking. else: # Yield chunks of response. for chunk, last in self.chunk_bytes(response.content): await send( { "type": "http.response.body", "body": chunk, "more_body": not last, } ) await sync_to_async(response.close, thread_sensitive=True)() @classmethod def chunk_bytes(cls, data): """ Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples. """ position = 0 if not data: yield data, True return while position < len(data): yield ( data[position : position + cls.chunk_size], (position + cls.chunk_size) >= len(data), ) position += cls.chunk_size
f350c4ae0cc701a65cc36522beb2aac12ebd429a1117cb66d00484738bf7b90e
from io import IOBase from django.conf import settings from django.core import signals from django.core.handlers import base from django.http import HttpRequest, QueryDict, parse_cookie from django.urls import set_script_prefix from django.utils.encoding import repercent_broken_unicode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile _slashes_re = _lazy_re_compile(rb"/+") class LimitedStream(IOBase): """ Wrap another stream to disallow reading it past a number of bytes. Based on the implementation from werkzeug.wsgi.LimitedStream See https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828 """ def __init__(self, stream, limit): self._read = stream.read self._readline = stream.readline self._pos = 0 self.limit = limit def read(self, size=-1, /): _pos = self._pos limit = self.limit if _pos >= limit: return b"" if size == -1 or size is None: size = limit - _pos else: size = min(size, limit - _pos) data = self._read(size) self._pos += len(data) return data def readline(self, size=-1, /): _pos = self._pos limit = self.limit if _pos >= limit: return b"" if size == -1 or size is None: size = limit - _pos else: size = min(size, limit - _pos) line = self._readline(size) self._pos += len(line) return line class WSGIRequest(HttpRequest): def __init__(self, environ): script_name = get_script_name(environ) # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL without a # trailing slash), operate as if '/' was requested. path_info = get_path_info(environ) or "/" self.environ = environ self.path_info = path_info # be careful to only replace the first slash in the path because of # http://test/something and http://test//something being different as # stated in RFC 3986. self.path = "%s/%s" % (script_name.rstrip("/"), path_info.replace("/", "", 1)) self.META = environ self.META["PATH_INFO"] = path_info self.META["SCRIPT_NAME"] = script_name self.method = environ["REQUEST_METHOD"].upper() # Set content_type, content_params, and encoding. self._set_content_type_params(environ) try: content_length = int(environ.get("CONTENT_LENGTH")) except (ValueError, TypeError): content_length = 0 self._stream = LimitedStream(self.environ["wsgi.input"], content_length) self._read_started = False self.resolver_match = None def _get_scheme(self): return self.environ.get("wsgi.url_scheme") @cached_property def GET(self): # The WSGI spec says 'QUERY_STRING' may be absent. raw_query_string = get_bytes_from_wsgi(self.environ, "QUERY_STRING", "") return QueryDict(raw_query_string, encoding=self._encoding) def _get_post(self): if not hasattr(self, "_post"): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post @cached_property def COOKIES(self): raw_cookie = get_str_from_wsgi(self.environ, "HTTP_COOKIE", "") return parse_cookie(raw_cookie) @property def FILES(self): if not hasattr(self, "_files"): self._load_post_and_files() return self._files POST = property(_get_post, _set_post) class WSGIHandler(base.BaseHandler): request_class = WSGIRequest def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.load_middleware() def __call__(self, environ, start_response): set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__, environ=environ) request = self.request_class(environ) response = self.get_response(request) response._handler_class = self.__class__ status = "%d %s" % (response.status_code, response.reason_phrase) response_headers = [ *response.items(), *(("Set-Cookie", c.output(header="")) for c in response.cookies.values()), ] start_response(status, response_headers) if getattr(response, "file_to_stream", None) is not None and environ.get( "wsgi.file_wrapper" ): # If `wsgi.file_wrapper` is used the WSGI server does not call # .close on the response, but on the file wrapper. Patch it to use # response.close instead which takes care of closing all files. response.file_to_stream.close = response.close response = environ["wsgi.file_wrapper"]( response.file_to_stream, response.block_size ) return response def get_path_info(environ): """Return the HTTP request's PATH_INFO as a string.""" path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "/") return repercent_broken_unicode(path_info).decode() def get_script_name(environ): """ Return the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite is used, return what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ if settings.FORCE_SCRIPT_NAME is not None: return settings.FORCE_SCRIPT_NAME # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = get_bytes_from_wsgi(environ, "SCRIPT_URL", "") or get_bytes_from_wsgi( environ, "REDIRECT_URL", "" ) if script_url: if b"//" in script_url: # mod_wsgi squashes multiple successive slashes in PATH_INFO, # do the same with script_url before manipulating paths (#17133). script_url = _slashes_re.sub(b"/", script_url) path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "") script_name = script_url.removesuffix(path_info) else: script_name = get_bytes_from_wsgi(environ, "SCRIPT_NAME", "") return script_name.decode() def get_bytes_from_wsgi(environ, key, default): """ Get a value from the WSGI environ dictionary as bytes. key and default should be strings. """ value = environ.get(key, default) # Non-ASCII values in the WSGI environ are arbitrarily decoded with # ISO-8859-1. This is wrong for Django websites where UTF-8 is the default. # Re-encode to recover the original bytestring. return value.encode("iso-8859-1") def get_str_from_wsgi(environ, key, default): """ Get a value from the WSGI environ dictionary as str. key and default should be str objects. """ value = get_bytes_from_wsgi(environ, key, default) return value.decode(errors="replace")
18064039256948bf9e0e31c23c63eb481ab0d0c7a2738e1ba9d3602c022ccf47
from django.db.models import ( CharField, Expression, Field, FloatField, Func, Lookup, TextField, Value, ) from django.db.models.expressions import CombinedExpression, register_combinable_fields from django.db.models.functions import Cast, Coalesce class SearchVectorExact(Lookup): lookup_name = "exact" def process_rhs(self, qn, connection): if not isinstance(self.rhs, (SearchQuery, CombinedSearchQuery)): config = getattr(self.lhs, "config", None) self.rhs = SearchQuery(self.rhs, config=config) rhs, rhs_params = super().process_rhs(qn, connection) return rhs, rhs_params def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s @@ %s" % (lhs, rhs), params class SearchVectorField(Field): def db_type(self, connection): return "tsvector" class SearchQueryField(Field): def db_type(self, connection): return "tsquery" class _Float4Field(Field): def db_type(self, connection): return "float4" class SearchConfig(Expression): def __init__(self, config): super().__init__() if not hasattr(config, "resolve_expression"): config = Value(config) self.config = config @classmethod def from_parameter(cls, config): if config is None or isinstance(config, cls): return config return cls(config) def get_source_expressions(self): return [self.config] def set_source_expressions(self, exprs): (self.config,) = exprs def as_sql(self, compiler, connection): sql, params = compiler.compile(self.config) return "%s::regconfig" % sql, params class SearchVectorCombinable: ADD = "||" def _combine(self, other, connector, reversed): if not isinstance(other, SearchVectorCombinable): raise TypeError( "SearchVector can only be combined with other SearchVector " "instances, got %s." % type(other).__name__ ) if reversed: return CombinedSearchVector(other, connector, self, self.config) return CombinedSearchVector(self, connector, other, self.config) register_combinable_fields( SearchVectorField, SearchVectorCombinable.ADD, SearchVectorField, SearchVectorField ) class SearchVector(SearchVectorCombinable, Func): function = "to_tsvector" arg_joiner = " || ' ' || " output_field = SearchVectorField() def __init__(self, *expressions, config=None, weight=None): super().__init__(*expressions) self.config = SearchConfig.from_parameter(config) if weight is not None and not hasattr(weight, "resolve_expression"): weight = Value(weight) self.weight = weight def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): resolved = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) if self.config: resolved.config = self.config.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return resolved def as_sql(self, compiler, connection, function=None, template=None): clone = self.copy() clone.set_source_expressions( [ Coalesce( expression if isinstance(expression.output_field, (CharField, TextField)) else Cast(expression, TextField()), Value(""), ) for expression in clone.get_source_expressions() ] ) config_sql = None config_params = [] if template is None: if clone.config: config_sql, config_params = compiler.compile(clone.config) template = "%(function)s(%(config)s, %(expressions)s)" else: template = clone.template sql, params = super(SearchVector, clone).as_sql( compiler, connection, function=function, template=template, config=config_sql, ) extra_params = [] if clone.weight: weight_sql, extra_params = compiler.compile(clone.weight) sql = "setweight({}, {})".format(sql, weight_sql) return sql, config_params + params + extra_params class CombinedSearchVector(SearchVectorCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) class SearchQueryCombinable: BITAND = "&&" BITOR = "||" def _combine(self, other, connector, reversed): if not isinstance(other, SearchQueryCombinable): raise TypeError( "SearchQuery can only be combined with other SearchQuery " "instances, got %s." % type(other).__name__ ) if reversed: return CombinedSearchQuery(other, connector, self, self.config) return CombinedSearchQuery(self, connector, other, self.config) # On Combinable, these are not implemented to reduce confusion with Q. In # this case we are actually (ab)using them to do logical combination so # it's consistent with other usage in Django. def __or__(self, other): return self._combine(other, self.BITOR, False) def __ror__(self, other): return self._combine(other, self.BITOR, True) def __and__(self, other): return self._combine(other, self.BITAND, False) def __rand__(self, other): return self._combine(other, self.BITAND, True) class SearchQuery(SearchQueryCombinable, Func): output_field = SearchQueryField() SEARCH_TYPES = { "plain": "plainto_tsquery", "phrase": "phraseto_tsquery", "raw": "to_tsquery", "websearch": "websearch_to_tsquery", } def __init__( self, value, output_field=None, *, config=None, invert=False, search_type="plain", ): self.function = self.SEARCH_TYPES.get(search_type) if self.function is None: raise ValueError("Unknown search_type argument '%s'." % search_type) if not hasattr(value, "resolve_expression"): value = Value(value) expressions = (value,) self.config = SearchConfig.from_parameter(config) if self.config is not None: expressions = (self.config,) + expressions self.invert = invert super().__init__(*expressions, output_field=output_field) def as_sql(self, compiler, connection, function=None, template=None): sql, params = super().as_sql(compiler, connection, function, template) if self.invert: sql = "!!(%s)" % sql return sql, params def __invert__(self): clone = self.copy() clone.invert = not self.invert return clone def __str__(self): result = super().__str__() return ("~%s" % result) if self.invert else result class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) def __str__(self): return "(%s)" % super().__str__() class SearchRank(Func): function = "ts_rank" output_field = FloatField() def __init__( self, vector, query, weights=None, normalization=None, cover_density=False, ): from .fields.array import ArrayField if not hasattr(vector, "resolve_expression"): vector = SearchVector(vector) if not hasattr(query, "resolve_expression"): query = SearchQuery(query) expressions = (vector, query) if weights is not None: if not hasattr(weights, "resolve_expression"): weights = Value(weights) weights = Cast(weights, ArrayField(_Float4Field())) expressions = (weights,) + expressions if normalization is not None: if not hasattr(normalization, "resolve_expression"): normalization = Value(normalization) expressions += (normalization,) if cover_density: self.function = "ts_rank_cd" super().__init__(*expressions) class SearchHeadline(Func): function = "ts_headline" template = "%(function)s(%(expressions)s%(options)s)" output_field = TextField() def __init__( self, expression, query, *, config=None, start_sel=None, stop_sel=None, max_words=None, min_words=None, short_word=None, highlight_all=None, max_fragments=None, fragment_delimiter=None, ): if not hasattr(query, "resolve_expression"): query = SearchQuery(query) options = { "StartSel": start_sel, "StopSel": stop_sel, "MaxWords": max_words, "MinWords": min_words, "ShortWord": short_word, "HighlightAll": highlight_all, "MaxFragments": max_fragments, "FragmentDelimiter": fragment_delimiter, } self.options = { option: value for option, value in options.items() if value is not None } expressions = (expression, query) if config is not None: config = SearchConfig.from_parameter(config) expressions = (config,) + expressions super().__init__(*expressions) def as_sql(self, compiler, connection, function=None, template=None): options_sql = "" options_params = [] if self.options: options_params.append( ", ".join( connection.ops.compose_sql(f"{option}=%s", [value]) for option, value in self.options.items() ) ) options_sql = ", %s" sql, params = super().as_sql( compiler, connection, function=function, template=template, options=options_sql, ) return sql, params + options_params SearchVectorField.register_lookup(SearchVectorExact) class TrigramBase(Func): output_field = FloatField() def __init__(self, expression, string, **extra): if not hasattr(string, "resolve_expression"): string = Value(string) super().__init__(expression, string, **extra) class TrigramWordBase(Func): output_field = FloatField() def __init__(self, string, expression, **extra): if not hasattr(string, "resolve_expression"): string = Value(string) super().__init__(string, expression, **extra) class TrigramSimilarity(TrigramBase): function = "SIMILARITY" class TrigramDistance(TrigramBase): function = "" arg_joiner = " <-> " class TrigramWordDistance(TrigramWordBase): function = "" arg_joiner = " <<-> " class TrigramStrictWordDistance(TrigramWordBase): function = "" arg_joiner = " <<<-> " class TrigramWordSimilarity(TrigramWordBase): function = "WORD_SIMILARITY" class TrigramStrictWordSimilarity(TrigramWordBase): function = "STRICT_WORD_SIMILARITY"
bd31f8126c844d435c023092699fcdb9588d0d26002ad08e3b8b491d197225cd
from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, UserChangeForm, UserCreationForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters csrf_protect_m = method_decorator(csrf_protect) sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) @admin.register(Group) class GroupAdmin(admin.ModelAdmin): search_fields = ("name",) ordering = ("name",) filter_horizontal = ("permissions",) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == "permissions": qs = kwargs.get("queryset", db_field.remote_field.model.objects) # Avoid a major performance hit resolving permission names which # triggers a content_type load: kwargs["queryset"] = qs.select_related("content_type") return super().formfield_for_manytomany(db_field, request=request, **kwargs) @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = "admin/auth/user/add_form.html" change_user_password_template = None fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("first_name", "last_name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "password1", "password2"), }, ), ) form = UserChangeForm add_form = UserCreationForm change_password_form = AdminPasswordChangeForm list_display = ("username", "email", "first_name", "last_name", "is_staff") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("username", "first_name", "last_name", "email") ordering = ("username",) filter_horizontal = ( "groups", "user_permissions", ) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults["form"] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( "<id>/password/", self.admin_site.admin_view(self.user_change_password), name="auth_user_password_change", ), ] + super().get_urls() # RemovedInDjango60Warning: when the deprecation ends, replace with: # def lookup_allowed(self, lookup, value, request): def lookup_allowed(self, lookup, value, request=None): # Don't allow lookups involving passwords. return not lookup.startswith("password") and super().lookup_allowed( lookup, value, request ) @sensitive_post_parameters_m @csrf_protect_m def add_view(self, request, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url="", extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not self.has_change_permission(request): if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' "order to add users, Django requires that your user " 'account have both the "Add user" and "Change user" ' "permissions set." ) raise PermissionDenied if extra_context is None: extra_context = {} username_field = self.opts.get_field(self.model.USERNAME_FIELD) defaults = { "auto_populated_fields": (), "username_help_text": username_field.help_text, } extra_context.update(defaults) return super().add_view(request, form_url, extra_context) @sensitive_post_parameters_m def user_change_password(self, request, id, form_url=""): user = self.get_object(request, unquote(id)) if not self.has_change_permission(request, user): raise PermissionDenied if user is None: raise Http404( _("%(name)s object with primary key %(key)r does not exist.") % { "name": self.opts.verbose_name, "key": escape(id), } ) if request.method == "POST": form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() change_message = self.construct_change_message(request, form, None) self.log_change(request, user, change_message) msg = gettext("Password changed successfully.") messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( "%s:%s_%s_change" % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) else: form = self.change_password_form(user) fieldsets = [(None, {"fields": list(form.base_fields)})] admin_form = admin.helpers.AdminForm(form, fieldsets, {}) context = { "title": _("Change password: %s") % escape(user.get_username()), "adminForm": admin_form, "form_url": form_url, "form": form, "is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), "is_popup_var": IS_POPUP_VAR, "add": True, "change": False, "has_delete_permission": False, "has_change_permission": True, "has_absolute_url": False, "opts": self.opts, "original": user, "save_as": False, "show_save": True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or "admin/auth/user/change_password.html", context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST["_continue"] = 1 return super().response_add(request, obj, post_url_continue)
c199dd415ac7a04228c86a559eace7987f2f1fabe3909c6790cc68d7ef1005e6
import unicodedata from django import forms from django.contrib.auth import authenticate, get_user_model, password_validation from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ValidationError from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.text import capfirst from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ UserModel = get_user_model() def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ return ( unicodedata.normalize("NFKC", s1).casefold() == unicodedata.normalize("NFKC", s2).casefold() ) class ReadOnlyPasswordHashWidget(forms.Widget): template_name = "auth/widgets/read_only_password_hash.html" read_only = True def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) summary = [] if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX): summary.append({"label": gettext("No password set.")}) else: try: hasher = identify_hasher(value) except ValueError: summary.append( { "label": gettext( "Invalid password format or unknown hashing algorithm." ) } ) else: for key, value_ in hasher.safe_summary(value).items(): summary.append({"label": gettext(key), "value": value_}) context["summary"] = summary return context def id_for_label(self, id_): return None class ReadOnlyPasswordHashField(forms.Field): widget = ReadOnlyPasswordHashWidget def __init__(self, *args, **kwargs): kwargs.setdefault("required", False) kwargs.setdefault("disabled", True) super().__init__(*args, **kwargs) class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize("NFKC", super().to_python(value)) def widget_attrs(self, widget): return { **super().widget_attrs(widget), "autocapitalize": "none", "autocomplete": "username", } class BaseUserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {"username": UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[ "autofocus" ] = True def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) return password2 def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get("password2") if password: try: password_validation.validate_password(password, self.instance) except ValidationError as error: self.add_error("password2", error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() if hasattr(self, "save_m2m"): self.save_m2m() return user class UserCreationForm(BaseUserCreationForm): def clean_username(self): """Reject usernames that differ only in case.""" username = self.cleaned_data.get("username") if ( username and self._meta.model.objects.filter(username__iexact=username).exists() ): self._update_errors( ValidationError( { "username": self.instance.unique_error_message( self._meta.model, ["username"] ) } ) ) else: return username class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user’s password, but you can change the password using " '<a href="{}">this form</a>.' ), ) class Meta: model = User fields = "__all__" field_classes = {"username": UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get("password") if password: password.help_text = password.help_text.format( f"../../{self.instance.pk}/password/" ) user_permissions = self.fields.get("user_permissions") if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related( "content_type" ) class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={"autofocus": True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}), ) error_messages = { "invalid_login": _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), "inactive": _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super().__init__(*args, **kwargs) # Set the max length and label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) username_max_length = self.username_field.max_length or 254 self.fields["username"].max_length = username_max_length self.fields["username"].widget.attrs["maxlength"] = username_max_length if self.fields["username"].label is None: self.fields["username"].label = capfirst(self.username_field.verbose_name) def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username is not None and password: self.user_cache = authenticate( self.request, username=username, password=password ) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise ValidationError( self.error_messages["inactive"], code="inactive", ) def get_user(self): return self.user_cache def get_invalid_login_error(self): return ValidationError( self.error_messages["invalid_login"], code="invalid_login", params={"username": self.username_field.verbose_name}, ) class PasswordResetForm(forms.Form): email = forms.EmailField( label=_("Email"), max_length=254, widget=forms.EmailInput(attrs={"autocomplete": "email"}), ) def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = "".join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, "text/html") email_message.send() def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter( **{ "%s__iexact" % email_field_name: email, "is_active": True, } ) return ( u for u in active_users if u.has_usable_password() and _unicode_ci_compare(email, getattr(u, email_field_name)) ) def save( self, domain_override=None, subject_template_name="registration/password_reset_subject.txt", email_template_name="registration/password_reset_email.html", use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None, ): """ Generate a one-use only link for resetting password and send it to the user. """ email = self.cleaned_data["email"] if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): user_email = getattr(user, email_field_name) context = { "email": user_email, "domain": domain, "site_name": site_name, "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, "token": token_generator.make_token(user), "protocol": "https" if use_https else "http", **(extra_email_context or {}), } self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, ) class SetPasswordForm(forms.Form): """ A form that lets a user set their password without entering the old password """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get("new_password1") password2 = self.cleaned_data.get("new_password2") if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, "password_incorrect": _( "Your old password was entered incorrectly. Please enter it again." ), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput( attrs={"autocomplete": "current-password", "autofocus": True} ), ) field_order = ["old_password", "new_password1", "new_password2"] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise ValidationError( self.error_messages["password_incorrect"], code="password_incorrect", ) return old_password class AdminPasswordChangeForm(forms.Form): """ A form used to change the password of a user in the admin interface. """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } required_css_class = "required" password1 = forms.CharField( label=_("Password"), widget=forms.PasswordInput( attrs={"autocomplete": "new-password", "autofocus": True} ), strip=False, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password (again)"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=_("Enter the same password as before, for verification."), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): """Save the new password.""" password = self.cleaned_data["password1"] self.user.set_password(password) if commit: self.user.save() return self.user @property def changed_data(self): data = super().changed_data for name in self.fields: if name not in data: return [] return ["password"]
b44aff7ddc4b8f8e15193c578ccf7b4c0f1cc8c1c22f4acd05cd356b24e4f194
import collections from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Combinable from django.forms.models import BaseModelForm, BaseModelFormSet, _get_foreign_key from django.template import engines from django.template.backends.django import DjangoTemplates from django.utils.module_loading import import_string def _issubclass(cls, classinfo): """ issubclass() variant that doesn't raise an exception if cls isn't a class. """ try: return issubclass(cls, classinfo) except TypeError: return False def _contains_subclass(class_path, candidate_paths): """ Return whether or not a dotted class path (or a subclass of that class) is found in a list of candidate paths. """ cls = import_string(class_path) for path in candidate_paths: try: candidate_cls = import_string(path) except ImportError: # ImportErrors are raised elsewhere. continue if _issubclass(candidate_cls, cls): return True return False def check_admin_app(app_configs, **kwargs): from django.contrib.admin.sites import all_sites errors = [] for site in all_sites: errors.extend(site.check(app_configs)) return errors def check_dependencies(**kwargs): """ Check that the admin's dependencies are correctly installed. """ from django.contrib.admin.sites import all_sites if not apps.is_installed("django.contrib.admin"): return [] errors = [] app_dependencies = ( ("django.contrib.contenttypes", 401), ("django.contrib.auth", 405), ("django.contrib.messages", 406), ) for app_name, error_code in app_dependencies: if not apps.is_installed(app_name): errors.append( checks.Error( "'%s' must be in INSTALLED_APPS in order to use the admin " "application." % app_name, id="admin.E%d" % error_code, ) ) for engine in engines.all(): if isinstance(engine, DjangoTemplates): django_templates_instance = engine.engine break else: django_templates_instance = None if not django_templates_instance: errors.append( checks.Error( "A 'django.template.backends.django.DjangoTemplates' instance " "must be configured in TEMPLATES in order to use the admin " "application.", id="admin.E403", ) ) else: if ( "django.contrib.auth.context_processors.auth" not in django_templates_instance.context_processors and _contains_subclass( "django.contrib.auth.backends.ModelBackend", settings.AUTHENTICATION_BACKENDS, ) ): errors.append( checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id="admin.E402", ) ) if ( "django.contrib.messages.context_processors.messages" not in django_templates_instance.context_processors ): errors.append( checks.Error( "'django.contrib.messages.context_processors.messages' must " "be enabled in DjangoTemplates (TEMPLATES) in order to use " "the admin application.", id="admin.E404", ) ) sidebar_enabled = any(site.enable_nav_sidebar for site in all_sites) if ( sidebar_enabled and "django.template.context_processors.request" not in django_templates_instance.context_processors ): errors.append( checks.Warning( "'django.template.context_processors.request' must be enabled " "in DjangoTemplates (TEMPLATES) in order to use the admin " "navigation sidebar.", id="admin.W411", ) ) if not _contains_subclass( "django.contrib.auth.middleware.AuthenticationMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.auth.middleware.AuthenticationMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", id="admin.E408", ) ) if not _contains_subclass( "django.contrib.messages.middleware.MessageMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.messages.middleware.MessageMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", id="admin.E409", ) ) if not _contains_subclass( "django.contrib.sessions.middleware.SessionMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.sessions.middleware.SessionMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", hint=( "Insert " "'django.contrib.sessions.middleware.SessionMiddleware' " "before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ), id="admin.E410", ) ) return errors class BaseModelAdminChecks: def check(self, admin_obj, **kwargs): return [ *self._check_autocomplete_fields(admin_obj), *self._check_raw_id_fields(admin_obj), *self._check_fields(admin_obj), *self._check_fieldsets(admin_obj), *self._check_exclude(admin_obj), *self._check_form(admin_obj), *self._check_filter_vertical(admin_obj), *self._check_filter_horizontal(admin_obj), *self._check_radio_fields(admin_obj), *self._check_prepopulated_fields(admin_obj), *self._check_view_on_site_url(admin_obj), *self._check_ordering(admin_obj), *self._check_readonly_fields(admin_obj), ] def _check_autocomplete_fields(self, obj): """ Check that `autocomplete_fields` is a list or tuple of model fields. """ if not isinstance(obj.autocomplete_fields, (list, tuple)): return must_be( "a list or tuple", option="autocomplete_fields", obj=obj, id="admin.E036", ) else: return list( chain.from_iterable( [ self._check_autocomplete_fields_item( obj, field_name, "autocomplete_fields[%d]" % index ) for index, field_name in enumerate(obj.autocomplete_fields) ] ) ) def _check_autocomplete_fields_item(self, obj, field_name, label): """ Check that an item in `autocomplete_fields` is a ForeignKey or a ManyToManyField and that the item has a related ModelAdmin with search_fields defined. """ try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E037" ) else: if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be( "a foreign key or a many-to-many field", option=label, obj=obj, id="admin.E038", ) related_admin = obj.admin_site._registry.get(field.remote_field.model) if related_admin is None: return [ checks.Error( 'An admin for model "%s" has to be registered ' "to be referenced by %s.autocomplete_fields." % ( field.remote_field.model.__name__, type(obj).__name__, ), obj=obj.__class__, id="admin.E039", ) ] elif not related_admin.search_fields: return [ checks.Error( '%s must define "search_fields", because it\'s ' "referenced by %s.autocomplete_fields." % ( related_admin.__class__.__name__, type(obj).__name__, ), obj=obj.__class__, id="admin.E040", ) ] return [] def _check_raw_id_fields(self, obj): """Check that `raw_id_fields` only contains field names that are listed on the model.""" if not isinstance(obj.raw_id_fields, (list, tuple)): return must_be( "a list or tuple", option="raw_id_fields", obj=obj, id="admin.E001" ) else: return list( chain.from_iterable( self._check_raw_id_fields_item( obj, field_name, "raw_id_fields[%d]" % index ) for index, field_name in enumerate(obj.raw_id_fields) ) ) def _check_raw_id_fields_item(self, obj, field_name, label): """Check an item of `raw_id_fields`, i.e. check that field named `field_name` exists in model `model` and is a ForeignKey or a ManyToManyField.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E002" ) else: # Using attname is not supported. if field.name != field_name: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E002", ) if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be( "a foreign key or a many-to-many field", option=label, obj=obj, id="admin.E003", ) else: return [] def _check_fields(self, obj): """Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if obj.fields is None: return [] elif not isinstance(obj.fields, (list, tuple)): return must_be("a list or tuple", option="fields", obj=obj, id="admin.E004") elif obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", obj=obj.__class__, id="admin.E005", ) ] fields = flatten(obj.fields) if len(fields) != len(set(fields)): return [ checks.Error( "The value of 'fields' contains duplicate field(s).", obj=obj.__class__, id="admin.E006", ) ] return list( chain.from_iterable( self._check_field_spec(obj, field_name, "fields") for field_name in obj.fields ) ) def _check_fieldsets(self, obj): """Check that fieldsets is properly formatted and doesn't contain duplicates.""" if obj.fieldsets is None: return [] elif not isinstance(obj.fieldsets, (list, tuple)): return must_be( "a list or tuple", option="fieldsets", obj=obj, id="admin.E007" ) else: seen_fields = [] return list( chain.from_iterable( self._check_fieldsets_item( obj, fieldset, "fieldsets[%d]" % index, seen_fields ) for index, fieldset in enumerate(obj.fieldsets) ) ) def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): """Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key.""" if not isinstance(fieldset, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E008") elif len(fieldset) != 2: return must_be("of length 2", option=label, obj=obj, id="admin.E009") elif not isinstance(fieldset[1], dict): return must_be( "a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010" ) elif "fields" not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id="admin.E011", ) ] elif not isinstance(fieldset[1]["fields"], (list, tuple)): return must_be( "a list or tuple", option="%s[1]['fields']" % label, obj=obj, id="admin.E008", ) seen_fields.extend(flatten(fieldset[1]["fields"])) if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id="admin.E012", ) ] return list( chain.from_iterable( self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]["fields"] ) ) def _check_field_spec(self, obj, fields, label): """`fields` should be an item of `fields` or an item of fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a field name or a tuple of field names.""" if isinstance(fields, tuple): return list( chain.from_iterable( self._check_field_spec_item( obj, field_name, "%s[%d]" % (label, index) ) for index, field_name in enumerate(fields) ) ) else: return self._check_field_spec_item(obj, fields, label) def _check_field_spec_item(self, obj, field_name, label): if field_name in obj.readonly_fields: # Stuff can be put in fields that isn't actually a model field if # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] else: try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: # If we can't find a field on the model that matches, it could # be an extra field on the form. return [] else: if ( isinstance(field, models.ManyToManyField) and not field.remote_field.through._meta.auto_created ): return [ checks.Error( "The value of '%s' cannot include the ManyToManyField " "'%s', because that field manually specifies a " "relationship model." % (label, field_name), obj=obj.__class__, id="admin.E013", ) ] else: return [] def _check_exclude(self, obj): """Check that exclude is a sequence without duplicates.""" if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be( "a list or tuple", option="exclude", obj=obj, id="admin.E014" ) elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=obj.__class__, id="admin.E015", ) ] else: return [] def _check_form(self, obj): """Check that form subclasses BaseModelForm.""" if not _issubclass(obj.form, BaseModelForm): return must_inherit_from( parent="BaseModelForm", option="form", obj=obj, id="admin.E016" ) else: return [] def _check_filter_vertical(self, obj): """Check that filter_vertical is a sequence of field names.""" if not isinstance(obj.filter_vertical, (list, tuple)): return must_be( "a list or tuple", option="filter_vertical", obj=obj, id="admin.E017" ) else: return list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_vertical[%d]" % index ) for index, field_name in enumerate(obj.filter_vertical) ) ) def _check_filter_horizontal(self, obj): """Check that filter_horizontal is a sequence of field names.""" if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be( "a list or tuple", option="filter_horizontal", obj=obj, id="admin.E018" ) else: return list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_horizontal[%d]" % index ) for index, field_name in enumerate(obj.filter_horizontal) ) ) def _check_filter_item(self, obj, field_name, label): """Check one item of `filter_vertical` or `filter_horizontal`, i.e. check that given field exists and is a ManyToManyField.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E019" ) else: if not field.many_to_many: return must_be( "a many-to-many field", option=label, obj=obj, id="admin.E020" ) else: return [] def _check_radio_fields(self, obj): """Check that `radio_fields` is a dictionary.""" if not isinstance(obj.radio_fields, dict): return must_be( "a dictionary", option="radio_fields", obj=obj, id="admin.E021" ) else: return list( chain.from_iterable( self._check_radio_fields_key(obj, field_name, "radio_fields") + self._check_radio_fields_value( obj, val, 'radio_fields["%s"]' % field_name ) for field_name, val in obj.radio_fields.items() ) ) def _check_radio_fields_key(self, obj, field_name, label): """Check that a key of `radio_fields` dictionary is name of existing field and that the field is a ForeignKey or has `choices` defined.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E022" ) else: if not (isinstance(field, models.ForeignKey) or field.choices): return [ checks.Error( "The value of '%s' refers to '%s', which is not an " "instance of ForeignKey, and does not have a 'choices' " "definition." % (label, field_name), obj=obj.__class__, id="admin.E023", ) ] else: return [] def _check_radio_fields_value(self, obj, val, label): """Check type of a value of `radio_fields` dictionary.""" from django.contrib.admin.options import HORIZONTAL, VERTICAL if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( "The value of '%s' must be either admin.HORIZONTAL or " "admin.VERTICAL." % label, obj=obj.__class__, id="admin.E024", ) ] else: return [] def _check_view_on_site_url(self, obj): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): return [ checks.Error( "The value of 'view_on_site' must be a callable or a boolean " "value.", obj=obj.__class__, id="admin.E025", ) ] else: return [] def _check_prepopulated_fields(self, obj): """Check that `prepopulated_fields` is a dictionary containing allowed field types.""" if not isinstance(obj.prepopulated_fields, dict): return must_be( "a dictionary", option="prepopulated_fields", obj=obj, id="admin.E026" ) else: return list( chain.from_iterable( self._check_prepopulated_fields_key( obj, field_name, "prepopulated_fields" ) + self._check_prepopulated_fields_value( obj, val, 'prepopulated_fields["%s"]' % field_name ) for field_name, val in obj.prepopulated_fields.items() ) ) def _check_prepopulated_fields_key(self, obj, field_name, label): """Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E027" ) else: if isinstance( field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField) ): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a " "DateTimeField, a ForeignKey, a OneToOneField, or a " "ManyToManyField." % (label, field_name), obj=obj.__class__, id="admin.E028", ) ] else: return [] def _check_prepopulated_fields_value(self, obj, val, label): """Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields.""" if not isinstance(val, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E029") else: return list( chain.from_iterable( self._check_prepopulated_fields_value_item( obj, subfield_name, "%s[%r]" % (label, index) ) for index, subfield_name in enumerate(val) ) ) def _check_prepopulated_fields_value_item(self, obj, field_name, label): """For `prepopulated_fields` equal to {"slug": ("title",)}, `field_name` is "title".""" try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E030" ) else: return [] def _check_ordering(self, obj): """Check that ordering refers to existing fields or is random.""" # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.ordering, (list, tuple)): return must_be( "a list or tuple", option="ordering", obj=obj, id="admin.E031" ) else: return list( chain.from_iterable( self._check_ordering_item(obj, field_name, "ordering[%d]" % index) for index, field_name in enumerate(obj.ordering) ) ) def _check_ordering_item(self, obj, field_name, label): """Check that `ordering` refers to existing fields.""" if isinstance(field_name, (Combinable, models.OrderBy)): if not isinstance(field_name, models.OrderBy): field_name = field_name.asc() if isinstance(field_name.expression, models.F): field_name = field_name.expression.name else: return [] if field_name == "?" and len(obj.ordering) != 1: return [ checks.Error( "The value of 'ordering' has the random ordering marker '?', " "but contains other fields as well.", hint='Either remove the "?", or remove the other fields.', obj=obj.__class__, id="admin.E032", ) ] elif field_name == "?": return [] elif LOOKUP_SEP in field_name: # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). return [] else: field_name = field_name.removeprefix("-") if field_name == "pk": return [] try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E033" ) else: return [] def _check_readonly_fields(self, obj): """Check that readonly_fields refers to proper attribute or field.""" if obj.readonly_fields == (): return [] elif not isinstance(obj.readonly_fields, (list, tuple)): return must_be( "a list or tuple", option="readonly_fields", obj=obj, id="admin.E034" ) else: return list( chain.from_iterable( self._check_readonly_fields_item( obj, field_name, "readonly_fields[%d]" % index ) for index, field_name in enumerate(obj.readonly_fields) ) ) def _check_readonly_fields_item(self, obj, field_name, label): if callable(field_name): return [] elif hasattr(obj, field_name): return [] elif hasattr(obj.model, field_name): return [] else: try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "The value of '%s' is not a callable, an attribute of " "'%s', or an attribute of '%s'." % ( label, obj.__class__.__name__, obj.model._meta.label, ), obj=obj.__class__, id="admin.E035", ) ] else: return [] class ModelAdminChecks(BaseModelAdminChecks): def check(self, admin_obj, **kwargs): return [ *super().check(admin_obj), *self._check_save_as(admin_obj), *self._check_save_on_top(admin_obj), *self._check_inlines(admin_obj), *self._check_list_display(admin_obj), *self._check_list_display_links(admin_obj), *self._check_list_filter(admin_obj), *self._check_list_select_related(admin_obj), *self._check_list_per_page(admin_obj), *self._check_list_max_show_all(admin_obj), *self._check_list_editable(admin_obj), *self._check_search_fields(admin_obj), *self._check_date_hierarchy(admin_obj), *self._check_action_permission_methods(admin_obj), *self._check_actions_uniqueness(admin_obj), ] def _check_save_as(self, obj): """Check save_as is a boolean.""" if not isinstance(obj.save_as, bool): return must_be("a boolean", option="save_as", obj=obj, id="admin.E101") else: return [] def _check_save_on_top(self, obj): """Check save_on_top is a boolean.""" if not isinstance(obj.save_on_top, bool): return must_be("a boolean", option="save_on_top", obj=obj, id="admin.E102") else: return [] def _check_inlines(self, obj): """Check all inline model admin classes.""" if not isinstance(obj.inlines, (list, tuple)): return must_be( "a list or tuple", option="inlines", obj=obj, id="admin.E103" ) else: return list( chain.from_iterable( self._check_inlines_item(obj, item, "inlines[%d]" % index) for index, item in enumerate(obj.inlines) ) ) def _check_inlines_item(self, obj, inline, label): """Check one inline model admin.""" try: inline_label = inline.__module__ + "." + inline.__name__ except AttributeError: return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % obj, obj=obj.__class__, id="admin.E104", ) ] from django.contrib.admin.options import InlineModelAdmin if not _issubclass(inline, InlineModelAdmin): return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % inline_label, obj=obj.__class__, id="admin.E104", ) ] elif not inline.model: return [ checks.Error( "'%s' must have a 'model' attribute." % inline_label, obj=obj.__class__, id="admin.E105", ) ] elif not _issubclass(inline.model, models.Model): return must_be( "a Model", option="%s.model" % inline_label, obj=obj, id="admin.E106" ) else: return inline(obj.model, obj.admin_site).check() def _check_list_display(self, obj): """Check that list_display only contains fields or usable attributes.""" if not isinstance(obj.list_display, (list, tuple)): return must_be( "a list or tuple", option="list_display", obj=obj, id="admin.E107" ) else: return list( chain.from_iterable( self._check_list_display_item(obj, item, "list_display[%d]" % index) for index, item in enumerate(obj.list_display) ) ) def _check_list_display_item(self, obj, item, label): if callable(item): return [] elif hasattr(obj, item): return [] try: field = obj.model._meta.get_field(item) except FieldDoesNotExist: try: field = getattr(obj.model, item) except AttributeError: return [ checks.Error( "The value of '%s' refers to '%s', which is not a " "callable, an attribute of '%s', or an attribute or " "method on '%s'." % ( label, item, obj.__class__.__name__, obj.model._meta.label, ), obj=obj.__class__, id="admin.E108", ) ] if ( getattr(field, "is_relation", False) and (field.many_to_many or field.one_to_many) ) or (getattr(field, "rel", None) and field.rel.field.many_to_one): return [ checks.Error( f"The value of '{label}' must not be a many-to-many field or a " f"reverse foreign key.", obj=obj.__class__, id="admin.E109", ) ] return [] def _check_list_display_links(self, obj): """Check that list_display_links is a unique subset of list_display.""" from django.contrib.admin.options import ModelAdmin if obj.list_display_links is None: return [] elif not isinstance(obj.list_display_links, (list, tuple)): return must_be( "a list, a tuple, or None", option="list_display_links", obj=obj, id="admin.E110", ) # Check only if ModelAdmin.get_list_display() isn't overridden. elif obj.get_list_display.__func__ is ModelAdmin.get_list_display: return list( chain.from_iterable( self._check_list_display_links_item( obj, field_name, "list_display_links[%d]" % index ) for index, field_name in enumerate(obj.list_display_links) ) ) return [] def _check_list_display_links_item(self, obj, field_name, label): if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not defined in " "'list_display'." % (label, field_name), obj=obj.__class__, id="admin.E111", ) ] else: return [] def _check_list_filter(self, obj): if not isinstance(obj.list_filter, (list, tuple)): return must_be( "a list or tuple", option="list_filter", obj=obj, id="admin.E112" ) else: return list( chain.from_iterable( self._check_list_filter_item(obj, item, "list_filter[%d]" % index) for index, item in enumerate(obj.list_filter) ) ) def _check_list_filter_item(self, obj, item, label): """ Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ from django.contrib.admin import FieldListFilter, ListFilter if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not _issubclass(item, ListFilter): return must_inherit_from( parent="ListFilter", option=label, obj=obj, id="admin.E113" ) # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, obj=obj.__class__, id="admin.E114", ) ] else: return [] elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not _issubclass(list_filter_class, FieldListFilter): return must_inherit_from( parent="FieldListFilter", option="%s[1]" % label, obj=obj, id="admin.E115", ) else: return [] else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(obj.model, field) except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of '%s' refers to '%s', which does not refer to a " "Field." % (label, field), obj=obj.__class__, id="admin.E116", ) ] else: return [] def _check_list_select_related(self, obj): """Check that list_select_related is a boolean, a list or a tuple.""" if not isinstance(obj.list_select_related, (bool, list, tuple)): return must_be( "a boolean, tuple or list", option="list_select_related", obj=obj, id="admin.E117", ) else: return [] def _check_list_per_page(self, obj): """Check that list_per_page is an integer.""" if not isinstance(obj.list_per_page, int): return must_be( "an integer", option="list_per_page", obj=obj, id="admin.E118" ) else: return [] def _check_list_max_show_all(self, obj): """Check that list_max_show_all is an integer.""" if not isinstance(obj.list_max_show_all, int): return must_be( "an integer", option="list_max_show_all", obj=obj, id="admin.E119" ) else: return [] def _check_list_editable(self, obj): """Check that list_editable is a sequence of editable fields from list_display without first element.""" if not isinstance(obj.list_editable, (list, tuple)): return must_be( "a list or tuple", option="list_editable", obj=obj, id="admin.E120" ) else: return list( chain.from_iterable( self._check_list_editable_item( obj, item, "list_editable[%d]" % index ) for index, item in enumerate(obj.list_editable) ) ) def _check_list_editable_item(self, obj, field_name, label): try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E121" ) else: if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not " "contained in 'list_display'." % (label, field_name), obj=obj.__class__, id="admin.E122", ) ] elif obj.list_display_links and field_name in obj.list_display_links: return [ checks.Error( "The value of '%s' cannot be in both 'list_editable' and " "'list_display_links'." % field_name, obj=obj.__class__, id="admin.E123", ) ] # If list_display[0] is in list_editable, check that # list_display_links is set. See #22792 and #26229 for use cases. elif ( obj.list_display[0] == field_name and not obj.list_display_links and obj.list_display_links is not None ): return [ checks.Error( "The value of '%s' refers to the first field in 'list_display' " "('%s'), which cannot be used unless 'list_display_links' is " "set." % (label, obj.list_display[0]), obj=obj.__class__, id="admin.E124", ) ] elif not field.editable or field.primary_key: return [ checks.Error( "The value of '%s' refers to '%s', which is not editable " "through the admin." % (label, field_name), obj=obj.__class__, id="admin.E125", ) ] else: return [] def _check_search_fields(self, obj): """Check search_fields is a sequence.""" if not isinstance(obj.search_fields, (list, tuple)): return must_be( "a list or tuple", option="search_fields", obj=obj, id="admin.E126" ) else: return [] def _check_date_hierarchy(self, obj): """Check that date_hierarchy refers to DateField or DateTimeField.""" if obj.date_hierarchy is None: return [] else: try: field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of 'date_hierarchy' refers to '%s', which " "does not refer to a Field." % obj.date_hierarchy, obj=obj.__class__, id="admin.E127", ) ] else: if not isinstance(field, (models.DateField, models.DateTimeField)): return must_be( "a DateField or DateTimeField", option="date_hierarchy", obj=obj, id="admin.E128", ) else: return [] def _check_action_permission_methods(self, obj): """ Actions with an allowed_permission attribute require the ModelAdmin to implement a has_<perm>_permission() method for each permission. """ actions = obj._get_base_actions() errors = [] for func, name, _ in actions: if not hasattr(func, "allowed_permissions"): continue for permission in func.allowed_permissions: method_name = "has_%s_permission" % permission if not hasattr(obj, method_name): errors.append( checks.Error( "%s must define a %s() method for the %s action." % ( obj.__class__.__name__, method_name, func.__name__, ), obj=obj.__class__, id="admin.E129", ) ) return errors def _check_actions_uniqueness(self, obj): """Check that every action has a unique __name__.""" errors = [] names = collections.Counter(name for _, name, _ in obj._get_base_actions()) for name, count in names.items(): if count > 1: errors.append( checks.Error( "__name__ attributes of actions defined in %s must be " "unique. Name %r is not unique." % ( obj.__class__.__name__, name, ), obj=obj.__class__, id="admin.E130", ) ) return errors class InlineModelAdminChecks(BaseModelAdminChecks): def check(self, inline_obj, **kwargs): parent_model = inline_obj.parent_model return [ *super().check(inline_obj), *self._check_relation(inline_obj, parent_model), *self._check_exclude_of_parent_model(inline_obj, parent_model), *self._check_extra(inline_obj), *self._check_max_num(inline_obj), *self._check_min_num(inline_obj), *self._check_formset(inline_obj), ] def _check_exclude_of_parent_model(self, obj, parent_model): # Do not perform more specific checks if the base checks result in an # error. errors = super()._check_exclude(obj) if errors: return [] # Skip if `fk_name` is invalid. if self._check_relation(obj, parent_model): return [] if obj.exclude is None: return [] fk = _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) if fk.name in obj.exclude: return [ checks.Error( "Cannot exclude the field '%s', because it is the foreign key " "to the parent model '%s'." % ( fk.name, parent_model._meta.label, ), obj=obj.__class__, id="admin.E201", ) ] else: return [] def _check_relation(self, obj, parent_model): try: _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) except ValueError as e: return [checks.Error(e.args[0], obj=obj.__class__, id="admin.E202")] else: return [] def _check_extra(self, obj): """Check that extra is an integer.""" if not isinstance(obj.extra, int): return must_be("an integer", option="extra", obj=obj, id="admin.E203") else: return [] def _check_max_num(self, obj): """Check that max_num is an integer.""" if obj.max_num is None: return [] elif not isinstance(obj.max_num, int): return must_be("an integer", option="max_num", obj=obj, id="admin.E204") else: return [] def _check_min_num(self, obj): """Check that min_num is an integer.""" if obj.min_num is None: return [] elif not isinstance(obj.min_num, int): return must_be("an integer", option="min_num", obj=obj, id="admin.E205") else: return [] def _check_formset(self, obj): """Check formset is a subclass of BaseModelFormSet.""" if not _issubclass(obj.formset, BaseModelFormSet): return must_inherit_from( parent="BaseModelFormSet", option="formset", obj=obj, id="admin.E206" ) else: return [] def must_be(type, option, obj, id): return [ checks.Error( "The value of '%s' must be %s." % (option, type), obj=obj.__class__, id=id, ), ] def must_inherit_from(parent, option, obj, id): return [ checks.Error( "The value of '%s' must inherit from '%s'." % (option, parent), obj=obj.__class__, id=id, ), ] def refer_to_missing_field(field, option, obj, id): return [ checks.Error( "The value of '%s' refers to '%s', which is not a field of '%s'." % (option, field, obj.model._meta.label), obj=obj.__class__, id=id, ), ]
3fac73a97b9bef76082e237ade4b982ebd3cd67c04768ab92684d57b89230a06
import copy import enum import json import re from functools import partial, update_wrapper from urllib.parse import quote as urlquote from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import helpers, widgets from django.contrib.admin.checks import ( BaseModelAdminChecks, InlineModelAdminChecks, ModelAdminChecks, ) from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( NestedObjects, construct_change_message, flatten_fieldsets, get_deleted_objects, lookup_spawns_duplicates, model_format_dict, model_ngettext, quote, unquote, ) from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple from django.contrib.auth import get_permission_codename from django.core.exceptions import ( FieldDoesNotExist, FieldError, PermissionDenied, ValidationError, ) from django.core.paginator import Paginator from django.db import models, router, transaction from django.db.models.constants import LOOKUP_SEP from django.forms.formsets import DELETION_FIELD_NAME, all_valid from django.forms.models import ( BaseInlineFormSet, inlineformset_factory, modelform_defines_fields, modelform_factory, modelformset_factory, ) from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple from django.http import HttpResponseRedirect from django.http.response import HttpResponseBase from django.template.response import SimpleTemplateResponse, TemplateResponse from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.html import format_html from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.text import ( capfirst, format_lazy, get_text_list, smart_split, unescape_string_literal, ) from django.utils.translation import gettext as _ from django.utils.translation import ngettext from django.views.decorators.csrf import csrf_protect from django.views.generic import RedirectView IS_POPUP_VAR = "_popup" TO_FIELD_VAR = "_to_field" IS_FACETS_VAR = "_facets" class ShowFacets(enum.Enum): NEVER = "NEVER" ALLOW = "ALLOW" ALWAYS = "ALWAYS" HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return "radiolist" if radio_style == VERTICAL else "radiolist inline" class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { "form_class": forms.SplitDateTimeField, "widget": widgets.AdminSplitDateTime, }, models.DateField: {"widget": widgets.AdminDateWidget}, models.TimeField: {"widget": widgets.AdminTimeWidget}, models.TextField: {"widget": widgets.AdminTextareaWidget}, models.URLField: {"widget": widgets.AdminURLFieldWidget}, models.IntegerField: {"widget": widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {"widget": widgets.AdminBigIntegerFieldWidget}, models.CharField: {"widget": widgets.AdminTextInputWidget}, models.ImageField: {"widget": widgets.AdminFileWidget}, models.FileField: {"widget": widgets.AdminFileWidget}, models.EmailField: {"widget": widgets.AdminEmailInputWidget}, models.UUIDField: {"widget": widgets.AdminUUIDInputWidget}, } csrf_protect_m = method_decorator(csrf_protect) class BaseModelAdmin(metaclass=forms.MediaDefiningClass): """Functionality common to both ModelAdmin and InlineAdmin.""" autocomplete_fields = () raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () ordering = None sortable_by = None view_on_site = True show_full_result_count = True checks_class = BaseModelAdminChecks def check(self, **kwargs): return self.checks_class().check(self, **kwargs) def __init__(self): # Merge FORMFIELD_FOR_DBFIELD_DEFAULTS with the formfield_overrides # rather than simply overwriting. overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, request, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs} # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get( db_field.remote_field.model ) wrapper_kwargs = {} if related_modeladmin: wrapper_kwargs.update( can_add_related=related_modeladmin.has_add_permission(request), can_change_related=related_modeladmin.has_change_permission( request ), can_delete_related=related_modeladmin.has_delete_permission( request ), can_view_related=related_modeladmin.has_view_permission( request ), ) formfield.widget = widgets.RelatedFieldWidgetWrapper( formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs, ) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs} return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if "widget" not in kwargs: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) if "choices" not in kwargs: kwargs["choices"] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[("", _("None"))] ) return db_field.formfield(**kwargs) def get_field_queryset(self, db, db_field, request): """ If the ModelAdmin specifies ordering, the queryset should respect that ordering. Otherwise don't specify the queryset, let the field decide (return None in that case). """ related_admin = self.admin_site._registry.get(db_field.remote_field.model) if related_admin is not None: ordering = related_admin.get_ordering(request) if ordering is not None and ordering != (): return db_field.remote_field.model._default_manager.using(db).order_by( *ordering ) return None def formfield_for_foreignkey(self, db_field, request, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get("using") if "widget" not in kwargs: if db_field.name in self.get_autocomplete_fields(request): kwargs["widget"] = AutocompleteSelect( db_field, self.admin_site, using=db ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ForeignKeyRawIdWidget( db_field.remote_field, self.admin_site, using=db ) elif db_field.name in self.radio_fields: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) kwargs["empty_label"] = ( kwargs.get("empty_label", _("None")) if db_field.blank else None ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widget" not in kwargs: autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs["widget"] = AutocompleteSelectMultiple( db_field, self.admin_site, using=db, ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ManyToManyRawIdWidget( db_field.remote_field, self.admin_site, using=db, ) elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]: kwargs["widget"] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset form_field = db_field.formfield(**kwargs) if ( isinstance(form_field.widget, SelectMultiple) and form_field.widget.allow_multiple_selected and not isinstance( form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple) ) ): msg = _( "Hold down “Control”, or “Command” on a Mac, to select more than one." ) help_text = form_field.help_text form_field.help_text = ( format_lazy("{} {}", help_text, msg) if help_text else msg ) return form_field def get_autocomplete_fields(self, request): """ Return a list of ForeignKey and/or ManyToMany fields which should use an autocomplete widget. """ return self.autocomplete_fields def get_view_on_site_url(self, obj=None): if obj is None or not self.view_on_site: return None if callable(self.view_on_site): return self.view_on_site(obj) elif hasattr(obj, "get_absolute_url"): # use the ContentType lookup if view_on_site is True return reverse( "admin:view_on_site", kwargs={ "content_type_id": get_content_type_for_model(obj).pk, "object_id": obj.pk, }, current_app=self.admin_site.name, ) def get_empty_value_display(self): """ Return the empty_value_display set on ModelAdmin or AdminSite. """ try: return mark_safe(self.empty_value_display) except AttributeError: return mark_safe(self.admin_site.empty_value_display) def get_exclude(self, request, obj=None): """ Hook for specifying exclude. """ return self.exclude def get_fields(self, request, obj=None): """ Hook for specifying fields. """ if self.fields: return self.fields # _get_form_for_get_fields() is implemented in subclasses. form = self._get_form_for_get_fields(request, obj) return [*form.base_fields, *self.get_readonly_fields(request, obj)] def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ if self.fieldsets: return self.fieldsets return [(None, {"fields": self.get_fields(request, obj)})] def get_inlines(self, request, obj): """Hook for specifying custom inlines.""" return self.inlines def get_ordering(self, request): """ Hook for specifying field ordering. """ return self.ordering or () # otherwise we might try to *None, which is bad ;) def get_readonly_fields(self, request, obj=None): """ Hook for specifying custom readonly fields. """ return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): """ Hook for specifying custom prepopulated fields. """ return self.prepopulated_fields def get_queryset(self, request): """ Return a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def get_sortable_by(self, request): """Hook for specifying which fields can be sorted in the changelist.""" return ( self.sortable_by if self.sortable_by is not None else self.get_list_display(request) ) # RemovedInDjango60Warning: when the deprecation ends, replace with: # def lookup_allowed(self, lookup, value, request): def lookup_allowed(self, lookup, value, request=None): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for fk_lookup in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(fk_lookup): fk_lookup = fk_lookup() if (lookup, value) in widgets.url_params_from_lookup_dict( fk_lookup ).items(): return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on nonexistent fields are ok, since they're ignored # later. break if not prev_field or ( prev_field.is_relation and field not in model._meta.parents.values() and field is not model._meta.auto_field and ( model._meta.auto_field is None or part not in getattr(prev_field, "to_fields", []) ) ): relation_parts.append(part) if not getattr(field, "path_infos", None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.path_infos[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True valid_lookups = {self.date_hierarchy} # RemovedInDjango60Warning: when the deprecation ends, replace with: # for filter_item in self.get_list_filter(request): list_filter = ( self.get_list_filter(request) if request is not None else self.list_filter ) for filter_item in list_filter: if isinstance(filter_item, type) and issubclass( filter_item, SimpleListFilter ): valid_lookups.add(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.add(filter_item[0]) else: valid_lookups.add(filter_item) # Is it a valid relational lookup? return not { LOOKUP_SEP.join(relation_parts), LOOKUP_SEP.join(relation_parts + [part]), }.isdisjoint(valid_lookups) def to_field_allowed(self, request, to_field): """ Return True if the model associated with this admin should be allowed to be referenced by the specified field. """ try: field = self.opts.get_field(to_field) except FieldDoesNotExist: return False # Always allow referencing the primary key since it's already possible # to get this information from the change view URL. if field.primary_key: return True # Allow reverse relationships to models defining m2m fields if they # target the specified field. for many_to_many in self.opts.many_to_many: if many_to_many.m2m_target_field_name() == to_field: return True # Make sure at least one of the models registered for this site # references this field through a FK or a M2M relationship. registered_models = set() for model, admin in self.admin_site._registry.items(): registered_models.add(model) for inline in admin.inlines: registered_models.add(inline.model) related_objects = ( f for f in self.opts.get_fields(include_hidden=True) if (f.auto_created and not f.concrete) ) for related_object in related_objects: related_model = related_object.related_model remote_field = related_object.field.remote_field if ( any(issubclass(model, related_model) for model in registered_models) and hasattr(remote_field, "get_related_field") and remote_field.get_related_field() == field ): return True return False def has_add_permission(self, request): """ Return True if the given request has permission to add an object. Can be overridden by the user in subclasses. """ opts = self.opts codename = get_permission_codename("add", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts codename = get_permission_codename("change", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ Return True if the given request has permission to delete the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts codename = get_permission_codename("delete", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_view_permission(self, request, obj=None): """ Return True if the given request has permission to view the given Django model instance. The default implementation doesn't examine the `obj` parameter. If overridden by the user in subclasses, it should return True if the given request has permission to view the `obj` model instance. If `obj` is None, it should return True if the request has permission to view any object of the given type. """ opts = self.opts codename_view = get_permission_codename("view", opts) codename_change = get_permission_codename("change", opts) return request.user.has_perm( "%s.%s" % (opts.app_label, codename_view) ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) def has_view_or_change_permission(self, request, obj=None): return self.has_view_permission(request, obj) or self.has_change_permission( request, obj ) def has_module_permission(self, request): """ Return True if the given request has any permission in the given app label. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to view the module on the admin index page and access the module's index page. Overriding it does not restrict access to the add, change or delete views. Use `ModelAdmin.has_(add|change|delete)_permission` for that. """ return request.user.has_module_perms(self.opts.app_label) class ModelAdmin(BaseModelAdmin): """Encapsulate all admin options and functionality for a given model.""" list_display = ("__str__",) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () search_help_text = None date_hierarchy = None save_as = False save_as_continue = True save_on_top = False paginator = Paginator preserve_filters = True show_facets = ShowFacets.ALLOW inlines = () # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None popup_response_template = None # Actions actions = () action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True checks_class = ModelAdminChecks def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site super().__init__() def __str__(self): return "%s.%s" % (self.opts.app_label, self.__class__.__name__) def __repr__(self): return ( f"<{self.__class__.__qualname__}: model={self.model.__qualname__} " f"site={self.admin_site!r}>" ) def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.get_inlines(request, obj): inline = inline_class(self.model, self.admin_site) if request: if not ( inline.has_view_or_change_permission(request, obj) or inline.has_add_permission(request, obj) or inline.has_delete_permission(request, obj) ): continue if not inline.has_add_permission(request, obj): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_urls(self): from django.urls import path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) wrapper.model_admin = self return update_wrapper(wrapper, view) info = self.opts.app_label, self.opts.model_name return [ path("", wrap(self.changelist_view), name="%s_%s_changelist" % info), path("add/", wrap(self.add_view), name="%s_%s_add" % info), path( "<path:object_id>/history/", wrap(self.history_view), name="%s_%s_history" % info, ), path( "<path:object_id>/delete/", wrap(self.delete_view), name="%s_%s_delete" % info, ), path( "<path:object_id>/change/", wrap(self.change_view), name="%s_%s_change" % info, ), # For backwards compatibility (was the change url before 1.9) path( "<path:object_id>/", wrap( RedirectView.as_view( pattern_name="%s:%s_%s_change" % ((self.admin_site.name,) + info) ) ), ), ] @property def urls(self): return self.get_urls() @property def media(self): extra = "" if settings.DEBUG else ".min" js = [ "vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "core.js", "admin/RelatedObjectLookups.js", "actions.js", "urlify.js", "prepopulate.js", "vendor/xregexp/xregexp%s.js" % extra, ] return forms.Media(js=["admin/js/%s" % url for url in js]) def get_model_perms(self, request): """ Return a dict of all perms for this model. This dict has the keys ``add``, ``change``, ``delete``, and ``view`` mapping to the True/False for each of those actions. """ return { "add": self.has_add_permission(request), "change": self.has_change_permission(request), "delete": self.has_delete_permission(request), "view": self.has_view_permission(request), } def _get_form_for_get_fields(self, request, obj): return self.get_form(request, obj, fields=None) def get_form(self, request, obj=None, change=False, **kwargs): """ Return a Form class for use in the admin add view. This is used by add_view and change_view. """ if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) readonly_fields = self.get_readonly_fields(request, obj) exclude.extend(readonly_fields) # Exclude all fields if it's a change form and the user doesn't have # the change permission. if ( change and hasattr(request, "user") and not self.has_change_permission(request, obj) ): exclude.extend(fields) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # ModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistent with the # default on modelform_factory exclude = exclude or None # Remove declared form fields which are in readonly_fields. new_attrs = dict.fromkeys( f for f in readonly_fields if f in self.form.declared_fields ) form = type(self.form.__name__, (self.form,), new_attrs) defaults = { "form": form, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( "%s. Check fields/fieldsets/exclude attributes of class %s." % (e, self.__class__.__name__) ) def get_changelist(self, request, **kwargs): """ Return the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_changelist_instance(self, request): """ Return a `ChangeList` instance based on `request`. May raise `IncorrectLookupParameters`. """ list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): list_display = ["action_checkbox", *list_display] sortable_by = self.get_sortable_by(request) ChangeList = self.get_changelist(request) return ChangeList( request, self.model, list_display, list_display_links, self.get_list_filter(request), self.date_hierarchy, self.get_search_fields(request), self.get_list_select_related(request), self.list_per_page, self.list_max_show_all, self.list_editable, self, sortable_by, self.search_help_text, ) def get_object(self, request, object_id, from_field=None): """ Return an instance matching the field and value provided, the primary key is used if no field is provided. Return ``None`` if no match is found or the object_id fails validation. """ queryset = self.get_queryset(request) model = queryset.model field = ( model._meta.pk if from_field is None else model._meta.get_field(from_field) ) try: object_id = field.to_python(object_id) return queryset.get(**{field.name: object_id}) except (model.DoesNotExist, ValidationError, ValueError): return None def get_changelist_form(self, request, **kwargs): """ Return a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults.get("fields") is None and not modelform_defines_fields( defaults.get("form") ): defaults["fields"] = forms.ALL_FIELDS return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Return a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } return modelformset_factory( self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults, ) def get_formsets_with_inlines(self, request, obj=None): """ Yield formsets and the corresponding inlines. """ for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj), inline def get_paginator( self, request, queryset, per_page, orphans=0, allow_empty_first_page=True ): return self.paginator(queryset, per_page, orphans, allow_empty_first_page) def log_addition(self, request, obj, message): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import ADDITION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=ADDITION, change_message=message, ) def log_change(self, request, obj, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import CHANGE, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=message, ) def log_deletion(self, request, obj, object_repr): """ Log that an object will be deleted. Note that this method must be called before the deletion. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import DELETION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=object_repr, action_flag=DELETION, ) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ attrs = { "class": "action-select", "aria-label": format_html(_("Select this object for an action - {}"), obj), } checkbox = forms.CheckboxInput(attrs, lambda value: False) return checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk)) @staticmethod def _get_action_description(func, name): return getattr(func, "short_description", capfirst(name.replace("_", " "))) def _get_base_actions(self): """Return the list of actions, prior to any request-based filtering.""" actions = [] base_actions = (self.get_action(action) for action in self.actions or []) # get_action might have returned None, so filter any of those out. base_actions = [action for action in base_actions if action] base_action_names = {name for _, name, _ in base_actions} # Gather actions from the admin site first for name, func in self.admin_site.actions: if name in base_action_names: continue description = self._get_action_description(func, name) actions.append((func, name, description)) # Add actions from this ModelAdmin. actions.extend(base_actions) return actions def _filter_actions_by_permissions(self, request, actions): """Filter out any actions that the user doesn't have access to.""" filtered_actions = [] for action in actions: callable = action[0] if not hasattr(callable, "allowed_permissions"): filtered_actions.append(action) continue permission_checks = ( getattr(self, "has_%s_permission" % permission) for permission in callable.allowed_permissions ) if any(has_permission(request) for has_permission in permission_checks): filtered_actions.append(action) return filtered_actions def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is set to None that means actions are disabled on # this page. if self.actions is None or IS_POPUP_VAR in request.GET: return {} actions = self._filter_actions_by_permissions(request, self._get_base_actions()) return {name: (func, name, desc) for func, name, desc in actions} def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in self.get_actions(request).values(): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None description = self._get_action_description(func, action) return func, action, description def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ return self.list_display def get_list_display_links(self, request, list_display): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if ( self.list_display_links or self.list_display_links is None or not list_display ): return self.list_display_links else: # Use only the first item in list_display as link return list(list_display)[:1] def get_list_filter(self, request): """ Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page. """ return self.list_filter def get_list_select_related(self, request): """ Return a list of fields to add to the select_related() part of the changelist items query. """ return self.list_select_related def get_search_fields(self, request): """ Return a sequence containing the fields to be searched whenever somebody submits a search query. """ return self.search_fields def get_search_results(self, request, queryset, search_term): """ Return a tuple containing a queryset to implement the search and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith("^"): return "%s__istartswith" % field_name.removeprefix("^") elif field_name.startswith("="): return "%s__iexact" % field_name.removeprefix("=") elif field_name.startswith("@"): return "%s__search" % field_name.removeprefix("@") # Use field_name if it includes a lookup. opts = queryset.model._meta lookup_fields = field_name.split(LOOKUP_SEP) # Go through the fields, following all relations. prev_field = None for path_part in lookup_fields: if path_part == "pk": path_part = opts.pk.name try: field = opts.get_field(path_part) except FieldDoesNotExist: # Use valid query lookups. if prev_field and prev_field.get_lookup(path_part): return field_name else: prev_field = field if hasattr(field, "path_infos"): # Update opts to follow the relation. opts = field.path_infos[-1].to_opts # Otherwise, use the field with icontains. return "%s__icontains" % field_name may_have_duplicates = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [ construct_search(str(search_field)) for search_field in search_fields ] term_queries = [] for bit in smart_split(search_term): if bit.startswith(('"', "'")) and bit[0] == bit[-1]: bit = unescape_string_literal(bit) or_queries = models.Q.create( [(orm_lookup, bit) for orm_lookup in orm_lookups], connector=models.Q.OR, ) term_queries.append(or_queries) queryset = queryset.filter(models.Q.create(term_queries)) may_have_duplicates |= any( lookup_spawns_duplicates(self.opts, search_spec) for search_spec in orm_lookups ) return queryset, may_have_duplicates def get_preserved_filters(self, request): """ Return the preserved filters querystring. """ match = request.resolver_match if self.preserve_filters and match: current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( self.opts.app_label, self.opts.model_name, ) if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: preserved_filters = request.GET.get("_changelist_filters") if preserved_filters: return urlencode({"_changelist_filters": preserved_filters}) return "" def construct_change_message(self, request, form, formsets, add=False): """ Construct a JSON structure describing changes from a changed object. """ return construct_change_message(form, formsets, add) def message_user( self, request, message, level=messages.INFO, extra_tags="", fail_silently=False ): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. Exposes almost the same API as messages.add_message(), but accepts the positional arguments in a different order to maintain backwards compatibility. For convenience, it accepts the `level` argument as a string rather than the usual level number. """ if not isinstance(level, int): # attempt to get the level if passed a string try: level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() levels_repr = ", ".join("`%s`" % level for level in levels) raise ValueError( "Bad message level string: `%s`. Possible values are: %s" % (level, levels_repr) ) messages.add_message( request, level, message, extra_tags=extra_tags, fail_silently=fail_silently ) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def delete_model(self, request, obj): """ Given a model instance delete it from the database. """ obj.delete() def delete_queryset(self, request, queryset): """Given a queryset, delete it from the database.""" queryset.delete() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) def render_change_form( self, request, context, add=False, change=False, form_url="", obj=None ): app_label = self.opts.app_label preserved_filters = self.get_preserved_filters(request) form_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, form_url ) view_on_site_url = self.get_view_on_site_url(obj) has_editable_inline_admin_formsets = False for inline in context["inline_admin_formsets"]: if ( inline.has_add_permission or inline.has_change_permission or inline.has_delete_permission ): has_editable_inline_admin_formsets = True break context.update( { "add": add, "change": change, "has_view_permission": self.has_view_permission(request, obj), "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_editable_inline_admin_formsets": ( has_editable_inline_admin_formsets ), "has_file_field": context["adminform"].form.is_multipart() or any( admin_formset.formset.is_multipart() for admin_formset in context["inline_admin_formsets"] ), "has_absolute_url": view_on_site_url is not None, "absolute_url": view_on_site_url, "form_url": form_url, "opts": self.opts, "content_type_id": get_content_type_for_model(self.model).pk, "save_as": self.save_as, "save_on_top": self.save_on_top, "to_field_var": TO_FIELD_VAR, "is_popup_var": IS_POPUP_VAR, "app_label": app_label, } ) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template request.current_app = self.admin_site.name return TemplateResponse( request, form_template or [ "admin/%s/%s/change_form.html" % (app_label, self.opts.model_name), "admin/%s/change_form.html" % app_label, "admin/change_form.html", ], context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. """ opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self.admin_site.name, ) # Add a link to the object's change form if the user can edit the obj. if self.has_change_permission(request, obj): obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj) else: obj_repr = str(obj) msg_dict = { "name": opts.verbose_name, "obj": obj_repr, } # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps( { "value": str(value), "obj": str(obj), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) elif "_continue" in request.POST or ( # Redirecting after "Save as new". "_saveasnew" in request.POST and self.save_as_continue and self.has_change_permission(request, obj) ): msg = _("The {name} “{obj}” was added successfully.") if self.has_change_permission(request, obj): msg += " " + _("You may edit it again below.") self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS) if post_url_continue is None: post_url_continue = obj_url post_url_continue = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url_continue, ) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was added successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj) def response_change(self, request, obj): """ Determine the HttpResponse for the change_view stage. """ if IS_POPUP_VAR in request.POST: opts = obj._meta to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else opts.pk.attname value = request.resolver_match.kwargs["object_id"] new_value = obj.serializable_value(attr) popup_response_data = json.dumps( { "action": "change", "value": str(value), "obj": str(obj), "new_value": str(new_value), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) opts = self.opts preserved_filters = self.get_preserved_filters(request) msg_dict = { "name": opts.verbose_name, "obj": format_html('<a href="{}">{}</a>', urlquote(request.path), obj), } if "_continue" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may edit it " "again below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_saveasnew" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may edit it again " "below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(obj.pk,), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_add" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was changed successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_change(request, obj) def _response_post_save(self, request, obj): if self.has_view_or_change_permission(request): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ return self._response_post_save(request, obj) def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ return self._response_post_save(request, obj) def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get("index", 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({"action": data.getlist("action")[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data["action"] select_across = action_form.cleaned_data["select_across"] func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse-like object, which will be # used as the response from the POST. If not, we'll be a good # little HTTP citizen and redirect back to the changelist page. if isinstance(response, HttpResponseBase): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg, messages.WARNING) return None def response_delete(self, request, obj_display, obj_id): """ Determine the HttpResponse for the delete_view stage. """ if IS_POPUP_VAR in request.POST: popup_response_data = json.dumps( { "action": "delete", "value": str(obj_id), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (self.opts.app_label, self.opts.model_name), "admin/%s/popup_response.html" % self.opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) self.message_user( request, _("The %(name)s “%(obj)s” was deleted successfully.") % { "name": self.opts.verbose_name, "obj": obj_display, }, messages.SUCCESS, ) if self.has_change_permission(request, None): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def render_delete_form(self, request, context): app_label = self.opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, media=self.media, ) return TemplateResponse( request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format( app_label, self.opts.model_name ), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html", ], context, ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = ( self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ) inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and override formset settings. has_add_permission = ( has_change_permission ) = has_delete_permission = False formset.extra = formset.max_num = 0 has_view_permission = inline.has_view_permission(request, obj) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet( inline, formset, fieldsets, prepopulated, readonly, model_admin=self, has_add_permission=has_add_permission, has_change_permission=has_change_permission, has_delete_permission=has_delete_permission, has_view_permission=has_view_permission, ) inline_admin_formsets.append(inline_admin_formset) return inline_admin_formsets def get_changeform_initial_data(self, request): """ Get the initial form data from the request's GET params. """ initial = dict(request.GET.items()) for k in initial: try: f = self.opts.get_field(k) except FieldDoesNotExist: continue # We have to special-case M2Ms as a list of comma-separated PKs. if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") return initial def _get_obj_does_not_exist_redirect(self, request, opts, object_id): """ Create a message informing the user that the object doesn't exist and return a redirect to the admin index page. """ msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % { "name": opts.verbose_name, "key": unquote(object_id), } self.message_user(request, msg, messages.WARNING) url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(url) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context) def _changeform_view(self, request, object_id, form_url, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) if request.method == "POST" and "_saveasnew" in request.POST: object_id = None add = object_id is None if add: if not self.has_add_permission(request): raise PermissionDenied obj = None else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == "POST": if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect( request, self.opts, object_id ) fieldsets = self.get_fieldsets(request, obj) ModelForm = self.get_form( request, obj, change=not add, fields=flatten_fieldsets(fieldsets) ) if request.method == "POST": form = ModelForm(request.POST, request.FILES, instance=obj) formsets, inline_instances = self._create_formsets( request, form.instance, change=not add, ) form_validated = form.is_valid() if form_validated: new_object = self.save_form(request, form, change=not add) else: new_object = form.instance if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) change_message = self.construct_change_message( request, form, formsets, add ) if add: self.log_addition(request, new_object, change_message) return self.response_add(request, new_object) else: self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: form_validated = False else: if add: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets( request, form.instance, change=False ) else: form = ModelForm(instance=obj) formsets, inline_instances = self._create_formsets( request, obj, change=True ) if not add and not self.has_change_permission(request, obj): readonly_fields = flatten_fieldsets(fieldsets) else: readonly_fields = self.get_readonly_fields(request, obj) admin_form = helpers.AdminForm( form, list(fieldsets), # Clear prepopulated fields on a view-only form to avoid a crash. self.get_prepopulated_fields(request, obj) if add or self.has_change_permission(request, obj) else {}, readonly_fields, model_admin=self, ) media = self.media + admin_form.media inline_formsets = self.get_inline_formsets( request, formsets, inline_instances, obj ) for inline_formset in inline_formsets: media += inline_formset.media if add: title = _("Add %s") elif self.has_change_permission(request, obj): title = _("Change %s") else: title = _("View %s") context = { **self.admin_site.each_context(request), "title": title % self.opts.verbose_name, "subtitle": str(obj) if obj else None, "adminform": admin_form, "object_id": object_id, "original": obj, "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, "media": media, "inline_admin_formsets": inline_formsets, "errors": helpers.AdminErrorList(form, formsets), "preserved_filters": self.get_preserved_filters(request), } # Hide the "Save" and "Save and continue" buttons if "Save as New" was # previously chosen to prevent the interface from getting confusing. if ( request.method == "POST" and not form_validated and "_saveasnew" in request.POST ): context["show_save"] = False context["show_save_and_continue"] = False # Use the change template instead of the add template. add = False context.update(extra_context or {}) return self.render_change_form( request, context, add=add, change=not add, obj=obj, form_url=form_url ) def add_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) def change_view(self, request, object_id, form_url="", extra_context=None): return self.changeform_view(request, object_id, form_url, extra_context) def _get_edited_object_pks(self, request, prefix): """Return POST data values of list_editable primary keys.""" pk_pattern = re.compile( r"{}-\d+-{}$".format(re.escape(prefix), self.opts.pk.name) ) return [value for key, value in request.POST.items() if pk_pattern.match(key)] def _get_list_editable_queryset(self, request, prefix): """ Based on POST data, return a queryset of the objects that were edited via list_editable. """ object_pks = self._get_edited_object_pks(request, prefix) queryset = self.get_queryset(request) validate = queryset.model._meta.pk.to_python try: for pk in object_pks: validate(pk) except ValidationError: # Disable the optimization if the POST data was tampered with. return queryset return queryset.filter(pk__in=object_pks) @csrf_protect_m def changelist_view(self, request, extra_context=None): """ The 'change list' admin view for this model. """ from django.contrib.admin.views.main import ERROR_FLAG app_label = self.opts.app_label if not self.has_view_or_change_permission(request): raise PermissionDenied try: cl = self.get_changelist_instance(request) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET: return SimpleTemplateResponse( "admin/invalid_setup.html", { "title": _("Database error"), }, ) return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1") # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) actions = self.get_actions(request) # Actions with no confirmation if ( actions and request.method == "POST" and "index" in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True else: msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) action_failed = True # Actions with confirmation if ( actions and request.method == "POST" and helpers.ACTION_CHECKBOX_NAME in request.POST and "index" not in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True if action_failed: # Redirect back to the changelist page to avoid resubmitting the # form if the user refreshes the browser or uses the "No, take # me back" button on the action confirmation page. return HttpResponseRedirect(request.get_full_path()) # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if request.method == "POST" and cl.list_editable and "_save" in request.POST: if not self.has_change_permission(request): raise PermissionDenied FormSet = self.get_changelist_formset(request) modified_objects = self._get_list_editable_queryset( request, FormSet.get_default_prefix() ) formset = cl.formset = FormSet( request.POST, request.FILES, queryset=modified_objects ) if formset.is_valid(): changecount = 0 with transaction.atomic(using=router.db_for_write(self.model)): for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message( request, form, None ) self.log_change(request, obj, change_msg) changecount += 1 if changecount: msg = ngettext( "%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount, ) % { "count": changecount, "name": model_ngettext(self.opts, changecount), } self.message_user(request, msg, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif cl.list_editable and self.has_change_permission(request): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) media += action_form.media else: action_form = None selection_note_all = ngettext( "%(total_count)s selected", "All %(total_count)s selected", cl.result_count ) context = { **self.admin_site.each_context(request), "module_name": str(self.opts.verbose_name_plural), "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)}, "selection_note_all": selection_note_all % {"total_count": cl.result_count}, "title": cl.title, "subtitle": None, "is_popup": cl.is_popup, "to_field": cl.to_field, "cl": cl, "media": media, "has_add_permission": self.has_add_permission(request), "opts": cl.opts, "action_form": action_form, "actions_on_top": self.actions_on_top, "actions_on_bottom": self.actions_on_bottom, "actions_selection_counter": self.actions_selection_counter, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_list_template or [ "admin/%s/%s/change_list.html" % (app_label, self.opts.model_name), "admin/%s/change_list.html" % app_label, "admin/change_list.html", ], context, ) def get_deleted_objects(self, objs, request): """ Hook for customizing the delete process for the delete view and the "delete selected" action. """ return get_deleted_objects(objs, request, self.admin_site) @csrf_protect_m def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context) def _delete_view(self, request, object_id, extra_context): "The 'delete' admin view for this model." app_label = self.opts.app_label to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) obj = self.get_object(request, unquote(object_id), to_field) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, self.opts, object_id) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. ( deleted_objects, model_count, perms_needed, protected, ) = self.get_deleted_objects([obj], request) if request.POST and not protected: # The user has confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = str(obj) attr = str(to_field) if to_field else self.opts.pk.attname obj_id = obj.serializable_value(attr) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return self.response_delete(request, obj_display, obj_id) object_name = str(self.opts.verbose_name) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") context = { **self.admin_site.each_context(request), "title": title, "subtitle": None, "object_name": object_name, "object": obj, "deleted_objects": deleted_objects, "model_count": dict(model_count).items(), "perms_lacking": perms_needed, "protected": protected, "opts": self.opts, "app_label": app_label, "preserved_filters": self.get_preserved_filters(request), "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, **(extra_context or {}), } return self.render_delete_form(request, context) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry from django.contrib.admin.views.main import PAGE_VAR # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: return self._get_obj_does_not_exist_redirect( request, model._meta, object_id ) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. app_label = self.opts.app_label action_list = ( LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model), ) .select_related() .order_by("action_time") ) paginator = self.get_paginator(request, action_list, 100) page_number = request.GET.get(PAGE_VAR, 1) page_obj = paginator.get_page(page_number) page_range = paginator.get_elided_page_range(page_obj.number) context = { **self.admin_site.each_context(request), "title": _("Change history: %s") % obj, "subtitle": None, "action_list": page_obj, "page_range": page_range, "page_var": PAGE_VAR, "pagination_required": paginator.count > 100, "module_name": str(capfirst(self.opts.verbose_name_plural)), "object": obj, "opts": self.opts, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, self.opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html", ], context, ) def get_formset_kwargs(self, request, obj, inline, prefix): formset_params = { "instance": obj, "prefix": prefix, "queryset": inline.get_queryset(request), } if request.method == "POST": formset_params.update( { "data": request.POST.copy(), "files": request.FILES, "save_as_new": "_saveasnew" in request.POST, } ) return formset_params def _create_formsets(self, request, obj, change): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if change: get_formsets_args.append(obj) for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = self.get_formset_kwargs(request, obj, inline, prefix) formset = FormSet(**formset_params) def user_deleted_form(request, obj, formset, index, inline): """Return whether or not the user deleted the form.""" return ( inline.has_delete_permission(request, obj) and "{}-{}-DELETE".format(formset.prefix, index) in request.POST ) # Bypass validation of each view-only inline form (since the form's # data won't be in request.POST), unless the form was deleted. if not inline.has_change_permission(request, obj if change else None): for index, form in enumerate(formset.initial_forms): if user_deleted_form(request, obj, formset, index, inline): continue form._errors = {} form.cleaned_data = form.initial formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 min_num = None max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True show_change_link = False checks_class = InlineModelAdminChecks classes = None def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) super().__init__() if self.verbose_name_plural is None: if self.verbose_name is None: self.verbose_name_plural = self.opts.verbose_name_plural else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) if self.verbose_name is None: self.verbose_name = self.opts.verbose_name @property def media(self): extra = "" if settings.DEBUG else ".min" js = ["vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "inlines.js"] if self.filter_vertical or self.filter_horizontal: js.extend(["SelectBox.js", "SelectFilter2.js"]) if self.classes and "collapse" in self.classes: js.append("collapse.js") return forms.Media(js=["admin/js/%s" % url for url in js]) def get_extra(self, request, obj=None, **kwargs): """Hook for customizing the number of extra inline forms.""" return self.extra def get_min_num(self, request, obj=None, **kwargs): """Hook for customizing the min number of inline forms.""" return self.min_num def get_max_num(self, request, obj=None, **kwargs): """Hook for customizing the max number of extra inline forms.""" return self.max_num def get_formset(self, request, obj=None, **kwargs): """Return a BaseInlineFormSet class for use in admin add/change views.""" if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) exclude.extend(self.get_readonly_fields(request, obj)) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # If exclude is an empty list we use None, since that's the actual # default. exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "extra": self.get_extra(request, obj, **kwargs), "min_num": self.get_min_num(request, obj, **kwargs), "max_num": self.get_max_num(request, obj, **kwargs), "can_delete": can_delete, **kwargs, } base_model_form = defaults["form"] can_change = self.has_change_permission(request, obj) if request else True can_add = self.has_add_permission(request, obj) if request else True class DeleteProtectedModelForm(base_model_form): def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance # representation, suitable to be an item in a # list. _("%(class_name)s %(instance)s") % {"class_name": p._meta.verbose_name, "instance": p} ) params = { "class_name": self._meta.model._meta.verbose_name, "instance": self.instance, "related_objects": get_text_list(objs, _("and")), } msg = _( "Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s" ) raise ValidationError( msg, code="deleting_protected", params=params ) def is_valid(self): result = super().is_valid() self.hand_clean_DELETE() return result def has_changed(self): # Protect against unauthorized edits. if not can_change and not self.instance._state.adding: return False if not can_add and self.instance._state.adding: return False return super().has_changed() defaults["form"] = DeleteProtectedModelForm if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS return inlineformset_factory(self.parent_model, self.model, **defaults) def _get_form_for_get_fields(self, request, obj=None): return self.get_formset(request, obj, fields=None).form def get_queryset(self, request): queryset = super().get_queryset(request) if not self.has_view_or_change_permission(request): queryset = queryset.none() return queryset def _has_any_perms_for_target_model(self, request, perms): """ This method is called only when the ModelAdmin's model is for an ManyToManyField's implicit through model (if self.opts.auto_created). Return True if the user has any of the given permissions ('add', 'change', etc.) for the model that points to the through model. """ opts = self.opts # Find the target model of an auto-created many-to-many relationship. for field in opts.fields: if field.remote_field and field.remote_field.model != self.parent_model: opts = field.remote_field.model._meta break return any( request.user.has_perm( "%s.%s" % (opts.app_label, get_permission_codename(perm, opts)) ) for perm in perms ) def has_add_permission(self, request, obj): if self.opts.auto_created: # Auto-created intermediate models don't have their own # permissions. The user needs to have the change permission for the # related model in order to be able to do anything with the # intermediate model. return self._has_any_perms_for_target_model(request, ["change"]) return super().has_add_permission(request) def has_change_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_change_permission(request) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_delete_permission(request, obj) def has_view_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). The 'change' permission # also implies the 'view' permission. return self._has_any_perms_for_target_model(request, ["view", "change"]) return super().has_view_permission(request) class StackedInline(InlineModelAdmin): template = "admin/edit_inline/stacked.html" class TabularInline(InlineModelAdmin): template = "admin/edit_inline/tabular.html"
0244eb7aa4d2f1ab1b08609680c0d7c5affd19b73e1adbea99ab4ce75ede206f
""" Built-in, globally-available admin actions. """ from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.decorators import action from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy @action( permissions=["delete"], description=gettext_lazy("Delete selected %(verbose_name_plural)s"), ) def delete_selected(modeladmin, request, queryset): """ Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. Next, it deletes all selected objects and redirects back to the change list. """ opts = modeladmin.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objects that # will also be deleted. ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = len(queryset) if n: for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) modeladmin.delete_queryset(request, queryset) modeladmin.message_user( request, _("Successfully deleted %(count)d %(items)s.") % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { **modeladmin.admin_site.each_context(request), "title": title, "subtitle": None, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html", ], context, )
c7c1c2b9ba96e5d0de045746a5efd4663904fe729c137fc64e167252db4b7acb
import json import os import posixpath import re from hashlib import md5 from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.utils import check_settings, matches_patterns from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, storages from django.utils.functional import LazyObject class StaticFilesStorage(FileSystemStorage): """ Standard file system storage for static files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name) class HashedFilesMixin: default_template = """url("%(url)s")""" max_post_process_passes = 5 support_js_module_import_aggregation = False _js_module_import_aggregation_patterns = ( "*.js", ( ( ( r"""(?P<matched>import(?s:(?P<import>[\s\{].*?))""" r"""\s*from\s*['"](?P<url>[\.\/].*?)["']\s*;)""" ), """import%(import)s from "%(url)s";""", ), ( ( r"""(?P<matched>export(?s:(?P<exports>[\s\{].*?))""" r"""\s*from\s*["'](?P<url>[\.\/].*?)["']\s*;)""" ), """export%(exports)s from "%(url)s";""", ), ( r"""(?P<matched>import\s*['"](?P<url>[\.\/].*?)["']\s*;)""", """import"%(url)s";""", ), ( r"""(?P<matched>import\(["'](?P<url>.*?)["']\))""", """import("%(url)s")""", ), ), ) patterns = ( ( "*.css", ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", ( r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""", """@import url("%(url)s")""", ), ( ( r"(?m)^(?P<matched>/\*#[ \t]" r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$" ), "/*# sourceMappingURL=%(url)s */", ), ), ), ( "*.js", ( ( r"(?m)^(?P<matched>//# (?-i:sourceMappingURL)=(?P<url>.*))$", "//# sourceMappingURL=%(url)s", ), ), ), ) keep_intermediate_files = True def __init__(self, *args, **kwargs): if self.support_js_module_import_aggregation: self.patterns += (self._js_module_import_aggregation_patterns,) super().__init__(*args, **kwargs) self._patterns = {} self.hashed_files = {} for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template)) def file_hash(self, name, content=None): """ Return a hash of the file with the given name and optional content. """ if content is None: return None hasher = md5(usedforsecurity=False) for chunk in content.chunks(): hasher.update(chunk) return hasher.hexdigest()[:12] def hashed_name(self, name, content=None, filename=None): # `filename` is the name of file to hash if `content` isn't given. # `name` is the base name to construct the new hashed filename from. parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name opened = content is None if opened: if not self.exists(filename): raise ValueError( "The file '%s' could not be found with %r." % (filename, self) ) try: content = self.open(filename) except OSError: # Handle directory paths and fragments return name try: file_hash = self.file_hash(clean_name, content) finally: if opened: content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) file_hash = (".%s" % file_hash) if file_hash else "" hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) def _url(self, hashed_name_func, name, force=False, hashed_files=None): """ Return the non-hashed URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, "" else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith("/"): # don't hash paths hashed_name = name else: args = (clean_name,) if hashed_files is not None: args += (hashed_files,) hashed_name = hashed_name_func(*args) final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = "?#" in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += "?" final_url = urlunsplit(urlparts) return unquote(final_url) def url(self, name, force=False): """ Return the non-hashed URL in DEBUG mode. """ return self._url(self.stored_name, name, force) def url_converter(self, name, hashed_files, template=None): """ Return the custom URL converter for the given file name. """ if template is None: template = self.default_template def converter(matchobj): """ Convert the matched URL to a normalized and hashed URL. This requires figuring out which files the matched URL resolves to and calling the url() method of the storage. """ matches = matchobj.groupdict() matched = matches["matched"] url = matches["url"] # Ignore absolute/protocol-relative and data-uri URLs. if re.match(r"^[a-z]+:", url): return matched # Ignore absolute URLs that don't point to a static file (dynamic # CSS / JS?). Note that STATIC_URL cannot be empty. if url.startswith("/") and not url.startswith(settings.STATIC_URL): return matched # Strip off the fragment so a path-like fragment won't interfere. url_path, fragment = urldefrag(url) # Ignore URLs without a path if not url_path: return matched if url_path.startswith("/"): # Otherwise the condition above would have returned prematurely. assert url_path.startswith(settings.STATIC_URL) target_name = url_path.removeprefix(settings.STATIC_URL) else: # We're using the posixpath module to mix paths and URLs conveniently. source_name = name if os.sep == "/" else name.replace(os.sep, "/") target_name = posixpath.join(posixpath.dirname(source_name), url_path) # Determine the hashed name of the target file with the storage backend. hashed_url = self._url( self._stored_name, unquote(target_name), force=True, hashed_files=hashed_files, ) transformed_url = "/".join( url_path.split("/")[:-1] + hashed_url.split("/")[-1:] ) # Restore the fragment that was stripped off earlier. if fragment: transformed_url += ("?#" if "?#" in url else "#") + fragment # Return the hashed version to the file matches["url"] = unquote(transformed_url) return template % matches return converter def post_process(self, paths, dry_run=False, **options): """ Post process the given dictionary of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-busting filenames. If either of these are performed on a file, then that file is considered post-processed. """ # don't even dare to process the files if we're in dry run mode if dry_run: return # where to store the new paths hashed_files = {} # build a list of adjustable files adjustable_paths = [ path for path in paths if matches_patterns(path, self._patterns) ] # Adjustable files to yield at end, keyed by the original path. processed_adjustable_paths = {} # Do a single pass first. Post-process all files once, yielding not # adjustable files and exceptions, and collecting adjustable files. for name, hashed_name, processed, _ in self._post_process( paths, adjustable_paths, hashed_files ): if name not in adjustable_paths or isinstance(processed, Exception): yield name, hashed_name, processed else: processed_adjustable_paths[name] = (name, hashed_name, processed) paths = {path: paths[path] for path in adjustable_paths} substitutions = False for i in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files ): # Overwrite since hashed_name may be newer. processed_adjustable_paths[name] = (name, hashed_name, processed) substitutions = substitutions or subst if not substitutions: break if substitutions: yield "All", None, RuntimeError("Max post-process passes exceeded.") # Store the processed paths self.hashed_files.update(hashed_files) # Yield adjustable files with final, hashed name. yield from processed_adjustable_paths.values() def _post_process(self, paths, adjustable_paths, hashed_files): # Sort the files by directory level def path_level(name): return len(name.split(os.sep)) for name in sorted(paths, key=path_level, reverse=True): substitutions = True # use the original, local file, not the copied-but-unprocessed # file, which might be somewhere far away, like S3 storage, path = paths[name] with storage.open(path) as original_file: cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) # generate the hash with the original content, even for # adjustable files. if hash_key not in hashed_files: hashed_name = self.hashed_name(name, original_file) else: hashed_name = hashed_files[hash_key] # then get the original's file content.. if hasattr(original_file, "seek"): original_file.seek(0) hashed_file_exists = self.exists(hashed_name) processed = False # ..to apply each replacement pattern to the content if name in adjustable_paths: old_hashed_name = hashed_name try: content = original_file.read().decode("utf-8") except UnicodeDecodeError as exc: yield name, None, exc, False for extension, patterns in self._patterns.items(): if matches_patterns(path, (extension,)): for pattern, template in patterns: converter = self.url_converter( name, hashed_files, template ) try: content = pattern.sub(converter, content) except ValueError as exc: yield name, None, exc, False if hashed_file_exists: self.delete(hashed_name) # then save the processed result content_file = ContentFile(content.encode()) if self.keep_intermediate_files: # Save intermediate file for reference self._save(hashed_name, content_file) hashed_name = self.hashed_name(name, content_file) if self.exists(hashed_name): self.delete(hashed_name) saved_name = self._save(hashed_name, content_file) hashed_name = self.clean_name(saved_name) # If the file hash stayed the same, this file didn't change if old_hashed_name == hashed_name: substitutions = False processed = True if not processed: # or handle the case in which neither processing nor # a change to the original file happened if not hashed_file_exists: processed = True saved_name = self._save(hashed_name, original_file) hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name yield name, hashed_name, processed, substitutions def clean_name(self, name): return name.replace("\\", "/") def hash_key(self, name): return name def _stored_name(self, name, hashed_files): # Normalize the path to avoid multiple names for the same file like # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same # path. name = posixpath.normpath(name) cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = hashed_files.get(hash_key) if cache_name is None: cache_name = self.clean_name(self.hashed_name(name)) return cache_name def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self)) class ManifestFilesMixin(HashedFilesMixin): manifest_version = "1.1" # the manifest format standard manifest_name = "staticfiles.json" manifest_strict = True keep_intermediate_files = False def __init__(self, *args, manifest_storage=None, **kwargs): super().__init__(*args, **kwargs) if manifest_storage is None: manifest_storage = self self.manifest_storage = manifest_storage self.hashed_files, self.manifest_hash = self.load_manifest() def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode() except FileNotFoundError: return None def load_manifest(self): content = self.read_manifest() if content is None: return {}, "" try: stored = json.loads(content) except json.JSONDecodeError: pass else: version = stored.get("version") if version in ("1.0", "1.1"): return stored.get("paths", {}), stored.get("hash", "") raise ValueError( "Couldn't load manifest '%s' (version %s)" % (self.manifest_name, self.manifest_version) ) def post_process(self, *args, **kwargs): self.hashed_files = {} yield from super().post_process(*args, **kwargs) if not kwargs.get("dry_run"): self.save_manifest() def save_manifest(self): self.manifest_hash = self.file_hash( None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode()) ) payload = { "paths": self.hashed_files, "version": self.manifest_version, "hash": self.manifest_hash, } if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode() self.manifest_storage._save(self.manifest_name, ContentFile(contents)) def stored_name(self, name): parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() hash_key = self.hash_key(clean_name) cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: raise ValueError( "Missing staticfiles manifest entry for '%s'" % clean_name ) cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage): """ A static file system storage backend which also saves hashed copies of the files it saves. """ pass class ConfiguredStorage(LazyObject): def _setup(self): self._wrapped = storages[STATICFILES_STORAGE_ALIAS] staticfiles_storage = ConfiguredStorage()
7a7ff17e6d2244edda76ada40646e9fd40e87c7ef1391e3418396260fdc5eb5f
import warnings from datetime import datetime, timedelta from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import FieldListFilter from django.contrib.admin.exceptions import ( DisallowedModelAdminLookup, DisallowedModelAdminToField, ) from django.contrib.admin.options import ( IS_FACETS_VAR, IS_POPUP_VAR, TO_FIELD_VAR, IncorrectLookupParameters, ShowFacets, ) from django.contrib.admin.utils import ( build_q_object_from_lookup_parameters, get_fields_from_path, lookup_spawns_duplicates, prepare_lookup_value, quote, ) from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, SuspiciousOperation, ) from django.core.paginator import InvalidPage from django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterRef from django.db.models.expressions import Combinable from django.urls import reverse from django.utils.deprecation import RemovedInDjango60Warning from django.utils.http import urlencode from django.utils.inspect import func_supports_parameter from django.utils.timezone import make_aware from django.utils.translation import gettext # Changelist settings ALL_VAR = "all" ORDER_VAR = "o" PAGE_VAR = "p" SEARCH_VAR = "q" ERROR_FLAG = "e" IGNORED_PARAMS = ( ALL_VAR, ORDER_VAR, SEARCH_VAR, IS_FACETS_VAR, IS_POPUP_VAR, TO_FIELD_VAR, ) class ChangeListSearchForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate "fields" dynamically because SEARCH_VAR is a variable: self.fields = { SEARCH_VAR: forms.CharField(required=False, strip=False), } class ChangeList: search_form_class = ChangeListSearchForm def __init__( self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin, sortable_by, search_help_text, ): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_queryset = model_admin.get_queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.has_filters = None self.has_active_filters = None self.clear_all_filters_qs = None self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_max_show_all = list_max_show_all self.model_admin = model_admin self.preserved_filters = model_admin.get_preserved_filters(request) self.sortable_by = sortable_by self.search_help_text = search_help_text # Get search parameters from the query string. _search_form = self.search_form_class(request.GET) if not _search_form.is_valid(): for error in _search_form.errors.values(): messages.error(request, ", ".join(error)) self.query = _search_form.cleaned_data.get(SEARCH_VAR) or "" try: self.page_num = int(request.GET.get(PAGE_VAR, 1)) except ValueError: self.page_num = 1 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET self.add_facets = model_admin.show_facets is ShowFacets.ALWAYS or ( model_admin.show_facets is ShowFacets.ALLOW and IS_FACETS_VAR in request.GET ) self.is_facets_optional = model_admin.show_facets is ShowFacets.ALLOW to_field = request.GET.get(TO_FIELD_VAR) if to_field and not model_admin.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) self.to_field = to_field self.params = dict(request.GET.items()) self.filter_params = dict(request.GET.lists()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] del self.filter_params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] del self.filter_params[ERROR_FLAG] self.remove_facet_link = self.get_query_string(remove=[IS_FACETS_VAR]) self.add_facet_link = self.get_query_string({IS_FACETS_VAR: True}) if self.is_popup: self.list_editable = () else: self.list_editable = list_editable self.queryset = self.get_queryset(request) self.get_results(request) if self.is_popup: title = gettext("Select %s") elif self.model_admin.has_change_permission(request): title = gettext("Select %s to change") else: title = gettext("Select %s to view") self.title = title % self.opts.verbose_name self.pk_attname = self.lookup_opts.pk.attname def __repr__(self): return "<%s: model=%s model_admin=%s>" % ( self.__class__.__qualname__, self.model.__qualname__, self.model_admin.__class__.__qualname__, ) def get_filters_params(self, params=None): """ Return all params except IGNORED_PARAMS. """ params = params or self.filter_params lookup_params = params.copy() # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] return lookup_params def get_filters(self, request): lookup_params = self.get_filters_params() may_have_duplicates = False has_active_filters = False supports_request = func_supports_parameter( self.model_admin.lookup_allowed, "request" ) if not supports_request: warnings.warn( f"`request` must be added to the signature of " f"{self.model_admin.__class__.__qualname__}.lookup_allowed().", RemovedInDjango60Warning, ) for key, value_list in lookup_params.items(): for value in value_list: params = (key, value, request) if supports_request else (key, value) if not self.model_admin.lookup_allowed(*params): raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed") filter_specs = [] for list_filter in self.list_filter: lookup_params_count = len(lookup_params) if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(request, lookup_params, self.model, self.model_admin) else: field_path = None if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for the # type of the given field. field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] spec = field_list_filter_class( field, request, lookup_params, self.model, self.model_admin, field_path=field_path, ) # field_list_filter_class removes any lookup_params it # processes. If that happened, check if duplicates should be # removed. if lookup_params_count > len(lookup_params): may_have_duplicates |= lookup_spawns_duplicates( self.lookup_opts, field_path, ) if spec and spec.has_output(): filter_specs.append(spec) if lookup_params_count > len(lookup_params): has_active_filters = True if self.date_hierarchy: # Create bounded lookup parameters so that the query is more # efficient. year = lookup_params.pop("%s__year" % self.date_hierarchy, None) if year is not None: month = lookup_params.pop("%s__month" % self.date_hierarchy, None) day = lookup_params.pop("%s__day" % self.date_hierarchy, None) try: from_date = datetime( int(year[-1]), int(month[-1] if month is not None else 1), int(day[-1] if day is not None else 1), ) except ValueError as e: raise IncorrectLookupParameters(e) from e if day: to_date = from_date + timedelta(days=1) elif month: # In this branch, from_date will always be the first of a # month, so advancing 32 days gives the next month. to_date = (from_date + timedelta(days=32)).replace(day=1) else: to_date = from_date.replace(year=from_date.year + 1) if settings.USE_TZ: from_date = make_aware(from_date) to_date = make_aware(to_date) lookup_params.update( { "%s__gte" % self.date_hierarchy: [from_date], "%s__lt" % self.date_hierarchy: [to_date], } ) # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them spawns duplicates. If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) may_have_duplicates |= lookup_spawns_duplicates(self.lookup_opts, key) return ( filter_specs, bool(filter_specs), lookup_params, may_have_duplicates, has_active_filters, ) except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) from e def get_query_string(self, new_params=None, remove=None): if new_params is None: new_params = {} if remove is None: remove = [] p = self.filter_params.copy() for r in remove: for k in list(p): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return "?%s" % urlencode(sorted(p.items()), doseq=True) def get_results(self, request): paginator = self.model_admin.get_paginator( request, self.queryset, self.list_per_page ) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. if self.model_admin.show_full_result_count: full_result_count = self.root_queryset.count() else: full_result_count = None can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.queryset._clone() else: try: result_list = paginator.page(self.page_num).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.show_full_result_count = self.model_admin.show_full_result_count # Admin actions are shown if there is at least one entry # or if entries are not counted because show_full_result_count is disabled self.show_admin_actions = not self.show_full_result_count or bool( full_result_count ) self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator def _get_default_ordering(self): ordering = [] if self.model_admin.ordering: ordering = self.model_admin.ordering elif self.lookup_opts.ordering: ordering = self.lookup_opts.ordering return ordering def get_ordering_field(self, field_name): """ Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) if isinstance(attr, property) and hasattr(attr, "fget"): attr = attr.fget return getattr(attr, "admin_order_field", None) def get_ordering(self, request, queryset): """ Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering. """ params = self.params ordering = list( self.model_admin.get_ordering(request) or self._get_default_ordering() ) if ORDER_VAR in params: # Clear ordering and used params ordering = [] order_params = params[ORDER_VAR].split(".") for p in order_params: try: none, pfx, idx = p.rpartition("-") field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: continue # No 'admin_order_field', skip it if isinstance(order_field, OrderBy): if pfx == "-": order_field = order_field.copy() order_field.reverse_ordering() ordering.append(order_field) elif hasattr(order_field, "resolve_expression"): # order_field is an expression. ordering.append( order_field.desc() if pfx == "-" else order_field.asc() ) # reverse order if order_field has already "-" as prefix elif pfx == "-" and order_field.startswith(pfx): ordering.append(order_field.removeprefix(pfx)) else: ordering.append(pfx + order_field) except (IndexError, ValueError): continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) return self._get_deterministic_ordering(ordering) def _get_deterministic_ordering(self, ordering): """ Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key. """ ordering = list(ordering) ordering_fields = set() total_ordering_fields = {"pk"} | { field.attname for field in self.lookup_opts.fields if field.unique and not field.null } for part in ordering: # Search for single field providing a total ordering. field_name = None if isinstance(part, str): field_name = part.lstrip("-") elif isinstance(part, F): field_name = part.name elif isinstance(part, OrderBy) and isinstance(part.expression, F): field_name = part.expression.name if field_name: # Normalize attname references by using get_field(). try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: # Could be "?" for random ordering or a related field # lookup. Skip this part of introspection for now. continue # Ordering by a related field name orders by the referenced # model's ordering. Skip this part of introspection for now. if field.remote_field and field_name == field.name: continue if field.attname in total_ordering_fields: break ordering_fields.add(field.attname) else: # No single total ordering field, try unique_together and total # unique constraints. constraint_field_names = ( *self.lookup_opts.unique_together, *( constraint.fields for constraint in self.lookup_opts.total_unique_constraints ), ) for field_names in constraint_field_names: # Normalize attname references by using get_field(). fields = [ self.lookup_opts.get_field(field_name) for field_name in field_names ] # Composite unique constraints containing a nullable column # cannot ensure total ordering. if any(field.null for field in fields): continue if ordering_fields.issuperset(field.attname for field in fields): break else: # If no set of unique fields is present in the ordering, rely # on the primary key to provide total ordering. ordering.append("-pk") return ordering def get_ordering_field_columns(self): """ Return a dictionary of ordering field column numbers and asc/desc. """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = {} if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if isinstance(field, (Combinable, OrderBy)): if not isinstance(field, OrderBy): field = field.asc() if isinstance(field.expression, F): order_type = "desc" if field.descending else "asc" field = field.expression.name else: continue elif field.startswith("-"): field = field.removeprefix("-") order_type = "desc" else: order_type = "asc" for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split("."): none, pfx, idx = p.rpartition("-") try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = "desc" if pfx == "-" else "asc" return ordering_fields def get_queryset(self, request, exclude_parameters=None): # First, we collect all the declared list filters. ( self.filter_specs, self.has_filters, remaining_lookup_params, filters_may_have_duplicates, self.has_active_filters, ) = self.get_filters(request) # Then, we let every list filter modify the queryset to its liking. qs = self.root_queryset for filter_spec in self.filter_specs: if ( exclude_parameters is None or filter_spec.expected_parameters() != exclude_parameters ): new_qs = filter_spec.queryset(request, qs) if new_qs is not None: qs = new_qs try: # Finally, we apply the remaining lookup parameters from the query # string (i.e. those that haven't already been processed by the # filters). q_object = build_q_object_from_lookup_parameters(remaining_lookup_params) qs = qs.filter(q_object) except (SuspiciousOperation, ImproperlyConfigured): # Allow certain types of errors to be re-raised as-is so that the # caller can treat them in a special way. raise except Exception as e: # Every other error is caught with a naked except, because we don't # have any other way of validating lookup parameters. They might be # invalid if the keyword arguments are incorrect, or if the values # are not in the correct type, so we might get FieldError, # ValueError, ValidationError, or ?. raise IncorrectLookupParameters(e) # Apply search results qs, search_may_have_duplicates = self.model_admin.get_search_results( request, qs, self.query, ) # Set query string for clearing all filters. self.clear_all_filters_qs = self.get_query_string( new_params=remaining_lookup_params, remove=self.get_filters_params(), ) # Remove duplicates from results, if necessary if filters_may_have_duplicates | search_may_have_duplicates: qs = qs.filter(pk=OuterRef("pk")) qs = self.root_queryset.filter(Exists(qs)) # Set ordering. ordering = self.get_ordering(request, qs) qs = qs.order_by(*ordering) if not qs.query.select_related: qs = self.apply_select_related(qs) return qs def apply_select_related(self, qs): if self.list_select_related is True: return qs.select_related() if self.list_select_related is False: if self.has_related_field_in_list_display(): return qs.select_related() if self.list_select_related: return qs.select_related(*self.list_select_related) return qs def has_related_field_in_list_display(self): for field_name in self.list_display: try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: pass else: if isinstance(field.remote_field, ManyToOneRel): # <FK>_id field names don't require a join. if field_name != field.get_attname(): return True return False def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( "admin:%s_%s_change" % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name, )
ebb5bfb63ed8eaf475cb083d3ce094c09fd3e76c47d0998b9b8677e471a8d548
from django.db import migrations, models from django.db.migrations import operations from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.serializer import serializer_factory from django.test import SimpleTestCase from .models import EmptyManager, UnicodeModel class OptimizerTests(SimpleTestCase): """ Tests the migration autodetector. """ def optimize(self, operations, app_label): """ Handy shortcut for getting results + number of loops """ optimizer = MigrationOptimizer() return optimizer.optimize(operations, app_label), optimizer._iterations def serialize(self, value): return serializer_factory(value).serialize()[0] def assertOptimizesTo( self, operations, expected, exact=None, less_than=None, app_label=None ): result, iterations = self.optimize(operations, app_label or "migrations") result = [self.serialize(f) for f in result] expected = [self.serialize(f) for f in expected] self.assertEqual(expected, result) if exact is not None and iterations != exact: raise self.failureException( "Optimization did not take exactly %s iterations (it took %s)" % (exact, iterations) ) if less_than is not None and iterations >= less_than: raise self.failureException( "Optimization did not take less than %s iterations (it took %s)" % (less_than, iterations) ) def assertDoesNotOptimize(self, operations, **kwargs): self.assertOptimizesTo(operations, operations, **kwargs) def test_none_app_label(self): optimizer = MigrationOptimizer() with self.assertRaisesMessage(TypeError, "app_label must be a str"): optimizer.optimize([], None) def test_single(self): """ The optimizer does nothing on a single operation, and that it does it in just one pass. """ self.assertOptimizesTo( [migrations.DeleteModel("Foo")], [migrations.DeleteModel("Foo")], exact=1, ) def test_create_delete_model(self): """ CreateModel and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.DeleteModel("Foo"), ], [], ) def test_create_rename_model(self): """ CreateModel should absorb RenameModels. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameModel("Foo", "Bar"), ], [ migrations.CreateModel( "Bar", [("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ) ], ) def test_rename_model_self(self): """ RenameModels should absorb themselves. """ self.assertOptimizesTo( [ migrations.RenameModel("Foo", "Baa"), migrations.RenameModel("Baa", "Bar"), ], [ migrations.RenameModel("Foo", "Bar"), ], ) def test_create_alter_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelOptions( name="Foo", options={"verbose_name_plural": "Foozes"} ), ], [ migrations.CreateModel( "Foo", fields=[], options={"verbose_name_plural": "Foozes"} ), ], ) def test_create_alter_model_managers(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelManagers( name="Foo", managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], [ migrations.CreateModel( "Foo", fields=[], managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], ) def test_create_model_and_remove_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), migrations.AlterModelOptions("MyModel", options={}), ], [migrations.CreateModel("MyModel", fields=[])], ) self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={ "verbose_name": "My Model", "verbose_name_plural": "My Model plural", }, ), migrations.AlterModelOptions( "MyModel", options={"verbose_name": "My Model"}, ), ], [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), ], ) def _test_create_alter_foo_delete_model(self, alter_foo): """ CreateModel, AlterModelTable, AlterUniqueTogether/AlterIndexTogether/ AlterOrderWithRespectTo, and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AlterModelTable("Foo", "woohoo"), alter_foo, migrations.DeleteModel("Foo"), ], [], ) def test_create_alter_unique_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterUniqueTogether("Foo", [["a", "b"]]) ) def test_create_alter_index_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterIndexTogether("Foo", [["a", "b"]]) ) def test_create_alter_owrt_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterOrderWithRespectTo("Foo", "a") ) def _test_alter_alter(self, alter_foo, alter_bar): """ Two AlterUniqueTogether/AlterIndexTogether/AlterOrderWithRespectTo /AlterField should collapse into the second. """ self.assertOptimizesTo( [ alter_foo, alter_bar, ], [ alter_bar, ], ) def test_alter_alter_table_model(self): self._test_alter_alter( migrations.AlterModelTable("Foo", "a"), migrations.AlterModelTable("Foo", "b"), ) def test_alter_alter_unique_model(self): self._test_alter_alter( migrations.AlterUniqueTogether("Foo", [["a", "b"]]), migrations.AlterUniqueTogether("Foo", [["a", "c"]]), ) def test_alter_alter_index_model(self): self._test_alter_alter( migrations.AlterIndexTogether("Foo", [["a", "b"]]), migrations.AlterIndexTogether("Foo", [["a", "c"]]), ) def test_alter_alter_owrt_model(self): self._test_alter_alter( migrations.AlterOrderWithRespectTo("Foo", "a"), migrations.AlterOrderWithRespectTo("Foo", "b"), ) def test_alter_alter_field(self): self._test_alter_alter( migrations.AlterField("Foo", "name", models.IntegerField()), migrations.AlterField("Foo", "name", models.IntegerField(help_text="help")), ) def test_optimize_through_create(self): """ We should be able to optimize away create/delete through a create or delete of a different model, but only if the create operation does not mention the model at all. """ # These should work self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel("Bar", [("size", models.IntegerField())]), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Bar"), migrations.DeleteModel("Foo"), ], [], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), migrations.DeleteModel("Bar"), ], [], ) # Operations should be optimized if the FK references a model from the # other app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), ], app_label="otherapp", ) # But it shouldn't work if a FK references a model with the same # app_label. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # This should not work - bases should block it self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("Foo",) ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # The same operations should be optimized if app_label and none of # bases belong to that app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), ], app_label="otherapp", ) # But it shouldn't work if some of bases belongs to the specified app. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) self.assertOptimizesTo( [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Person", [("name", models.CharField(max_length=255))] ), migrations.AddField( "book", "author", models.ForeignKey("test_app.Person", models.CASCADE), ), migrations.CreateModel( "Review", [("book", models.ForeignKey("test_app.Book", models.CASCADE))], ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.AddField( "review", "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), migrations.RemoveField("book", "author"), migrations.DeleteModel("Person"), ], [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Review", [ ("book", models.ForeignKey("test_app.Book", models.CASCADE)), ( "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), ], ), ], app_label="test_app", ) def test_create_model_add_field(self): """ AddField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AddField("Foo", "age", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_reordering(self): """ AddField optimizes into CreateModel if it's a FK to a model that's between them (and there's no FK in the other direction), by changing the order of the CreateModel operations. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Foo", "link", models.ForeignKey("migrations.Link", models.CASCADE) ), ], [ migrations.CreateModel("Link", [("url", models.TextField())]), migrations.CreateModel( "Foo", [ ("name", models.CharField(max_length=255)), ("link", models.ForeignKey("migrations.Link", models.CASCADE)), ], ), ], ) def test_create_model_reordering_circular_fk(self): """ CreateModel reordering behavior doesn't result in an infinite loop if there are FKs in both directions. """ self.assertOptimizesTo( [ migrations.CreateModel("Bar", [("url", models.TextField())]), migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AddField( "Bar", "foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE) ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [ ("url", models.TextField()), ("foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE)), ], ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], ) def test_create_model_no_reordering_for_unrelated_fk(self): """ CreateModel order remains unchanged if the later AddField operation isn't a FK between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Other", "link", models.ForeignKey("migrations.Link", models.CASCADE), ), ], ) def test_create_model_no_reordering_of_inherited_model(self): """ A CreateModel that inherits from another isn't reordered to avoid moving it earlier than its parent CreateModel operation. """ self.assertOptimizesTo( [ migrations.CreateModel( "Other", [("foo", models.CharField(max_length=255))] ), migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.AddField( "Other", "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], [ migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.CreateModel( "Other", [ ("foo", models.CharField(max_length=255)), ( "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], ), ], ) def test_create_model_add_field_not_through_m2m_through(self): """ AddField should NOT optimize into CreateModel if it's an M2M using a through that's created between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel("Employee", []), migrations.CreateModel("Employer", []), migrations.CreateModel( "Employment", [ ( "employee", models.ForeignKey("migrations.Employee", models.CASCADE), ), ( "employment", models.ForeignKey("migrations.Employer", models.CASCADE), ), ], ), migrations.AddField( "Employer", "employees", models.ManyToManyField( "migrations.Employee", through="migrations.Employment", ), ), ], ) def test_create_model_alter_field(self): """ AlterField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AlterField("Foo", "name", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_rename_field(self): """ RenameField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameField("Foo", "name", "title"), ], [ migrations.CreateModel( name="Foo", fields=[ ("title", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_rename_field(self): """ RenameField should optimize into AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), ], [ migrations.AddField("Foo", "title", models.CharField(max_length=255)), ], ) def test_alter_field_rename_field(self): """ RenameField should optimize to the other side of AlterField, and into itself. """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), migrations.RenameField("Foo", "title", "nom"), ], [ migrations.RenameField("Foo", "name", "nom"), migrations.AlterField("Foo", "nom", models.CharField(max_length=255)), ], ) def test_swapping_fields_names(self): self.assertDoesNotOptimize( [ migrations.CreateModel( "MyModel", [ ("field_a", models.IntegerField()), ("field_b", models.IntegerField()), ], ), migrations.RunPython(migrations.RunPython.noop), migrations.RenameField("MyModel", "field_a", "field_c"), migrations.RenameField("MyModel", "field_b", "field_a"), migrations.RenameField("MyModel", "field_c", "field_b"), ], ) def test_create_model_remove_field(self): """ RemoveField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RemoveField("Foo", "age"), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_alter_field(self): """ AlterField should optimize into AddField. """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.AlterField("Foo", "age", models.FloatField(default=2.4)), ], [ migrations.AddField( "Foo", name="age", field=models.FloatField(default=2.4) ), ], ) def test_add_field_delete_field(self): """ RemoveField should cancel AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [], ) def test_alter_field_delete_field(self): """ RemoveField should absorb AlterField """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [ migrations.RemoveField("Foo", "age"), ], ) def _test_create_alter_foo_field(self, alter): """ CreateModel, AlterFooTogether/AlterOrderWithRespectTo followed by an add/alter/rename field should optimize to CreateModel with options. """ option_value = getattr(alter, alter.option_name) options = {alter.option_name: option_value} # AddField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AddField("Foo", "c", models.IntegerField()), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], options=options, ), ], ) # AlterField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "b", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.CharField(max_length=255)), ], options=options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "c", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.CharField(max_length=255)), ], options=options, ), ], ) # RenameField if isinstance(option_value, str): renamed_options = {alter.option_name: "c"} else: renamed_options = { alter.option_name: { tuple("c" if value == "b" else value for value in item) for item in option_value } } self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "b", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("c", models.IntegerField()), ], options=renamed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "b", "x"), migrations.RenameField("Foo", "x", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("c", models.IntegerField()), ], options=renamed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "c", "d"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("d", models.IntegerField()), ], options=options, ), ], ) # RemoveField if isinstance(option_value, str): removed_options = None else: removed_options = { alter.option_name: { tuple(value for value in item if value != "b") for item in option_value } } self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RemoveField("Foo", "b"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ], options=removed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.RemoveField("Foo", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], options=options, ), ], ) def test_create_alter_unique_field(self): self._test_create_alter_foo_field( migrations.AlterUniqueTogether("Foo", [["a", "b"]]) ) def test_create_alter_index_field(self): self._test_create_alter_foo_field( migrations.AlterIndexTogether("Foo", [["a", "b"]]) ) def test_create_alter_owrt_field(self): self._test_create_alter_foo_field( migrations.AlterOrderWithRespectTo("Foo", "b") ) def test_optimize_through_fields(self): """ field-level through checking is working. This should manage to collapse model Foo to nonexistence, and model Bar to a single IntegerField called "width". """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.AddField("Foo", "age", models.IntegerField()), migrations.AddField("Bar", "width", models.IntegerField()), migrations.AlterField("Foo", "age", models.IntegerField()), migrations.RenameField("Bar", "size", "dimensions"), migrations.RemoveField("Foo", "age"), migrations.RenameModel("Foo", "Phou"), migrations.RemoveField("Bar", "dimensions"), migrations.RenameModel("Phou", "Fou"), migrations.DeleteModel("Fou"), ], [ migrations.CreateModel("Bar", [("width", models.IntegerField())]), ], ) def test_optimize_elidable_operation(self): elidable_operation = operations.base.Operation() elidable_operation.elidable = True self.assertOptimizesTo( [ elidable_operation, migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), elidable_operation, migrations.CreateModel("Bar", [("size", models.IntegerField())]), elidable_operation, migrations.RenameModel("Foo", "Phou"), migrations.DeleteModel("Bar"), elidable_operation, ], [ migrations.CreateModel( "Phou", [("name", models.CharField(max_length=255))] ), ], ) def test_rename_index(self): self.assertOptimizesTo( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_fields=("weight", "pink") ), migrations.RenameIndex( "Pony", new_name="new_name", old_name="mid_name" ), ], [ migrations.RenameIndex( "Pony", new_name="new_name", old_fields=("weight", "pink") ), ], ) self.assertOptimizesTo( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_name="old_name" ), migrations.RenameIndex( "Pony", new_name="new_name", old_name="mid_name" ), ], [migrations.RenameIndex("Pony", new_name="new_name", old_name="old_name")], ) self.assertDoesNotOptimize( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_name="old_name" ), migrations.RenameIndex( "Pony", new_name="new_name", old_fields=("weight", "pink") ), ] ) def test_add_remove_index(self): self.assertOptimizesTo( [ migrations.AddIndex( "Pony", models.Index( fields=["weight", "pink"], name="idx_pony_weight_pink" ), ), migrations.RemoveIndex("Pony", "idx_pony_weight_pink"), ], [], )
d74fab787e8af3ebbf7c393e272a3f8288438330cf0c6257b16c01e33402c191
import datetime import re import urllib.parse from unittest import mock from django.contrib.auth.forms import ( AdminPasswordChangeForm, AuthenticationForm, BaseUserCreationForm, PasswordChangeForm, PasswordResetForm, ReadOnlyPasswordHashField, ReadOnlyPasswordHashWidget, SetPasswordForm, UserChangeForm, UserCreationForm, ) from django.contrib.auth.models import User from django.contrib.auth.signals import user_login_failed from django.contrib.sites.models import Site from django.core import mail from django.core.exceptions import ValidationError from django.core.mail import EmailMultiAlternatives from django.forms import forms from django.forms.fields import CharField, Field, IntegerField from django.test import SimpleTestCase, TestCase, override_settings from django.urls import reverse from django.utils import translation from django.utils.text import capfirst from django.utils.translation import gettext as _ from .models.custom_user import ( CustomUser, CustomUserWithoutIsActiveField, ExtensionUser, ) from .models.with_custom_email_field import CustomEmailField from .models.with_integer_username import IntegerUsernameUser from .models.with_many_to_many import CustomUserWithM2M, Organization from .settings import AUTH_TEMPLATES class TestDataMixin: @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user( username="testclient", password="password", email="[email protected]" ) cls.u2 = User.objects.create_user( username="inactive", password="password", is_active=False ) cls.u3 = User.objects.create_user(username="staff", password="password") cls.u4 = User.objects.create(username="empty_password", password="") cls.u5 = User.objects.create(username="unmanageable_password", password="$") cls.u6 = User.objects.create(username="unknown_password", password="foo$bar") class BaseUserCreationFormTest(TestDataMixin, TestCase): def test_user_already_exists(self): data = { "username": "testclient", "password1": "test123", "password2": "test123", } form = BaseUserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form["username"].errors, [str(User._meta.get_field("username").error_messages["unique"])], ) def test_invalid_data(self): data = { "username": "jsmith!", "password1": "test123", "password2": "test123", } form = BaseUserCreationForm(data) self.assertFalse(form.is_valid()) validator = next( v for v in User._meta.get_field("username").validators if v.code == "invalid" ) self.assertEqual(form["username"].errors, [str(validator.message)]) def test_password_verification(self): # The verification password is incorrect. data = { "username": "jsmith", "password1": "test123", "password2": "test", } form = BaseUserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form["password2"].errors, [str(form.error_messages["password_mismatch"])] ) def test_both_passwords(self): # One (or both) passwords weren't given data = {"username": "jsmith"} form = BaseUserCreationForm(data) required_error = [str(Field.default_error_messages["required"])] self.assertFalse(form.is_valid()) self.assertEqual(form["password1"].errors, required_error) self.assertEqual(form["password2"].errors, required_error) data["password2"] = "test123" form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["password1"].errors, required_error) self.assertEqual(form["password2"].errors, []) @mock.patch("django.contrib.auth.password_validation.password_changed") def test_success(self, password_changed): # The success case. data = { "username": "[email protected]", "password1": "test123", "password2": "test123", } form = BaseUserCreationForm(data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) u = form.save() self.assertEqual(password_changed.call_count, 1) self.assertEqual(repr(u), "<User: [email protected]>") def test_unicode_username(self): data = { "username": "宝", "password1": "test123", "password2": "test123", } form = BaseUserCreationForm(data) self.assertTrue(form.is_valid()) u = form.save() self.assertEqual(u.username, "宝") def test_normalize_username(self): # The normalization happens in AbstractBaseUser.clean() and ModelForm # validation calls Model.clean(). ohm_username = "testΩ" # U+2126 OHM SIGN data = { "username": ohm_username, "password1": "pwd2", "password2": "pwd2", } form = BaseUserCreationForm(data) self.assertTrue(form.is_valid()) user = form.save() self.assertNotEqual(user.username, ohm_username) self.assertEqual(user.username, "testΩ") # U+03A9 GREEK CAPITAL LETTER OMEGA def test_duplicate_normalized_unicode(self): """ To prevent almost identical usernames, visually identical but differing by their unicode code points only, Unicode NFKC normalization should make appear them equal to Django. """ omega_username = "iamtheΩ" # U+03A9 GREEK CAPITAL LETTER OMEGA ohm_username = "iamtheΩ" # U+2126 OHM SIGN self.assertNotEqual(omega_username, ohm_username) User.objects.create_user(username=omega_username, password="pwd") data = { "username": ohm_username, "password1": "pwd2", "password2": "pwd2", } form = BaseUserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["username"], ["A user with that username already exists."] ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation.MinimumLengthValidator" ), "OPTIONS": { "min_length": 12, }, }, ] ) def test_validates_password(self): data = { "username": "testclient", "password1": "testclient", "password2": "testclient", } form = BaseUserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(len(form["password2"].errors), 2) self.assertIn( "The password is too similar to the username.", form["password2"].errors ) self.assertIn( "This password is too short. It must contain at least 12 characters.", form["password2"].errors, ) def test_custom_form(self): class CustomUserCreationForm(BaseUserCreationForm): class Meta(BaseUserCreationForm.Meta): model = ExtensionUser fields = UserCreationForm.Meta.fields + ("date_of_birth",) data = { "username": "testclient", "password1": "testclient", "password2": "testclient", "date_of_birth": "1988-02-24", } form = CustomUserCreationForm(data) self.assertTrue(form.is_valid()) def test_custom_form_with_different_username_field(self): class CustomUserCreationForm(BaseUserCreationForm): class Meta(BaseUserCreationForm.Meta): model = CustomUser fields = ("email", "date_of_birth") data = { "email": "[email protected]", "password1": "testclient", "password2": "testclient", "date_of_birth": "1988-02-24", } form = CustomUserCreationForm(data) self.assertTrue(form.is_valid()) def test_custom_form_hidden_username_field(self): class CustomUserCreationForm(BaseUserCreationForm): class Meta(BaseUserCreationForm.Meta): model = CustomUserWithoutIsActiveField fields = ("email",) # without USERNAME_FIELD data = { "email": "[email protected]", "password1": "testclient", "password2": "testclient", } form = CustomUserCreationForm(data) self.assertTrue(form.is_valid()) def test_custom_form_saves_many_to_many_field(self): class CustomUserCreationForm(BaseUserCreationForm): class Meta(BaseUserCreationForm.Meta): model = CustomUserWithM2M fields = UserCreationForm.Meta.fields + ("orgs",) organization = Organization.objects.create(name="organization 1") data = { "username": "[email protected]", "password1": "testclient", "password2": "testclient", "orgs": [str(organization.pk)], } form = CustomUserCreationForm(data) self.assertIs(form.is_valid(), True) user = form.save(commit=True) self.assertSequenceEqual(user.orgs.all(), [organization]) def test_password_whitespace_not_stripped(self): data = { "username": "testuser", "password1": " testpassword ", "password2": " testpassword ", } form = BaseUserCreationForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["password1"], data["password1"]) self.assertEqual(form.cleaned_data["password2"], data["password2"]) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ] ) def test_password_help_text(self): form = BaseUserCreationForm() self.assertEqual( form.fields["password1"].help_text, "<ul><li>" "Your password can’t be too similar to your other personal information." "</li></ul>", ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ] ) def test_user_create_form_validates_password_with_all_data(self): """ BaseUserCreationForm password validation uses all of the form's data. """ class CustomUserCreationForm(BaseUserCreationForm): class Meta(BaseUserCreationForm.Meta): model = User fields = ("username", "email", "first_name", "last_name") form = CustomUserCreationForm( { "username": "testuser", "password1": "testpassword", "password2": "testpassword", "first_name": "testpassword", "last_name": "lastname", } ) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["password2"], ["The password is too similar to the first name."], ) def test_username_field_autocapitalize_none(self): form = BaseUserCreationForm() self.assertEqual( form.fields["username"].widget.attrs.get("autocapitalize"), "none" ) def test_html_autocomplete_attributes(self): form = BaseUserCreationForm() tests = ( ("username", "username"), ("password1", "new-password"), ("password2", "new-password"), ) for field_name, autocomplete in tests: with self.subTest(field_name=field_name, autocomplete=autocomplete): self.assertEqual( form.fields[field_name].widget.attrs["autocomplete"], autocomplete ) class UserCreationFormTest(TestDataMixin, TestCase): def test_case_insensitive_username(self): data = { "username": "TeStClIeNt", "password1": "test123", "password2": "test123", } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form["username"].errors, ["A user with that username already exists."], ) @override_settings(AUTH_USER_MODEL="auth_tests.ExtensionUser") def test_case_insensitive_username_custom_user_and_error_message(self): class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = ExtensionUser fields = UserCreationForm.Meta.fields + ("date_of_birth",) error_messages = { "username": {"unique": "This username has already been taken."} } ExtensionUser.objects.create_user( username="testclient", password="password", email="[email protected]", date_of_birth=datetime.date(1984, 3, 5), ) data = { "username": "TeStClIeNt", "password1": "test123", "password2": "test123", "date_of_birth": "1980-01-01", } form = CustomUserCreationForm(data) self.assertIs(form.is_valid(), False) self.assertEqual( form["username"].errors, ["This username has already been taken."], ) # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.AllowAllUsersModelBackend"] ) class AuthenticationFormTest(TestDataMixin, TestCase): def test_invalid_username(self): # The user submits an invalid username. data = { "username": "jsmith_does_not_exist", "password": "test123", } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual( form.non_field_errors(), [ form.error_messages["invalid_login"] % {"username": User._meta.get_field("username").verbose_name} ], ) def test_inactive_user(self): # The user is inactive. data = { "username": "inactive", "password": "password", } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual( form.non_field_errors(), [str(form.error_messages["inactive"])] ) # Use an authentication backend that rejects inactive users. @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend"] ) def test_inactive_user_incorrect_password(self): """An invalid login doesn't leak the inactive status of a user.""" data = { "username": "inactive", "password": "incorrect", } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual( form.non_field_errors(), [ form.error_messages["invalid_login"] % {"username": User._meta.get_field("username").verbose_name} ], ) def test_login_failed(self): signal_calls = [] def signal_handler(**kwargs): signal_calls.append(kwargs) user_login_failed.connect(signal_handler) fake_request = object() try: form = AuthenticationForm( fake_request, { "username": "testclient", "password": "incorrect", }, ) self.assertFalse(form.is_valid()) self.assertIs(signal_calls[0]["request"], fake_request) finally: user_login_failed.disconnect(signal_handler) def test_inactive_user_i18n(self): with self.settings(USE_I18N=True), translation.override( "pt-br", deactivate=True ): # The user is inactive. data = { "username": "inactive", "password": "password", } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual( form.non_field_errors(), [str(form.error_messages["inactive"])] ) # Use an authentication backend that allows inactive users. @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.AllowAllUsersModelBackend" ] ) def test_custom_login_allowed_policy(self): # The user is inactive, but our custom form policy allows them to log in. data = { "username": "inactive", "password": "password", } class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm): def confirm_login_allowed(self, user): pass form = AuthenticationFormWithInactiveUsersOkay(None, data) self.assertTrue(form.is_valid()) # Raise a ValidationError in the form to disallow some logins according # to custom logic. class PickyAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if user.username == "inactive": raise ValidationError("This user is disallowed.") raise ValidationError("Sorry, nobody's allowed in.") form = PickyAuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), ["This user is disallowed."]) data = { "username": "testclient", "password": "password", } form = PickyAuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), ["Sorry, nobody's allowed in."]) def test_success(self): # The success case data = { "username": "testclient", "password": "password", } form = AuthenticationForm(None, data) self.assertTrue(form.is_valid()) self.assertEqual(form.non_field_errors(), []) def test_unicode_username(self): User.objects.create_user(username="Σαρα", password="pwd") data = { "username": "Σαρα", "password": "pwd", } form = AuthenticationForm(None, data) self.assertTrue(form.is_valid()) self.assertEqual(form.non_field_errors(), []) @override_settings(AUTH_USER_MODEL="auth_tests.CustomEmailField") def test_username_field_max_length_matches_user_model(self): self.assertEqual(CustomEmailField._meta.get_field("username").max_length, 255) data = { "username": "u" * 255, "password": "pwd", "email": "[email protected]", } CustomEmailField.objects.create_user(**data) form = AuthenticationForm(None, data) self.assertEqual(form.fields["username"].max_length, 255) self.assertEqual(form.fields["username"].widget.attrs.get("maxlength"), 255) self.assertEqual(form.errors, {}) @override_settings(AUTH_USER_MODEL="auth_tests.IntegerUsernameUser") def test_username_field_max_length_defaults_to_254(self): self.assertIsNone(IntegerUsernameUser._meta.get_field("username").max_length) data = { "username": "0123456", "password": "password", } IntegerUsernameUser.objects.create_user(**data) form = AuthenticationForm(None, data) self.assertEqual(form.fields["username"].max_length, 254) self.assertEqual(form.fields["username"].widget.attrs.get("maxlength"), 254) self.assertEqual(form.errors, {}) def test_username_field_label(self): class CustomAuthenticationForm(AuthenticationForm): username = CharField(label="Name", max_length=75) form = CustomAuthenticationForm() self.assertEqual(form["username"].label, "Name") def test_username_field_label_not_set(self): class CustomAuthenticationForm(AuthenticationForm): username = CharField() form = CustomAuthenticationForm() username_field = User._meta.get_field(User.USERNAME_FIELD) self.assertEqual( form.fields["username"].label, capfirst(username_field.verbose_name) ) def test_username_field_autocapitalize_none(self): form = AuthenticationForm() self.assertEqual( form.fields["username"].widget.attrs.get("autocapitalize"), "none" ) def test_username_field_label_empty_string(self): class CustomAuthenticationForm(AuthenticationForm): username = CharField(label="") form = CustomAuthenticationForm() self.assertEqual(form.fields["username"].label, "") def test_password_whitespace_not_stripped(self): data = { "username": "testuser", "password": " pass ", } form = AuthenticationForm(None, data) form.is_valid() # Not necessary to have valid credentails for the test. self.assertEqual(form.cleaned_data["password"], data["password"]) @override_settings(AUTH_USER_MODEL="auth_tests.IntegerUsernameUser") def test_integer_username(self): class CustomAuthenticationForm(AuthenticationForm): username = IntegerField() user = IntegerUsernameUser.objects.create_user(username=0, password="pwd") data = { "username": 0, "password": "pwd", } form = CustomAuthenticationForm(None, data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["username"], data["username"]) self.assertEqual(form.cleaned_data["password"], data["password"]) self.assertEqual(form.errors, {}) self.assertEqual(form.user_cache, user) def test_get_invalid_login_error(self): error = AuthenticationForm().get_invalid_login_error() self.assertIsInstance(error, ValidationError) self.assertEqual( error.message, "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive.", ) self.assertEqual(error.code, "invalid_login") self.assertEqual(error.params, {"username": "username"}) def test_html_autocomplete_attributes(self): form = AuthenticationForm() tests = ( ("username", "username"), ("password", "current-password"), ) for field_name, autocomplete in tests: with self.subTest(field_name=field_name, autocomplete=autocomplete): self.assertEqual( form.fields[field_name].widget.attrs["autocomplete"], autocomplete ) def test_no_password(self): data = {"username": "username"} form = AuthenticationForm(None, data) self.assertIs(form.is_valid(), False) self.assertEqual( form["password"].errors, [Field.default_error_messages["required"]] ) class SetPasswordFormTest(TestDataMixin, TestCase): def test_password_verification(self): # The two new passwords do not match. user = User.objects.get(username="testclient") data = { "new_password1": "abc123", "new_password2": "abc", } form = SetPasswordForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual( form["new_password2"].errors, [str(form.error_messages["password_mismatch"])], ) @mock.patch("django.contrib.auth.password_validation.password_changed") def test_success(self, password_changed): user = User.objects.get(username="testclient") data = { "new_password1": "abc123", "new_password2": "abc123", } form = SetPasswordForm(user, data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) form.save() self.assertEqual(password_changed.call_count, 1) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation.MinimumLengthValidator" ), "OPTIONS": { "min_length": 12, }, }, ] ) def test_validates_password(self): user = User.objects.get(username="testclient") data = { "new_password1": "testclient", "new_password2": "testclient", } form = SetPasswordForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual(len(form["new_password2"].errors), 2) self.assertIn( "The password is too similar to the username.", form["new_password2"].errors ) self.assertIn( "This password is too short. It must contain at least 12 characters.", form["new_password2"].errors, ) def test_no_password(self): user = User.objects.get(username="testclient") data = {"new_password1": "new-password"} form = SetPasswordForm(user, data) self.assertIs(form.is_valid(), False) self.assertEqual( form["new_password2"].errors, [Field.default_error_messages["required"]] ) form = SetPasswordForm(user, {}) self.assertIs(form.is_valid(), False) self.assertEqual( form["new_password1"].errors, [Field.default_error_messages["required"]] ) self.assertEqual( form["new_password2"].errors, [Field.default_error_messages["required"]] ) def test_password_whitespace_not_stripped(self): user = User.objects.get(username="testclient") data = { "new_password1": " password ", "new_password2": " password ", } form = SetPasswordForm(user, data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["new_password1"], data["new_password1"]) self.assertEqual(form.cleaned_data["new_password2"], data["new_password2"]) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation.MinimumLengthValidator" ), "OPTIONS": { "min_length": 12, }, }, ] ) def test_help_text_translation(self): french_help_texts = [ "Votre mot de passe ne peut pas trop ressembler à vos autres informations " "personnelles.", "Votre mot de passe doit contenir au minimum 12 caractères.", ] form = SetPasswordForm(self.u1) with translation.override("fr"): html = form.as_p() for french_text in french_help_texts: self.assertIn(french_text, html) def test_html_autocomplete_attributes(self): form = SetPasswordForm(self.u1) tests = ( ("new_password1", "new-password"), ("new_password2", "new-password"), ) for field_name, autocomplete in tests: with self.subTest(field_name=field_name, autocomplete=autocomplete): self.assertEqual( form.fields[field_name].widget.attrs["autocomplete"], autocomplete ) class PasswordChangeFormTest(TestDataMixin, TestCase): def test_incorrect_password(self): user = User.objects.get(username="testclient") data = { "old_password": "test", "new_password1": "abc123", "new_password2": "abc123", } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual( form["old_password"].errors, [str(form.error_messages["password_incorrect"])], ) def test_password_verification(self): # The two new passwords do not match. user = User.objects.get(username="testclient") data = { "old_password": "password", "new_password1": "abc123", "new_password2": "abc", } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual( form["new_password2"].errors, [str(form.error_messages["password_mismatch"])], ) @mock.patch("django.contrib.auth.password_validation.password_changed") def test_success(self, password_changed): # The success case. user = User.objects.get(username="testclient") data = { "old_password": "password", "new_password1": "abc123", "new_password2": "abc123", } form = PasswordChangeForm(user, data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) form.save() self.assertEqual(password_changed.call_count, 1) def test_field_order(self): # Regression test - check the order of fields: user = User.objects.get(username="testclient") self.assertEqual( list(PasswordChangeForm(user, {}).fields), ["old_password", "new_password1", "new_password2"], ) def test_password_whitespace_not_stripped(self): user = User.objects.get(username="testclient") user.set_password(" oldpassword ") data = { "old_password": " oldpassword ", "new_password1": " pass ", "new_password2": " pass ", } form = PasswordChangeForm(user, data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["old_password"], data["old_password"]) self.assertEqual(form.cleaned_data["new_password1"], data["new_password1"]) self.assertEqual(form.cleaned_data["new_password2"], data["new_password2"]) def test_html_autocomplete_attributes(self): user = User.objects.get(username="testclient") form = PasswordChangeForm(user) self.assertEqual( form.fields["old_password"].widget.attrs["autocomplete"], "current-password" ) class UserChangeFormTest(TestDataMixin, TestCase): def test_username_validity(self): user = User.objects.get(username="testclient") data = {"username": "not valid"} form = UserChangeForm(data, instance=user) self.assertFalse(form.is_valid()) validator = next( v for v in User._meta.get_field("username").validators if v.code == "invalid" ) self.assertEqual(form["username"].errors, [str(validator.message)]) def test_bug_14242(self): # A regression test, introduce by adding an optimization for the # UserChangeForm. class MyUserForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[ "groups" ].help_text = "These groups give users different permissions" class Meta(UserChangeForm.Meta): fields = ("groups",) # Just check we can create it MyUserForm({}) def test_unusable_password(self): user = User.objects.get(username="empty_password") user.set_unusable_password() user.save() form = UserChangeForm(instance=user) self.assertIn(_("No password set."), form.as_table()) def test_bug_17944_empty_password(self): user = User.objects.get(username="empty_password") form = UserChangeForm(instance=user) self.assertIn(_("No password set."), form.as_table()) def test_bug_17944_unmanageable_password(self): user = User.objects.get(username="unmanageable_password") form = UserChangeForm(instance=user) self.assertIn( _("Invalid password format or unknown hashing algorithm."), form.as_table() ) def test_bug_17944_unknown_password_algorithm(self): user = User.objects.get(username="unknown_password") form = UserChangeForm(instance=user) self.assertIn( _("Invalid password format or unknown hashing algorithm."), form.as_table() ) def test_bug_19133(self): "The change form does not return the password value" # Use the form to construct the POST data user = User.objects.get(username="testclient") form_for_data = UserChangeForm(instance=user) post_data = form_for_data.initial # The password field should be readonly, so anything # posted here should be ignored; the form will be # valid, and give back the 'initial' value for the # password field. post_data["password"] = "new password" form = UserChangeForm(instance=user, data=post_data) self.assertTrue(form.is_valid()) # original hashed password contains $ self.assertIn("$", form.cleaned_data["password"]) def test_bug_19349_bound_password_field(self): user = User.objects.get(username="testclient") form = UserChangeForm(data={}, instance=user) # When rendering the bound password field, # ReadOnlyPasswordHashWidget needs the initial # value to render correctly self.assertEqual(form.initial["password"], form["password"].value()) @override_settings(ROOT_URLCONF="auth_tests.urls_admin") def test_link_to_password_reset_in_helptext_via_to_field(self): user = User.objects.get(username="testclient") form = UserChangeForm(data={}, instance=user) password_help_text = form.fields["password"].help_text matches = re.search('<a href="(.*?)">', password_help_text) # URL to UserChangeForm in admin via to_field (instead of pk). admin_user_change_url = reverse( f"admin:{user._meta.app_label}_{user._meta.model_name}_change", args=(user.username,), ) joined_url = urllib.parse.urljoin(admin_user_change_url, matches.group(1)) pw_change_url = reverse( f"admin:{user._meta.app_label}_{user._meta.model_name}_password_change", args=(user.pk,), ) self.assertEqual(joined_url, pw_change_url) def test_custom_form(self): class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = ExtensionUser fields = ( "username", "password", "date_of_birth", ) user = User.objects.get(username="testclient") data = { "username": "testclient", "password": "testclient", "date_of_birth": "1998-02-24", } form = CustomUserChangeForm(data, instance=user) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.cleaned_data["username"], "testclient") self.assertEqual(form.cleaned_data["date_of_birth"], datetime.date(1998, 2, 24)) def test_password_excluded(self): class UserChangeFormWithoutPassword(UserChangeForm): password = None class Meta: model = User exclude = ["password"] form = UserChangeFormWithoutPassword() self.assertNotIn("password", form.fields) def test_username_field_autocapitalize_none(self): form = UserChangeForm() self.assertEqual( form.fields["username"].widget.attrs.get("autocapitalize"), "none" ) @override_settings(TEMPLATES=AUTH_TEMPLATES) class PasswordResetFormTest(TestDataMixin, TestCase): @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() def create_dummy_user(self): """ Create a user and return a tuple (user_object, username, email). """ username = "jsmith" email = "[email protected]" user = User.objects.create_user(username, email, "test123") return (user, username, email) def test_invalid_email(self): data = {"email": "not valid"} form = PasswordResetForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form["email"].errors, [_("Enter a valid email address.")]) def test_user_email_unicode_collision(self): User.objects.create_user("mike123", "[email protected]", "test123") User.objects.create_user("mike456", "mı[email protected]", "test123") data = {"email": "mı[email protected]"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["mı[email protected]"]) def test_user_email_domain_unicode_collision(self): User.objects.create_user("mike123", "[email protected]", "test123") User.objects.create_user("mike456", "mike@ıxample.org", "test123") data = {"email": "mike@ıxample.org"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["mike@ıxample.org"]) def test_user_email_unicode_collision_nonexistent(self): User.objects.create_user("mike123", "[email protected]", "test123") data = {"email": "mı[email protected]"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) def test_user_email_domain_unicode_collision_nonexistent(self): User.objects.create_user("mike123", "[email protected]", "test123") data = {"email": "mike@ıxample.org"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would expose information about registered users. """ data = {"email": "[email protected]"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) self.assertEqual(len(mail.outbox), 0) def test_cleaned_data(self): (user, username, email) = self.create_dummy_user() data = {"email": email} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) form.save(domain_override="example.com") self.assertEqual(form.cleaned_data["email"], email) self.assertEqual(len(mail.outbox), 1) def test_custom_email_subject(self): data = {"email": "[email protected]"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) # Since we're not providing a request object, we must provide a # domain_override to prevent the save operation from failing in the # potential case where contrib.sites is not installed. Refs #16412. form.save(domain_override="example.com") self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Custom password reset on example.com") def test_custom_email_constructor(self): data = {"email": "[email protected]"} class CustomEmailPasswordResetForm(PasswordResetForm): def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): EmailMultiAlternatives( "Forgot your password?", "Sorry to hear you forgot your password.", None, [to_email], ["[email protected]"], headers={"Reply-To": "[email protected]"}, alternatives=[ ("Really sorry to hear you forgot your password.", "text/html") ], ).send() form = CustomEmailPasswordResetForm(data) self.assertTrue(form.is_valid()) # Since we're not providing a request object, we must provide a # domain_override to prevent the save operation from failing in the # potential case where contrib.sites is not installed. Refs #16412. form.save(domain_override="example.com") self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Forgot your password?") self.assertEqual(mail.outbox[0].bcc, ["[email protected]"]) self.assertEqual(mail.outbox[0].content_subtype, "plain") def test_preserve_username_case(self): """ Preserve the case of the user name (before the @ in the email address) when creating a user (#5605). """ user = User.objects.create_user("forms_test2", "[email protected]", "test") self.assertEqual(user.email, "[email protected]") user = User.objects.create_user("forms_test3", "tesT", "test") self.assertEqual(user.email, "tesT") def test_inactive_user(self): """ Inactive user cannot receive password reset email. """ (user, username, email) = self.create_dummy_user() user.is_active = False user.save() form = PasswordResetForm({"email": email}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) def test_unusable_password(self): user = User.objects.create_user("testuser", "[email protected]", "test") data = {"email": "[email protected]"} form = PasswordResetForm(data) self.assertTrue(form.is_valid()) user.set_unusable_password() user.save() form = PasswordResetForm(data) # The form itself is valid, but no email is sent self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) def test_save_plaintext_email(self): """ Test the PasswordResetForm.save() method with no html_email_template_name parameter passed in. Test to ensure original behavior is unchanged after the parameter was added. """ (user, username, email) = self.create_dummy_user() form = PasswordResetForm({"email": email}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0].message() self.assertFalse(message.is_multipart()) self.assertEqual(message.get_content_type(), "text/plain") self.assertEqual(message.get("subject"), "Custom password reset on example.com") self.assertEqual(len(mail.outbox[0].alternatives), 0) self.assertEqual(message.get_all("to"), [email]) self.assertTrue( re.match(r"^http://example.com/reset/[\w+/-]", message.get_payload()) ) def test_save_html_email_template_name(self): """ Test the PasswordResetForm.save() method with html_email_template_name parameter specified. Test to ensure that a multipart email is sent with both text/plain and text/html parts. """ (user, username, email) = self.create_dummy_user() form = PasswordResetForm({"email": email}) self.assertTrue(form.is_valid()) form.save( html_email_template_name="registration/html_password_reset_email.html" ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox[0].alternatives), 1) message = mail.outbox[0].message() self.assertEqual(message.get("subject"), "Custom password reset on example.com") self.assertEqual(len(message.get_payload()), 2) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") self.assertEqual(message.get_payload(1).get_content_type(), "text/html") self.assertEqual(message.get_all("to"), [email]) self.assertTrue( re.match( r"^http://example.com/reset/[\w/-]+", message.get_payload(0).get_payload(), ) ) self.assertTrue( re.match( r'^<html><a href="http://example.com/reset/[\w/-]+/">Link</a></html>$', message.get_payload(1).get_payload(), ) ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomEmailField") def test_custom_email_field(self): email = "[email protected]" CustomEmailField.objects.create_user("test name", "test password", email) form = PasswordResetForm({"email": email}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.cleaned_data["email"], email) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [email]) def test_html_autocomplete_attributes(self): form = PasswordResetForm() self.assertEqual(form.fields["email"].widget.attrs["autocomplete"], "email") class ReadOnlyPasswordHashTest(SimpleTestCase): def test_bug_19349_render_with_none_value(self): # Rendering the widget with value set to None # mustn't raise an exception. widget = ReadOnlyPasswordHashWidget() html = widget.render(name="password", value=None, attrs={}) self.assertIn(_("No password set."), html) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.PBKDF2PasswordHasher"] ) def test_render(self): widget = ReadOnlyPasswordHashWidget() value = ( "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5u" "dm0=" ) self.assertHTMLEqual( widget.render("name", value, {"id": "id_password"}), '<div id="id_password">' " <strong>algorithm</strong>: <bdi>pbkdf2_sha256</bdi>" " <strong>iterations</strong>: <bdi>100000</bdi>" " <strong>salt</strong>: <bdi>a6Pucb******</bdi>" " <strong>hash</strong>: " " <bdi>WmCkn9**************************************</bdi>" "</div>", ) def test_readonly_field_has_changed(self): field = ReadOnlyPasswordHashField() self.assertIs(field.disabled, True) self.assertFalse(field.has_changed("aaa", "bbb")) def test_label(self): """ ReadOnlyPasswordHashWidget doesn't contain a for attribute in the <label> because it doesn't have any labelable elements. """ class TestForm(forms.Form): hash_field = ReadOnlyPasswordHashField() bound_field = TestForm()["hash_field"] self.assertIsNone(bound_field.field.widget.id_for_label("id")) self.assertEqual(bound_field.label_tag(), "<label>Hash field:</label>") class AdminPasswordChangeFormTest(TestDataMixin, TestCase): @mock.patch("django.contrib.auth.password_validation.password_changed") def test_success(self, password_changed): user = User.objects.get(username="testclient") data = { "password1": "test123", "password2": "test123", } form = AdminPasswordChangeForm(user, data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) form.save() self.assertEqual(password_changed.call_count, 1) self.assertEqual(form.changed_data, ["password"]) def test_password_whitespace_not_stripped(self): user = User.objects.get(username="testclient") data = { "password1": " pass ", "password2": " pass ", } form = AdminPasswordChangeForm(user, data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["password1"], data["password1"]) self.assertEqual(form.cleaned_data["password2"], data["password2"]) self.assertEqual(form.changed_data, ["password"]) def test_non_matching_passwords(self): user = User.objects.get(username="testclient") data = {"password1": "password1", "password2": "password2"} form = AdminPasswordChangeForm(user, data) self.assertEqual( form.errors["password2"], [form.error_messages["password_mismatch"]] ) self.assertEqual(form.changed_data, ["password"]) def test_missing_passwords(self): user = User.objects.get(username="testclient") data = {"password1": "", "password2": ""} form = AdminPasswordChangeForm(user, data) required_error = [Field.default_error_messages["required"]] self.assertEqual(form.errors["password1"], required_error) self.assertEqual(form.errors["password2"], required_error) self.assertEqual(form.changed_data, []) def test_one_password(self): user = User.objects.get(username="testclient") form1 = AdminPasswordChangeForm(user, {"password1": "", "password2": "test"}) required_error = [Field.default_error_messages["required"]] self.assertEqual(form1.errors["password1"], required_error) self.assertNotIn("password2", form1.errors) self.assertEqual(form1.changed_data, []) form2 = AdminPasswordChangeForm(user, {"password1": "test", "password2": ""}) self.assertEqual(form2.errors["password2"], required_error) self.assertNotIn("password1", form2.errors) self.assertEqual(form2.changed_data, []) def test_html_autocomplete_attributes(self): user = User.objects.get(username="testclient") form = AdminPasswordChangeForm(user) tests = ( ("password1", "new-password"), ("password2", "new-password"), ) for field_name, autocomplete in tests: with self.subTest(field_name=field_name, autocomplete=autocomplete): self.assertEqual( form.fields[field_name].widget.attrs["autocomplete"], autocomplete )
5b5b442f916797767f6492d31533cba81d7c19561cfd7cdad72f2e3d7982b02e
import datetime import math import re from decimal import Decimal from django.core.exceptions import FieldError from django.db import connection from django.db.models import ( Avg, Case, Count, DateField, DateTimeField, DecimalField, DurationField, Exists, F, FloatField, IntegerField, Max, Min, OuterRef, Q, StdDev, Subquery, Sum, TimeField, Value, Variance, When, ) from django.db.models.expressions import Func, RawSQL from django.db.models.functions import ( Cast, Coalesce, Greatest, Least, Lower, Mod, Now, Pi, TruncDate, TruncHour, ) from django.test import TestCase from django.test.testcases import skipUnlessDBFeature from django.test.utils import Approximate, CaptureQueriesContext from django.utils import timezone from .models import Author, Book, Publisher, Store class NowUTC(Now): template = "CURRENT_TIMESTAMP" output_field = DateTimeField() def as_sql(self, compiler, connection, **extra_context): if connection.features.test_now_utc_template: extra_context["template"] = connection.features.test_now_utc_template return super().as_sql(compiler, connection, **extra_context) class AggregateTestCase(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="Brad Dayley", age=45) cls.a4 = Author.objects.create(name="James Bennett", age=29) cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37) cls.a6 = Author.objects.create(name="Paul Bissex", age=29) cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25) cls.a8 = Author.objects.create(name="Peter Norvig", age=57) cls.a9 = Author.objects.create(name="Stuart Russell", age=46) cls.a1.friends.add(cls.a2, cls.a4) cls.a2.friends.add(cls.a1, cls.a7) cls.a4.friends.add(cls.a1) cls.a5.friends.add(cls.a6, cls.a7) cls.a6.friends.add(cls.a5, cls.a7) cls.a7.friends.add(cls.a2, cls.a5, cls.a6) cls.a8.friends.add(cls.a9) cls.a9.friends.add(cls.a8) cls.p1 = Publisher.objects.create( name="Apress", num_awards=3, duration=datetime.timedelta(days=1) ) cls.p2 = Publisher.objects.create( name="Sams", num_awards=1, duration=datetime.timedelta(days=2) ) cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7) cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9) cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a3, publisher=cls.p2, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a4, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.b4 = Book.objects.create( isbn="013235613", name="Python Web Development with Django", pages=350, rating=4.0, price=Decimal("29.69"), contact=cls.a5, publisher=cls.p3, pubdate=datetime.date(2008, 11, 3), ) cls.b5 = Book.objects.create( isbn="013790395", name="Artificial Intelligence: A Modern Approach", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a8, publisher=cls.p3, pubdate=datetime.date(1995, 1, 15), ) cls.b6 = Book.objects.create( isbn="155860191", name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a8, publisher=cls.p4, pubdate=datetime.date(1991, 10, 15), ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4) cls.b4.authors.add(cls.a5, cls.a6, cls.a7) cls.b5.authors.add(cls.a8, cls.a9) cls.b6.authors.add(cls.a8) s1 = Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) s2 = Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) s3 = Store.objects.create( name="Mamma and Pappa's Books", original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14), friday_night_closing=datetime.time(21, 30), ) s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6) s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6) s3.books.add(cls.b3, cls.b4, cls.b6) def test_empty_aggregate(self): self.assertEqual(Author.objects.aggregate(), {}) def test_aggregate_in_order_by(self): msg = ( "Using an aggregate in order_by() without also including it in " "annotate() is not allowed: Avg(F(book__rating)" ) with self.assertRaisesMessage(FieldError, msg): Author.objects.values("age").order_by(Avg("book__rating")) def test_single_aggregate(self): vals = Author.objects.aggregate(Avg("age")) self.assertEqual(vals, {"age__avg": Approximate(37.4, places=1)}) def test_multiple_aggregates(self): vals = Author.objects.aggregate(Sum("age"), Avg("age")) self.assertEqual( vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)} ) def test_filter_aggregate(self): vals = Author.objects.filter(age__gt=29).aggregate(Sum("age")) self.assertEqual(vals, {"age__sum": 254}) def test_related_aggregate(self): vals = Author.objects.aggregate(Avg("friends__age")) self.assertEqual(vals, {"friends__age__avg": Approximate(34.07, places=2)}) vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age")) self.assertEqual(vals, {"authors__age__avg": Approximate(38.2857, places=2)}) vals = Author.objects.filter(name__contains="a").aggregate(Avg("book__rating")) self.assertEqual(vals, {"book__rating__avg": 4.0}) vals = Book.objects.aggregate(Sum("publisher__num_awards")) self.assertEqual(vals, {"publisher__num_awards__sum": 30}) vals = Publisher.objects.aggregate(Sum("book__price")) self.assertEqual(vals, {"book__price__sum": Decimal("270.27")}) def test_aggregate_multi_join(self): vals = Store.objects.aggregate(Max("books__authors__age")) self.assertEqual(vals, {"books__authors__age__max": 57}) vals = Author.objects.aggregate(Min("book__publisher__num_awards")) self.assertEqual(vals, {"book__publisher__num_awards__min": 1}) def test_aggregate_alias(self): vals = Store.objects.filter(name="Amazon.com").aggregate( amazon_mean=Avg("books__rating") ) self.assertEqual(vals, {"amazon_mean": Approximate(4.08, places=2)}) def test_aggregate_transform(self): vals = Store.objects.aggregate(min_month=Min("original_opening__month")) self.assertEqual(vals, {"min_month": 3}) def test_aggregate_join_transform(self): vals = Publisher.objects.aggregate(min_year=Min("book__pubdate__year")) self.assertEqual(vals, {"min_year": 1991}) def test_annotate_basic(self): self.assertQuerySetEqual( Book.objects.annotate().order_by("pk"), [ "The Definitive Guide to Django: Web Development Done Right", "Sams Teach Yourself Django in 24 Hours", "Practical Django Projects", "Python Web Development with Django", "Artificial Intelligence: A Modern Approach", "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", ], lambda b: b.name, ) books = Book.objects.annotate(mean_age=Avg("authors__age")) b = books.get(pk=self.b1.pk) self.assertEqual( b.name, "The Definitive Guide to Django: Web Development Done Right" ) self.assertEqual(b.mean_age, 34.5) def test_annotate_defer(self): qs = ( Book.objects.annotate(page_sum=Sum("pages")) .defer("name") .filter(pk=self.b1.pk) ) rows = [ ( self.b1.id, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right", ) ] self.assertQuerySetEqual( qs.order_by("pk"), rows, lambda r: (r.id, r.isbn, r.page_sum, r.name) ) def test_annotate_defer_select_related(self): qs = ( Book.objects.select_related("contact") .annotate(page_sum=Sum("pages")) .defer("name") .filter(pk=self.b1.pk) ) rows = [ ( self.b1.id, "159059725", 447, "Adrian Holovaty", "The Definitive Guide to Django: Web Development Done Right", ) ] self.assertQuerySetEqual( qs.order_by("pk"), rows, lambda r: (r.id, r.isbn, r.page_sum, r.contact.name, r.name), ) def test_annotate_m2m(self): books = ( Book.objects.filter(rating__lt=4.5) .annotate(Avg("authors__age")) .order_by("name") ) self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 51.5), ("Practical Django Projects", 29.0), ("Python Web Development with Django", Approximate(30.3, places=1)), ("Sams Teach Yourself Django in 24 Hours", 45.0), ], lambda b: (b.name, b.authors__age__avg), ) books = Book.objects.annotate(num_authors=Count("authors")).order_by("name") self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 2), ( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", 1, ), ("Practical Django Projects", 1), ("Python Web Development with Django", 3), ("Sams Teach Yourself Django in 24 Hours", 1), ("The Definitive Guide to Django: Web Development Done Right", 2), ], lambda b: (b.name, b.num_authors), ) def test_backwards_m2m_annotate(self): authors = ( Author.objects.filter(name__contains="a") .annotate(Avg("book__rating")) .order_by("name") ) self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 4.5), ("Brad Dayley", 3.0), ("Jacob Kaplan-Moss", 4.5), ("James Bennett", 4.0), ("Paul Bissex", 4.0), ("Stuart Russell", 4.0), ], lambda a: (a.name, a.book__rating__avg), ) authors = Author.objects.annotate(num_books=Count("book")).order_by("name") self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 1), ("Brad Dayley", 1), ("Jacob Kaplan-Moss", 1), ("James Bennett", 1), ("Jeffrey Forcier", 1), ("Paul Bissex", 1), ("Peter Norvig", 2), ("Stuart Russell", 1), ("Wesley J. Chun", 1), ], lambda a: (a.name, a.num_books), ) def test_reverse_fkey_annotate(self): books = Book.objects.annotate(Sum("publisher__num_awards")).order_by("name") self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 7), ( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", 9, ), ("Practical Django Projects", 3), ("Python Web Development with Django", 7), ("Sams Teach Yourself Django in 24 Hours", 1), ("The Definitive Guide to Django: Web Development Done Right", 3), ], lambda b: (b.name, b.publisher__num_awards__sum), ) publishers = Publisher.objects.annotate(Sum("book__price")).order_by("name") self.assertQuerySetEqual( publishers, [ ("Apress", Decimal("59.69")), ("Jonno's House of Books", None), ("Morgan Kaufmann", Decimal("75.00")), ("Prentice Hall", Decimal("112.49")), ("Sams", Decimal("23.09")), ], lambda p: (p.name, p.book__price__sum), ) def test_annotate_values(self): books = list( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values() ) self.assertEqual( books, [ { "contact_id": self.a1.id, "id": self.b1.id, "isbn": "159059725", "mean_age": 34.5, "name": ( "The Definitive Guide to Django: Web Development Done Right" ), "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": self.p1.id, "rating": 4.5, } ], ) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values("pk", "isbn", "mean_age") ) self.assertEqual( list(books), [ { "pk": self.b1.pk, "isbn": "159059725", "mean_age": 34.5, } ], ) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values("name") ) self.assertEqual( list(books), [{"name": "The Definitive Guide to Django: Web Development Done Right"}], ) books = ( Book.objects.filter(pk=self.b1.pk) .values() .annotate(mean_age=Avg("authors__age")) ) self.assertEqual( list(books), [ { "contact_id": self.a1.id, "id": self.b1.id, "isbn": "159059725", "mean_age": 34.5, "name": ( "The Definitive Guide to Django: Web Development Done Right" ), "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": self.p1.id, "rating": 4.5, } ], ) books = ( Book.objects.values("rating") .annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age")) .order_by("rating") ) self.assertEqual( list(books), [ { "rating": 3.0, "n_authors": 1, "mean_age": 45.0, }, { "rating": 4.0, "n_authors": 6, "mean_age": Approximate(37.16, places=1), }, { "rating": 4.5, "n_authors": 2, "mean_age": 34.5, }, { "rating": 5.0, "n_authors": 1, "mean_age": 57.0, }, ], ) authors = Author.objects.annotate(Avg("friends__age")).order_by("name") self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 32.0), ("Brad Dayley", None), ("Jacob Kaplan-Moss", 29.5), ("James Bennett", 34.0), ("Jeffrey Forcier", 27.0), ("Paul Bissex", 31.0), ("Peter Norvig", 46.0), ("Stuart Russell", 57.0), ("Wesley J. Chun", Approximate(33.66, places=1)), ], lambda a: (a.name, a.friends__age__avg), ) def test_count(self): vals = Book.objects.aggregate(Count("rating")) self.assertEqual(vals, {"rating__count": 6}) def test_count_star(self): with self.assertNumQueries(1) as ctx: Book.objects.aggregate(n=Count("*")) sql = ctx.captured_queries[0]["sql"] self.assertIn("SELECT COUNT(*) ", sql) def test_count_distinct_expression(self): aggs = Book.objects.aggregate( distinct_ratings=Count( Case(When(pages__gt=300, then="rating")), distinct=True ), ) self.assertEqual(aggs["distinct_ratings"], 4) def test_distinct_on_aggregate(self): for aggregate, expected_result in ( (Avg, 4.125), (Count, 4), (Sum, 16.5), ): with self.subTest(aggregate=aggregate.__name__): books = Book.objects.aggregate( ratings=aggregate("rating", distinct=True) ) self.assertEqual(books["ratings"], expected_result) def test_non_grouped_annotation_not_in_group_by(self): """ An annotation not included in values() before an aggregate should be excluded from the group by clause. """ qs = ( Book.objects.annotate(xprice=F("price")) .filter(rating=4.0) .values("rating") .annotate(count=Count("publisher_id", distinct=True)) .values("count", "rating") .order_by("count") ) self.assertEqual(list(qs), [{"rating": 4.0, "count": 2}]) def test_grouped_annotation_in_group_by(self): """ An annotation included in values() before an aggregate should be included in the group by clause. """ qs = ( Book.objects.annotate(xprice=F("price")) .filter(rating=4.0) .values("rating", "xprice") .annotate(count=Count("publisher_id", distinct=True)) .values("count", "rating") .order_by("count") ) self.assertEqual( list(qs), [ {"rating": 4.0, "count": 1}, {"rating": 4.0, "count": 2}, ], ) def test_fkey_aggregate(self): explicit = list(Author.objects.annotate(Count("book__id"))) implicit = list(Author.objects.annotate(Count("book"))) self.assertCountEqual(explicit, implicit) def test_annotate_ordering(self): books = ( Book.objects.values("rating") .annotate(oldest=Max("authors__age")) .order_by("oldest", "rating") ) self.assertEqual( list(books), [ {"rating": 4.5, "oldest": 35}, {"rating": 3.0, "oldest": 45}, {"rating": 4.0, "oldest": 57}, {"rating": 5.0, "oldest": 57}, ], ) books = ( Book.objects.values("rating") .annotate(oldest=Max("authors__age")) .order_by("-oldest", "-rating") ) self.assertEqual( list(books), [ {"rating": 5.0, "oldest": 57}, {"rating": 4.0, "oldest": 57}, {"rating": 3.0, "oldest": 45}, {"rating": 4.5, "oldest": 35}, ], ) def test_aggregate_annotation(self): vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate( Avg("num_authors") ) self.assertEqual(vals, {"num_authors__avg": Approximate(1.66, places=1)}) def test_avg_duration_field(self): # Explicit `output_field`. self.assertEqual( Publisher.objects.aggregate(Avg("duration", output_field=DurationField())), {"duration__avg": datetime.timedelta(days=1, hours=12)}, ) # Implicit `output_field`. self.assertEqual( Publisher.objects.aggregate(Avg("duration")), {"duration__avg": datetime.timedelta(days=1, hours=12)}, ) def test_sum_duration_field(self): self.assertEqual( Publisher.objects.aggregate(Sum("duration", output_field=DurationField())), {"duration__sum": datetime.timedelta(days=3)}, ) def test_sum_distinct_aggregate(self): """ Sum on a distinct() QuerySet should aggregate only the distinct items. """ authors = Author.objects.filter(book__in=[self.b5, self.b6]) self.assertEqual(authors.count(), 3) distinct_authors = authors.distinct() self.assertEqual(distinct_authors.count(), 2) # Selected author ages are 57 and 46 age_sum = distinct_authors.aggregate(Sum("age")) self.assertEqual(age_sum["age__sum"], 103) def test_filtering(self): p = Publisher.objects.create(name="Expensive Publisher", num_awards=0) Book.objects.create( name="ExpensiveBook1", pages=1, isbn="111", rating=3.5, price=Decimal("1000"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 1), ) Book.objects.create( name="ExpensiveBook2", pages=1, isbn="222", rating=4.0, price=Decimal("1000"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 2), ) Book.objects.create( name="ExpensiveBook3", pages=1, isbn="333", rating=4.5, price=Decimal("35"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 3), ) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall", "Expensive Publisher"], lambda p: p.name, ) publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).order_by( "pk" ) self.assertQuerySetEqual( publishers, [ "Apress", "Apress", "Sams", "Prentice Hall", "Expensive Publisher", ], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1, book__price__lt=Decimal("40.0")) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall", "Expensive Publisher"], lambda p: p.name, ) publishers = ( Publisher.objects.filter(book__price__lt=Decimal("40.0")) .annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual(publishers, ["Apress"], lambda p: p.name) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__range=[1, 3]) .order_by("pk") ) self.assertQuerySetEqual( publishers, [ "Apress", "Sams", "Prentice Hall", "Morgan Kaufmann", "Expensive Publisher", ], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__range=[1, 2]) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Sams", "Prentice Hall", "Morgan Kaufmann"], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__in=[1, 3]) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Sams", "Morgan Kaufmann", "Expensive Publisher"], lambda p: p.name, ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter( num_books__isnull=True ) self.assertEqual(len(publishers), 0) def test_annotation(self): vals = Author.objects.filter(pk=self.a1.pk).aggregate(Count("friends__id")) self.assertEqual(vals, {"friends__id__count": 2}) books = ( Book.objects.annotate(num_authors=Count("authors__name")) .filter(num_authors__exact=2) .order_by("pk") ) self.assertQuerySetEqual( books, [ "The Definitive Guide to Django: Web Development Done Right", "Artificial Intelligence: A Modern Approach", ], lambda b: b.name, ) authors = ( Author.objects.annotate(num_friends=Count("friends__id", distinct=True)) .filter(num_friends=0) .order_by("pk") ) self.assertQuerySetEqual(authors, ["Brad Dayley"], lambda a: a.name) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall"], lambda p: p.name ) publishers = ( Publisher.objects.filter(book__price__lt=Decimal("40.0")) .annotate(num_books=Count("book__id")) .filter(num_books__gt=1) ) self.assertQuerySetEqual(publishers, ["Apress"], lambda p: p.name) books = Book.objects.annotate(num_authors=Count("authors__id")).filter( authors__name__contains="Norvig", num_authors__gt=1 ) self.assertQuerySetEqual( books, ["Artificial Intelligence: A Modern Approach"], lambda b: b.name ) def test_more_aggregation(self): a = Author.objects.get(name__contains="Norvig") b = Book.objects.get(name__contains="Done Right") b.authors.add(a) b.save() vals = ( Book.objects.annotate(num_authors=Count("authors__id")) .filter(authors__name__contains="Norvig", num_authors__gt=1) .aggregate(Avg("rating")) ) self.assertEqual(vals, {"rating__avg": 4.25}) def test_even_more_aggregate(self): publishers = ( Publisher.objects.annotate( earliest_book=Min("book__pubdate"), ) .exclude(earliest_book=None) .order_by("earliest_book") .values( "earliest_book", "num_awards", "id", "name", ) ) self.assertEqual( list(publishers), [ { "earliest_book": datetime.date(1991, 10, 15), "num_awards": 9, "id": self.p4.id, "name": "Morgan Kaufmann", }, { "earliest_book": datetime.date(1995, 1, 15), "num_awards": 7, "id": self.p3.id, "name": "Prentice Hall", }, { "earliest_book": datetime.date(2007, 12, 6), "num_awards": 3, "id": self.p1.id, "name": "Apress", }, { "earliest_book": datetime.date(2008, 3, 3), "num_awards": 1, "id": self.p2.id, "name": "Sams", }, ], ) vals = Store.objects.aggregate( Max("friday_night_closing"), Min("original_opening") ) self.assertEqual( vals, { "friday_night_closing__max": datetime.time(23, 59, 59), "original_opening__min": datetime.datetime(1945, 4, 25, 16, 24, 14), }, ) def test_annotate_values_list(self): books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("pk", "isbn", "mean_age") ) self.assertEqual(list(books), [(self.b1.id, "159059725", 34.5)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("isbn") ) self.assertEqual(list(books), [("159059725",)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("mean_age") ) self.assertEqual(list(books), [(34.5,)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("mean_age", flat=True) ) self.assertEqual(list(books), [34.5]) books = ( Book.objects.values_list("price") .annotate(count=Count("price")) .order_by("-count", "price") ) self.assertEqual( list(books), [ (Decimal("29.69"), 2), (Decimal("23.09"), 1), (Decimal("30"), 1), (Decimal("75"), 1), (Decimal("82.8"), 1), ], ) def test_dates_with_aggregation(self): """ .dates() returns a distinct set of dates when applied to a QuerySet with aggregation. Refs #18056. Previously, .dates() would return distinct (date_kind, aggregation) sets, in this case (year, num_authors), so 2008 would be returned twice because there are books from 2008 with a different number of authors. """ dates = Book.objects.annotate(num_authors=Count("authors")).dates( "pubdate", "year" ) self.assertSequenceEqual( dates, [ datetime.date(1991, 1, 1), datetime.date(1995, 1, 1), datetime.date(2007, 1, 1), datetime.date(2008, 1, 1), ], ) def test_values_aggregation(self): # Refs #20782 max_rating = Book.objects.values("rating").aggregate(max_rating=Max("rating")) self.assertEqual(max_rating["max_rating"], 5) max_books_per_rating = ( Book.objects.values("rating") .annotate(books_per_rating=Count("id")) .aggregate(Max("books_per_rating")) ) self.assertEqual(max_books_per_rating, {"books_per_rating__max": 3}) def test_ticket17424(self): """ Doing exclude() on a foreign model after annotate() doesn't crash. """ all_books = list(Book.objects.values_list("pk", flat=True).order_by("pk")) annotated_books = Book.objects.order_by("pk").annotate(one=Count("id")) # The value doesn't matter, we just need any negative # constraint on a related model that's a noop. excluded_books = annotated_books.exclude(publisher__name="__UNLIKELY_VALUE__") # Try to generate query tree str(excluded_books.query) self.assertQuerySetEqual(excluded_books, all_books, lambda x: x.pk) # Check internal state self.assertIsNone(annotated_books.query.alias_map["aggregation_book"].join_type) self.assertIsNone(excluded_books.query.alias_map["aggregation_book"].join_type) def test_ticket12886(self): """ Aggregation over sliced queryset works correctly. """ qs = Book.objects.order_by("-rating")[0:3] vals = qs.aggregate(average_top3_rating=Avg("rating"))["average_top3_rating"] self.assertAlmostEqual(vals, 4.5, places=2) def test_ticket11881(self): """ Subqueries do not needlessly contain ORDER BY, SELECT FOR UPDATE or select_related() stuff. """ qs = ( Book.objects.select_for_update() .order_by("pk") .select_related("publisher") .annotate(max_pk=Max("pk")) ) with CaptureQueriesContext(connection) as captured_queries: qs.aggregate(avg_pk=Avg("max_pk")) self.assertEqual(len(captured_queries), 1) qstr = captured_queries[0]["sql"].lower() self.assertNotIn("for update", qstr) forced_ordering = connection.ops.force_no_ordering() if forced_ordering: # If the backend needs to force an ordering we make sure it's # the only "ORDER BY" clause present in the query. self.assertEqual( re.findall(r"order by (\w+)", qstr), [", ".join(f[1][0] for f in forced_ordering).lower()], ) else: self.assertNotIn("order by", qstr) self.assertEqual(qstr.count(" join "), 0) def test_decimal_max_digits_has_no_effect(self): Book.objects.all().delete() a1 = Author.objects.first() p1 = Publisher.objects.first() thedate = timezone.now() for i in range(10): Book.objects.create( isbn="abcde{}".format(i), name="none", pages=10, rating=4.0, price=9999.98, contact=a1, publisher=p1, pubdate=thedate, ) book = Book.objects.aggregate(price_sum=Sum("price")) self.assertEqual(book["price_sum"], Decimal("99999.80")) def test_nonaggregate_aggregation_throws(self): with self.assertRaisesMessage(TypeError, "fail is not an aggregate expression"): Book.objects.aggregate(fail=F("price")) def test_nonfield_annotation(self): book = Book.objects.annotate(val=Max(Value(2))).first() self.assertEqual(book.val, 2) book = Book.objects.annotate( val=Max(Value(2), output_field=IntegerField()) ).first() self.assertEqual(book.val, 2) book = Book.objects.annotate(val=Max(2, output_field=IntegerField())).first() self.assertEqual(book.val, 2) def test_annotation_expressions(self): authors = Author.objects.annotate( combined_ages=Sum(F("age") + F("friends__age")) ).order_by("name") authors2 = Author.objects.annotate( combined_ages=Sum("age") + Sum("friends__age") ).order_by("name") for qs in (authors, authors2): self.assertQuerySetEqual( qs, [ ("Adrian Holovaty", 132), ("Brad Dayley", None), ("Jacob Kaplan-Moss", 129), ("James Bennett", 63), ("Jeffrey Forcier", 128), ("Paul Bissex", 120), ("Peter Norvig", 103), ("Stuart Russell", 103), ("Wesley J. Chun", 176), ], lambda a: (a.name, a.combined_ages), ) def test_aggregation_expressions(self): a1 = Author.objects.aggregate(av_age=Sum("age") / Count("*")) a2 = Author.objects.aggregate(av_age=Sum("age") / Count("age")) a3 = Author.objects.aggregate(av_age=Avg("age")) self.assertEqual(a1, {"av_age": 37}) self.assertEqual(a2, {"av_age": 37}) self.assertEqual(a3, {"av_age": Approximate(37.4, places=1)}) def test_avg_decimal_field(self): v = Book.objects.filter(rating=4).aggregate(avg_price=(Avg("price")))[ "avg_price" ] self.assertIsInstance(v, Decimal) self.assertEqual(v, Approximate(Decimal("47.39"), places=2)) def test_order_of_precedence(self): p1 = Book.objects.filter(rating=4).aggregate(avg_price=(Avg("price") + 2) * 3) self.assertEqual(p1, {"avg_price": Approximate(Decimal("148.18"), places=2)}) p2 = Book.objects.filter(rating=4).aggregate(avg_price=Avg("price") + 2 * 3) self.assertEqual(p2, {"avg_price": Approximate(Decimal("53.39"), places=2)}) def test_combine_different_types(self): msg = ( "Cannot infer type of '+' expression involving these types: FloatField, " "DecimalField. You must set output_field." ) qs = Book.objects.annotate(sums=Sum("rating") + Sum("pages") + Sum("price")) with self.assertRaisesMessage(FieldError, msg): qs.first() with self.assertRaisesMessage(FieldError, msg): qs.first() b1 = Book.objects.annotate( sums=Sum(F("rating") + F("pages") + F("price"), output_field=IntegerField()) ).get(pk=self.b4.pk) self.assertEqual(b1.sums, 383) b2 = Book.objects.annotate( sums=Sum(F("rating") + F("pages") + F("price"), output_field=FloatField()) ).get(pk=self.b4.pk) self.assertEqual(b2.sums, 383.69) b3 = Book.objects.annotate( sums=Sum(F("rating") + F("pages") + F("price"), output_field=DecimalField()) ).get(pk=self.b4.pk) self.assertEqual(b3.sums, Approximate(Decimal("383.69"), places=2)) def test_complex_aggregations_require_kwarg(self): with self.assertRaisesMessage( TypeError, "Complex annotations require an alias" ): Author.objects.annotate(Sum(F("age") + F("friends__age"))) with self.assertRaisesMessage(TypeError, "Complex aggregates require an alias"): Author.objects.aggregate(Sum("age") / Count("age")) with self.assertRaisesMessage(TypeError, "Complex aggregates require an alias"): Author.objects.aggregate(Sum(1)) def test_aggregate_over_complex_annotation(self): qs = Author.objects.annotate(combined_ages=Sum(F("age") + F("friends__age"))) age = qs.aggregate(max_combined_age=Max("combined_ages")) self.assertEqual(age["max_combined_age"], 176) age = qs.aggregate(max_combined_age_doubled=Max("combined_ages") * 2) self.assertEqual(age["max_combined_age_doubled"], 176 * 2) age = qs.aggregate( max_combined_age_doubled=Max("combined_ages") + Max("combined_ages") ) self.assertEqual(age["max_combined_age_doubled"], 176 * 2) age = qs.aggregate( max_combined_age_doubled=Max("combined_ages") + Max("combined_ages"), sum_combined_age=Sum("combined_ages"), ) self.assertEqual(age["max_combined_age_doubled"], 176 * 2) self.assertEqual(age["sum_combined_age"], 954) age = qs.aggregate( max_combined_age_doubled=Max("combined_ages") + Max("combined_ages"), sum_combined_age_doubled=Sum("combined_ages") + Sum("combined_ages"), ) self.assertEqual(age["max_combined_age_doubled"], 176 * 2) self.assertEqual(age["sum_combined_age_doubled"], 954 * 2) def test_values_annotation_with_expression(self): # ensure the F() is promoted to the group by clause qs = Author.objects.values("name").annotate(another_age=Sum("age") + F("age")) a = qs.get(name="Adrian Holovaty") self.assertEqual(a["another_age"], 68) qs = qs.annotate(friend_count=Count("friends")) a = qs.get(name="Adrian Holovaty") self.assertEqual(a["friend_count"], 2) qs = ( qs.annotate(combined_age=Sum("age") + F("friends__age")) .filter(name="Adrian Holovaty") .order_by("-combined_age") ) self.assertEqual( list(qs), [ { "name": "Adrian Holovaty", "another_age": 68, "friend_count": 1, "combined_age": 69, }, { "name": "Adrian Holovaty", "another_age": 68, "friend_count": 1, "combined_age": 63, }, ], ) vals = qs.values("name", "combined_age") self.assertEqual( list(vals), [ {"name": "Adrian Holovaty", "combined_age": 69}, {"name": "Adrian Holovaty", "combined_age": 63}, ], ) def test_annotate_values_aggregate(self): alias_age = ( Author.objects.annotate(age_alias=F("age")) .values( "age_alias", ) .aggregate(sum_age=Sum("age_alias")) ) age = Author.objects.values("age").aggregate(sum_age=Sum("age")) self.assertEqual(alias_age["sum_age"], age["sum_age"]) def test_annotate_over_annotate(self): author = ( Author.objects.annotate(age_alias=F("age")) .annotate(sum_age=Sum("age_alias")) .get(name="Adrian Holovaty") ) other_author = Author.objects.annotate(sum_age=Sum("age")).get( name="Adrian Holovaty" ) self.assertEqual(author.sum_age, other_author.sum_age) def test_aggregate_over_aggregate(self): msg = "Cannot resolve keyword 'age_agg' into field." with self.assertRaisesMessage(FieldError, msg): Author.objects.aggregate( age_agg=Sum(F("age")), avg_age=Avg(F("age_agg")), ) def test_annotated_aggregate_over_annotated_aggregate(self): with self.assertRaisesMessage( FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate" ): Book.objects.annotate(Max("id")).annotate(Sum("id__max")) class MyMax(Max): def as_sql(self, compiler, connection): self.set_source_expressions(self.get_source_expressions()[0:1]) return super().as_sql(compiler, connection) with self.assertRaisesMessage( FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate" ): Book.objects.annotate(Max("id")).annotate(my_max=MyMax("id__max", "price")) def test_multi_arg_aggregate(self): class MyMax(Max): output_field = DecimalField() def as_sql(self, compiler, connection): copy = self.copy() copy.set_source_expressions(copy.get_source_expressions()[0:1]) return super(MyMax, copy).as_sql(compiler, connection) with self.assertRaisesMessage(TypeError, "Complex aggregates require an alias"): Book.objects.aggregate(MyMax("pages", "price")) with self.assertRaisesMessage( TypeError, "Complex annotations require an alias" ): Book.objects.annotate(MyMax("pages", "price")) Book.objects.aggregate(max_field=MyMax("pages", "price")) def test_add_implementation(self): class MySum(Sum): pass # test completely changing how the output is rendered def lower_case_function_override(self, compiler, connection): sql, params = compiler.compile(self.source_expressions[0]) substitutions = { "function": self.function.lower(), "expressions": sql, "distinct": "", } substitutions.update(self.extra) return self.template % substitutions, params setattr(MySum, "as_" + connection.vendor, lower_case_function_override) qs = Book.objects.annotate( sums=MySum( F("rating") + F("pages") + F("price"), output_field=IntegerField() ) ) self.assertEqual(str(qs.query).count("sum("), 1) b1 = qs.get(pk=self.b4.pk) self.assertEqual(b1.sums, 383) # test changing the dict and delegating def lower_case_function_super(self, compiler, connection): self.extra["function"] = self.function.lower() return super(MySum, self).as_sql(compiler, connection) setattr(MySum, "as_" + connection.vendor, lower_case_function_super) qs = Book.objects.annotate( sums=MySum( F("rating") + F("pages") + F("price"), output_field=IntegerField() ) ) self.assertEqual(str(qs.query).count("sum("), 1) b1 = qs.get(pk=self.b4.pk) self.assertEqual(b1.sums, 383) # test overriding all parts of the template def be_evil(self, compiler, connection): substitutions = {"function": "MAX", "expressions": "2", "distinct": ""} substitutions.update(self.extra) return self.template % substitutions, () setattr(MySum, "as_" + connection.vendor, be_evil) qs = Book.objects.annotate( sums=MySum( F("rating") + F("pages") + F("price"), output_field=IntegerField() ) ) self.assertEqual(str(qs.query).count("MAX("), 1) b1 = qs.get(pk=self.b4.pk) self.assertEqual(b1.sums, 2) def test_complex_values_aggregation(self): max_rating = Book.objects.values("rating").aggregate( double_max_rating=Max("rating") + Max("rating") ) self.assertEqual(max_rating["double_max_rating"], 5 * 2) max_books_per_rating = ( Book.objects.values("rating") .annotate(books_per_rating=Count("id") + 5) .aggregate(Max("books_per_rating")) ) self.assertEqual(max_books_per_rating, {"books_per_rating__max": 3 + 5}) def test_expression_on_aggregation(self): qs = ( Publisher.objects.annotate( price_or_median=Greatest( Avg("book__rating", output_field=DecimalField()), Avg("book__price") ) ) .filter(price_or_median__gte=F("num_awards")) .order_by("num_awards") ) self.assertQuerySetEqual(qs, [1, 3, 7, 9], lambda v: v.num_awards) qs2 = ( Publisher.objects.annotate( rating_or_num_awards=Greatest( Avg("book__rating"), F("num_awards"), output_field=FloatField() ) ) .filter(rating_or_num_awards__gt=F("num_awards")) .order_by("num_awards") ) self.assertQuerySetEqual(qs2, [1, 3], lambda v: v.num_awards) def test_arguments_must_be_expressions(self): msg = "QuerySet.aggregate() received non-expression(s): %s." with self.assertRaisesMessage(TypeError, msg % FloatField()): Book.objects.aggregate(FloatField()) with self.assertRaisesMessage(TypeError, msg % True): Book.objects.aggregate(is_book=True) with self.assertRaisesMessage( TypeError, msg % ", ".join([str(FloatField()), "True"]) ): Book.objects.aggregate(FloatField(), Avg("price"), is_book=True) def test_aggregation_subquery_annotation(self): """Subquery annotations are excluded from the GROUP BY if they are not explicitly grouped against.""" latest_book_pubdate_qs = ( Book.objects.filter(publisher=OuterRef("pk")) .order_by("-pubdate") .values("pubdate")[:1] ) publisher_qs = Publisher.objects.annotate( latest_book_pubdate=Subquery(latest_book_pubdate_qs), ).annotate(count=Count("book")) with self.assertNumQueries(1) as ctx: list(publisher_qs) self.assertEqual(ctx[0]["sql"].count("SELECT"), 2) # The GROUP BY should not be by alias either. self.assertEqual(ctx[0]["sql"].lower().count("latest_book_pubdate"), 1) def test_aggregation_subquery_annotation_exists(self): latest_book_pubdate_qs = ( Book.objects.filter(publisher=OuterRef("pk")) .order_by("-pubdate") .values("pubdate")[:1] ) publisher_qs = Publisher.objects.annotate( latest_book_pubdate=Subquery(latest_book_pubdate_qs), count=Count("book"), ) self.assertTrue(publisher_qs.exists()) def test_aggregation_filter_exists(self): publishers_having_more_than_one_book_qs = ( Book.objects.values("publisher") .annotate(cnt=Count("isbn")) .filter(cnt__gt=1) ) query = publishers_having_more_than_one_book_qs.query.exists() _, _, group_by = query.get_compiler(connection=connection).pre_sql_setup() self.assertEqual(len(group_by), 1) def test_aggregation_exists_annotation(self): published_books = Book.objects.filter(publisher=OuterRef("pk")) publisher_qs = Publisher.objects.annotate( published_book=Exists(published_books), count=Count("book"), ).values_list("name", flat=True) self.assertCountEqual( list(publisher_qs), [ "Apress", "Morgan Kaufmann", "Jonno's House of Books", "Prentice Hall", "Sams", ], ) def test_aggregation_subquery_annotation_values(self): """ Subquery annotations and external aliases are excluded from the GROUP BY if they are not selected. """ books_qs = ( Book.objects.annotate( first_author_the_same_age=Subquery( Author.objects.filter( age=OuterRef("contact__friends__age"), ) .order_by("age") .values("id")[:1], ) ) .filter( publisher=self.p1, first_author_the_same_age__isnull=False, ) .annotate( min_age=Min("contact__friends__age"), ) .values("name", "min_age") .order_by("name") ) self.assertEqual( list(books_qs), [ {"name": "Practical Django Projects", "min_age": 34}, { "name": ( "The Definitive Guide to Django: Web Development Done Right" ), "min_age": 29, }, ], ) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_aggregation_subquery_annotation_values_collision(self): books_rating_qs = Book.objects.filter( pk=OuterRef("book"), ).values("rating") publisher_qs = ( Publisher.objects.filter( book__contact__age__gt=20, ) .annotate( rating=Subquery(books_rating_qs), ) .values("rating") .annotate(total_count=Count("*")) .order_by("rating") ) self.assertEqual( list(publisher_qs), [ {"rating": 3.0, "total_count": 1}, {"rating": 4.0, "total_count": 3}, {"rating": 4.5, "total_count": 1}, {"rating": 5.0, "total_count": 1}, ], ) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_aggregation_subquery_annotation_multivalued(self): """ Subquery annotations must be included in the GROUP BY if they use potentially multivalued relations (contain the LOOKUP_SEP). """ subquery_qs = Author.objects.filter( pk=OuterRef("pk"), book__name=OuterRef("book__name"), ).values("pk") author_qs = Author.objects.annotate( subquery_id=Subquery(subquery_qs), ).annotate(count=Count("book")) self.assertEqual(author_qs.count(), Author.objects.count()) def test_aggregation_order_by_not_selected_annotation_values(self): result_asc = [ self.b4.pk, self.b3.pk, self.b1.pk, self.b2.pk, self.b5.pk, self.b6.pk, ] result_desc = result_asc[::-1] tests = [ ("min_related_age", result_asc), ("-min_related_age", result_desc), (F("min_related_age"), result_asc), (F("min_related_age").asc(), result_asc), (F("min_related_age").desc(), result_desc), ] for ordering, expected_result in tests: with self.subTest(ordering=ordering): books_qs = ( Book.objects.annotate( min_age=Min("authors__age"), ) .annotate( min_related_age=Coalesce("min_age", "contact__age"), ) .order_by(ordering) .values_list("pk", flat=True) ) self.assertEqual(list(books_qs), expected_result) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_group_by_subquery_annotation(self): """ Subquery annotations are included in the GROUP BY if they are grouped against. """ long_books_count_qs = ( Book.objects.filter( publisher=OuterRef("pk"), pages__gt=400, ) .values("publisher") .annotate(count=Count("pk")) .values("count") ) groups = [ Subquery(long_books_count_qs), long_books_count_qs, long_books_count_qs.query, ] for group in groups: with self.subTest(group=group.__class__.__name__): long_books_count_breakdown = Publisher.objects.values_list( group, ).annotate(total=Count("*")) self.assertEqual(dict(long_books_count_breakdown), {None: 1, 1: 4}) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_group_by_exists_annotation(self): """ Exists annotations are included in the GROUP BY if they are grouped against. """ long_books_qs = Book.objects.filter( publisher=OuterRef("pk"), pages__gt=800, ) has_long_books_breakdown = Publisher.objects.values_list( Exists(long_books_qs), ).annotate(total=Count("*")) self.assertEqual(dict(has_long_books_breakdown), {True: 2, False: 3}) def test_group_by_nested_expression_with_params(self): books_qs = ( Book.objects.annotate(greatest_pages=Greatest("pages", Value(600))) .values( "greatest_pages", ) .annotate( min_pages=Min("pages"), least=Least("min_pages", "greatest_pages"), ) .values_list("least", flat=True) ) self.assertCountEqual(books_qs, [300, 946, 1132]) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_aggregation_subquery_annotation_related_field(self): publisher = Publisher.objects.create(name=self.a9.name, num_awards=2) book = Book.objects.create( isbn="159059999", name="Test book.", pages=819, rating=2.5, price=Decimal("14.44"), contact=self.a9, publisher=publisher, pubdate=datetime.date(2019, 12, 6), ) book.authors.add(self.a5, self.a6, self.a7) books_qs = ( Book.objects.annotate( contact_publisher=Subquery( Publisher.objects.filter( pk=OuterRef("publisher"), name=OuterRef("contact__name"), ).values("name")[:1], ) ) .filter( contact_publisher__isnull=False, ) .annotate(count=Count("authors")) ) with self.assertNumQueries(1) as ctx: self.assertSequenceEqual(books_qs, [book]) if connection.features.allows_group_by_select_index: self.assertEqual(ctx[0]["sql"].count("SELECT"), 3) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_aggregation_nested_subquery_outerref(self): publisher_with_same_name = Publisher.objects.filter( id__in=Subquery( Publisher.objects.filter( name=OuterRef(OuterRef("publisher__name")), ).values("id"), ), ).values(publisher_count=Count("id"))[:1] books_breakdown = Book.objects.annotate( publisher_count=Subquery(publisher_with_same_name), authors_count=Count("authors"), ).values_list("publisher_count", flat=True) self.assertSequenceEqual(books_breakdown, [1] * 6) def test_aggregation_exists_multivalued_outeref(self): self.assertCountEqual( Publisher.objects.annotate( books_exists=Exists( Book.objects.filter(publisher=OuterRef("book__publisher")) ), books_count=Count("book"), ), Publisher.objects.all(), ) def test_filter_in_subquery_or_aggregation(self): """ Filtering against an aggregate requires the usage of the HAVING clause. If such a filter is unionized to a non-aggregate one the latter will also need to be moved to the HAVING clause and have its grouping columns used in the GROUP BY. When this is done with a subquery the specialized logic in charge of using outer reference columns to group should be used instead of the subquery itself as the latter might return multiple rows. """ authors = Author.objects.annotate( Count("book"), ).filter(Q(book__count__gt=0) | Q(pk__in=Book.objects.values("authors"))) self.assertCountEqual(authors, Author.objects.all()) def test_aggregation_random_ordering(self): """Random() is not included in the GROUP BY when used for ordering.""" authors = Author.objects.annotate(contact_count=Count("book")).order_by("?") self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 1), ("Jacob Kaplan-Moss", 1), ("Brad Dayley", 1), ("James Bennett", 1), ("Jeffrey Forcier", 1), ("Paul Bissex", 1), ("Wesley J. Chun", 1), ("Stuart Russell", 1), ("Peter Norvig", 2), ], lambda a: (a.name, a.contact_count), ordered=False, ) def test_empty_result_optimization(self): with self.assertNumQueries(0): self.assertEqual( Publisher.objects.none().aggregate( sum_awards=Sum("num_awards"), books_count=Count("book"), ), { "sum_awards": None, "books_count": 0, }, ) # Expression without empty_result_set_value forces queries to be # executed even if they would return an empty result set. raw_books_count = Func("book", function="COUNT") raw_books_count.contains_aggregate = True with self.assertNumQueries(1): self.assertEqual( Publisher.objects.none().aggregate( sum_awards=Sum("num_awards"), books_count=raw_books_count, ), { "sum_awards": None, "books_count": 0, }, ) def test_coalesced_empty_result_set(self): with self.assertNumQueries(0): self.assertEqual( Publisher.objects.none().aggregate( sum_awards=Coalesce(Sum("num_awards"), 0), )["sum_awards"], 0, ) # Multiple expressions. with self.assertNumQueries(0): self.assertEqual( Publisher.objects.none().aggregate( sum_awards=Coalesce(Sum("num_awards"), None, 0), )["sum_awards"], 0, ) # Nested coalesce. with self.assertNumQueries(0): self.assertEqual( Publisher.objects.none().aggregate( sum_awards=Coalesce(Coalesce(Sum("num_awards"), None), 0), )["sum_awards"], 0, ) # Expression coalesce. with self.assertNumQueries(1): self.assertIsInstance( Store.objects.none().aggregate( latest_opening=Coalesce( Max("original_opening"), RawSQL("CURRENT_TIMESTAMP", []), ), )["latest_opening"], datetime.datetime, ) def test_aggregation_default_unsupported_by_count(self): msg = "Count does not allow default." with self.assertRaisesMessage(TypeError, msg): Count("age", default=0) def test_aggregation_default_unset(self): for Aggregate in [Avg, Max, Min, StdDev, Sum, Variance]: with self.subTest(Aggregate): result = Author.objects.filter(age__gt=100).aggregate( value=Aggregate("age"), ) self.assertIsNone(result["value"]) def test_aggregation_default_zero(self): for Aggregate in [Avg, Max, Min, StdDev, Sum, Variance]: with self.subTest(Aggregate): result = Author.objects.filter(age__gt=100).aggregate( value=Aggregate("age", default=0), ) self.assertEqual(result["value"], 0) def test_aggregation_default_integer(self): for Aggregate in [Avg, Max, Min, StdDev, Sum, Variance]: with self.subTest(Aggregate): result = Author.objects.filter(age__gt=100).aggregate( value=Aggregate("age", default=21), ) self.assertEqual(result["value"], 21) def test_aggregation_default_expression(self): for Aggregate in [Avg, Max, Min, StdDev, Sum, Variance]: with self.subTest(Aggregate): result = Author.objects.filter(age__gt=100).aggregate( value=Aggregate("age", default=Value(5) * Value(7)), ) self.assertEqual(result["value"], 35) def test_aggregation_default_group_by(self): qs = ( Publisher.objects.values("name") .annotate( books=Count("book"), pages=Sum("book__pages", default=0), ) .filter(books=0) ) self.assertSequenceEqual( qs, [{"name": "Jonno's House of Books", "books": 0, "pages": 0}], ) def test_aggregation_default_compound_expression(self): # Scale rating to a percentage; default to 50% if no books published. formula = Avg("book__rating", default=2.5) * 20.0 queryset = Publisher.objects.annotate(rating=formula).order_by("name") self.assertSequenceEqual( queryset.values("name", "rating"), [ {"name": "Apress", "rating": 85.0}, {"name": "Jonno's House of Books", "rating": 50.0}, {"name": "Morgan Kaufmann", "rating": 100.0}, {"name": "Prentice Hall", "rating": 80.0}, {"name": "Sams", "rating": 60.0}, ], ) def test_aggregation_default_using_time_from_python(self): expr = Min( "store__friday_night_closing", filter=~Q(store__name="Amazon.com"), default=datetime.time(17), ) if connection.vendor == "mysql": # Workaround for #30224 for MySQL & MariaDB. expr.default = Cast(expr.default, TimeField()) queryset = Book.objects.annotate(oldest_store_opening=expr).order_by("isbn") self.assertSequenceEqual( queryset.values("isbn", "oldest_store_opening"), [ {"isbn": "013235613", "oldest_store_opening": datetime.time(21, 30)}, { "isbn": "013790395", "oldest_store_opening": datetime.time(23, 59, 59), }, {"isbn": "067232959", "oldest_store_opening": datetime.time(17)}, {"isbn": "155860191", "oldest_store_opening": datetime.time(21, 30)}, { "isbn": "159059725", "oldest_store_opening": datetime.time(23, 59, 59), }, {"isbn": "159059996", "oldest_store_opening": datetime.time(21, 30)}, ], ) def test_aggregation_default_using_time_from_database(self): now = timezone.now().astimezone(datetime.timezone.utc) expr = Min( "store__friday_night_closing", filter=~Q(store__name="Amazon.com"), default=TruncHour(NowUTC(), output_field=TimeField()), ) queryset = Book.objects.annotate(oldest_store_opening=expr).order_by("isbn") self.assertSequenceEqual( queryset.values("isbn", "oldest_store_opening"), [ {"isbn": "013235613", "oldest_store_opening": datetime.time(21, 30)}, { "isbn": "013790395", "oldest_store_opening": datetime.time(23, 59, 59), }, {"isbn": "067232959", "oldest_store_opening": datetime.time(now.hour)}, {"isbn": "155860191", "oldest_store_opening": datetime.time(21, 30)}, { "isbn": "159059725", "oldest_store_opening": datetime.time(23, 59, 59), }, {"isbn": "159059996", "oldest_store_opening": datetime.time(21, 30)}, ], ) def test_aggregation_default_using_date_from_python(self): expr = Min("book__pubdate", default=datetime.date(1970, 1, 1)) if connection.vendor == "mysql": # Workaround for #30224 for MySQL & MariaDB. expr.default = Cast(expr.default, DateField()) queryset = Publisher.objects.annotate(earliest_pubdate=expr).order_by("name") self.assertSequenceEqual( queryset.values("name", "earliest_pubdate"), [ {"name": "Apress", "earliest_pubdate": datetime.date(2007, 12, 6)}, { "name": "Jonno's House of Books", "earliest_pubdate": datetime.date(1970, 1, 1), }, { "name": "Morgan Kaufmann", "earliest_pubdate": datetime.date(1991, 10, 15), }, { "name": "Prentice Hall", "earliest_pubdate": datetime.date(1995, 1, 15), }, {"name": "Sams", "earliest_pubdate": datetime.date(2008, 3, 3)}, ], ) def test_aggregation_default_using_date_from_database(self): now = timezone.now().astimezone(datetime.timezone.utc) expr = Min("book__pubdate", default=TruncDate(NowUTC())) queryset = Publisher.objects.annotate(earliest_pubdate=expr).order_by("name") self.assertSequenceEqual( queryset.values("name", "earliest_pubdate"), [ {"name": "Apress", "earliest_pubdate": datetime.date(2007, 12, 6)}, {"name": "Jonno's House of Books", "earliest_pubdate": now.date()}, { "name": "Morgan Kaufmann", "earliest_pubdate": datetime.date(1991, 10, 15), }, { "name": "Prentice Hall", "earliest_pubdate": datetime.date(1995, 1, 15), }, {"name": "Sams", "earliest_pubdate": datetime.date(2008, 3, 3)}, ], ) def test_aggregation_default_using_datetime_from_python(self): expr = Min( "store__original_opening", filter=~Q(store__name="Amazon.com"), default=datetime.datetime(1970, 1, 1), ) if connection.vendor == "mysql": # Workaround for #30224 for MySQL & MariaDB. expr.default = Cast(expr.default, DateTimeField()) queryset = Book.objects.annotate(oldest_store_opening=expr).order_by("isbn") self.assertSequenceEqual( queryset.values("isbn", "oldest_store_opening"), [ { "isbn": "013235613", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, { "isbn": "013790395", "oldest_store_opening": datetime.datetime(2001, 3, 15, 11, 23, 37), }, { "isbn": "067232959", "oldest_store_opening": datetime.datetime(1970, 1, 1), }, { "isbn": "155860191", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, { "isbn": "159059725", "oldest_store_opening": datetime.datetime(2001, 3, 15, 11, 23, 37), }, { "isbn": "159059996", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, ], ) def test_aggregation_default_using_datetime_from_database(self): now = timezone.now().astimezone(datetime.timezone.utc) expr = Min( "store__original_opening", filter=~Q(store__name="Amazon.com"), default=TruncHour(NowUTC(), output_field=DateTimeField()), ) queryset = Book.objects.annotate(oldest_store_opening=expr).order_by("isbn") self.assertSequenceEqual( queryset.values("isbn", "oldest_store_opening"), [ { "isbn": "013235613", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, { "isbn": "013790395", "oldest_store_opening": datetime.datetime(2001, 3, 15, 11, 23, 37), }, { "isbn": "067232959", "oldest_store_opening": now.replace( minute=0, second=0, microsecond=0, tzinfo=None ), }, { "isbn": "155860191", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, { "isbn": "159059725", "oldest_store_opening": datetime.datetime(2001, 3, 15, 11, 23, 37), }, { "isbn": "159059996", "oldest_store_opening": datetime.datetime(1945, 4, 25, 16, 24, 14), }, ], ) def test_aggregation_default_using_duration_from_python(self): result = Publisher.objects.filter(num_awards__gt=3).aggregate( value=Sum("duration", default=datetime.timedelta(0)), ) self.assertEqual(result["value"], datetime.timedelta(0)) def test_aggregation_default_using_duration_from_database(self): result = Publisher.objects.filter(num_awards__gt=3).aggregate( value=Sum("duration", default=Now() - Now()), ) self.assertEqual(result["value"], datetime.timedelta(0)) def test_aggregation_default_using_decimal_from_python(self): result = Book.objects.filter(rating__lt=3.0).aggregate( value=Sum("price", default=Decimal("0.00")), ) self.assertEqual(result["value"], Decimal("0.00")) def test_aggregation_default_using_decimal_from_database(self): result = Book.objects.filter(rating__lt=3.0).aggregate( value=Sum("price", default=Pi()), ) self.assertAlmostEqual(result["value"], Decimal.from_float(math.pi), places=6) def test_aggregation_default_passed_another_aggregate(self): result = Book.objects.aggregate( value=Sum("price", filter=Q(rating__lt=3.0), default=Avg("pages") / 10.0), ) self.assertAlmostEqual(result["value"], Decimal("61.72"), places=2) def test_aggregation_default_after_annotation(self): result = Publisher.objects.annotate( double_num_awards=F("num_awards") * 2, ).aggregate(value=Sum("double_num_awards", default=0)) self.assertEqual(result["value"], 40) def test_aggregation_default_not_in_aggregate(self): result = Publisher.objects.annotate( avg_rating=Avg("book__rating", default=2.5), ).aggregate(Sum("num_awards")) self.assertEqual(result["num_awards__sum"], 20) def test_exists_none_with_aggregate(self): qs = Book.objects.annotate( count=Count("id"), exists=Exists(Author.objects.none()), ) self.assertEqual(len(qs), 6) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "aggregation_author"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) with self.assertRaisesMessage(ValueError, msg): Author.objects.aggregate(**{crafted_alias: Avg("age")}) def test_exists_extra_where_with_aggregate(self): qs = Book.objects.annotate( count=Count("id"), exists=Exists(Author.objects.extra(where=["1=0"])), ) self.assertEqual(len(qs), 6) def test_aggregation_over_annotation_shared_alias(self): self.assertEqual( Publisher.objects.annotate(agg=Count("book__authors")).aggregate( agg=Count("agg"), ), {"agg": 5}, ) class AggregateAnnotationPruningTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(age=1) cls.a2 = Author.objects.create(age=2) cls.p1 = Publisher.objects.create(num_awards=1) cls.p2 = Publisher.objects.create(num_awards=0) cls.b1 = Book.objects.create( name="b1", publisher=cls.p1, pages=100, rating=4.5, price=10, contact=cls.a1, pubdate=datetime.date.today(), ) cls.b1.authors.add(cls.a1) cls.b2 = Book.objects.create( name="b2", publisher=cls.p2, pages=1000, rating=3.2, price=50, contact=cls.a2, pubdate=datetime.date.today(), ) cls.b2.authors.add(cls.a1, cls.a2) def test_unused_aliased_aggregate_pruned(self): with CaptureQueriesContext(connection) as ctx: cnt = Book.objects.alias( authors_count=Count("authors"), ).count() self.assertEqual(cnt, 2) sql = ctx.captured_queries[0]["sql"].lower() self.assertEqual(sql.count("select"), 2, "Subquery wrapping required") self.assertNotIn("authors_count", sql) def test_non_aggregate_annotation_pruned(self): with CaptureQueriesContext(connection) as ctx: Book.objects.annotate( name_lower=Lower("name"), ).count() sql = ctx.captured_queries[0]["sql"].lower() self.assertEqual(sql.count("select"), 1, "No subquery wrapping required") self.assertNotIn("name_lower", sql) def test_unreferenced_aggregate_annotation_pruned(self): with CaptureQueriesContext(connection) as ctx: cnt = Book.objects.annotate( authors_count=Count("authors"), ).count() self.assertEqual(cnt, 2) sql = ctx.captured_queries[0]["sql"].lower() self.assertEqual(sql.count("select"), 2, "Subquery wrapping required") self.assertNotIn("authors_count", sql) def test_referenced_aggregate_annotation_kept(self): with CaptureQueriesContext(connection) as ctx: Book.objects.annotate( authors_count=Count("authors"), ).aggregate(Avg("authors_count")) sql = ctx.captured_queries[0]["sql"].lower() self.assertEqual(sql.count("select"), 2, "Subquery wrapping required") self.assertEqual(sql.count("authors_count"), 2) def test_referenced_group_by_annotation_kept(self): queryset = Book.objects.values(pages_mod=Mod("pages", 10)).annotate( mod_count=Count("*") ) self.assertEqual(queryset.count(), 1)
c997587d9b53fc22b545c2fcc19fc8498edfafc8146adcaf34ab172c86bb1639
import datetime import os import re import unittest import zoneinfo from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse from django.contrib import admin from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth import REDIRECT_FIELD_NAME, get_permission_codename from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.db import connection from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( TestCase, ignore_warnings, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.utils import override_script_prefix from django.urls import NoReverseMatch, resolve, reverse from django.utils import formats, translation from django.utils.cache import get_max_age from django.utils.deprecation import RemovedInDjango60Warning from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, Category, Chapter, ChapterXtra1, ChapterXtra2, Character, Child, Choice, City, Collector, Color, ComplexSortedPerson, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DooHickey, Employee, EmptyModel, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, Link, MainPrepopulated, Media, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recommendation, Recommender, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Restaurant, RowLevelChangePermissionModel, SecretHideout, Section, ShortMessage, Simple, Song, State, Story, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." MULTIPART_ENCTYPE = 'enctype="multipart/form-data"' def make_aware_datetimes(dt, iana_key): """Makes one aware datetime for each supported time zone provider.""" yield dt.replace(tzinfo=zoneinfo.ZoneInfo(iana_key)) class AdminFieldExtractionMixin: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for field_line in fieldset: fields.extend(field_line) return fields def get_admin_readonly_fields(self, response): """ Return the readonly fields for the response's AdminForm. """ return [f for f in self.get_admin_form_fields(response) if f.is_readonly] def get_admin_readonly_field(self, response, field_name): """ Return the readonly field for the given field_name. """ admin_readonly_fields = self.get_admin_readonly_fields(response) for field in admin_readonly_fields: if field.field["name"] == field_name: return field @override_settings(ROOT_URLCONF="admin_views.urls", USE_I18N=True, LANGUAGE_CODE="en") class AdminViewBasicTestCase(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, title="Article 1", ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, title="Article 2", ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.color1 = Color.objects.create(value="Red", warm=True) cls.color2 = Color.objects.create(value="Orange", warm=True) cls.color3 = Color.objects.create(value="Blue", warm=False) cls.color4 = Color.objects.create(value="Green", warm=False) cls.fab1 = Fabric.objects.create(surface="x") cls.fab2 = Fabric.objects.create(surface="y") cls.fab3 = Fabric.objects.create(surface="plain") cls.b1 = Book.objects.create(name="Book 1") cls.b2 = Book.objects.create(name="Book 2") cls.pro1 = Promo.objects.create(name="Promo 1", book=cls.b1) cls.pro1 = Promo.objects.create(name="Promo 2", book=cls.b2) cls.chap1 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b1 ) cls.chap2 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b1 ) cls.chap3 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b2 ) cls.chap4 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b2 ) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra="ChapterXtra1 1") cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra="ChapterXtra1 2") Actor.objects.create(name="Palin", age=27) # Post data for edit inline cls.inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": cls.a1.pk, # there is no title in database, give one here or formset will fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "&lt;p&gt;Middle content&lt;/p&gt;", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": cls.s1.pk, "article_set-1-id": cls.a2.pk, "article_set-1-title": "Need a title.", "article_set-1-content": "&lt;p&gt;Oldest content&lt;/p&gt;", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": cls.a3.pk, "article_set-2-title": "Need a title.", "article_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def setUp(self): self.client.force_login(self.superuser) def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertLess( response.content.index(text1.encode()), response.content.index(text2.encode()), (failing_msg or "") + "\nResponse:\n" + response.content.decode(response.charset), ) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ add_url = reverse("admin:admin_views_article_add") response = self.client.get(add_url[:-1]) self.assertRedirects(response, add_url, status_code=301) def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): response = self.client.get( reverse("admin:admin_views_section_add"), {"name": "My Section"} ) self.assertContains( response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response", ) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(quote("abc/<b>"),)), follow=True, ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["section with ID “abc/<b>” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_edit_GET_old_url_redirect(self): """ The change URL changed in Django 1.9, but the old one still redirects. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)).replace( "change/", "" ) ) self.assertRedirects( response, reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) def test_basic_inheritance_GET_string_PK(self): """ GET on the change_view (for inherited models) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_supervillain_change", args=("abc",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["super villain with ID “abc” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_section_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """HTTP response from a popup is properly escaped.""" post_data = { IS_POPUP_VAR: "1", "title": "title with a new\nline", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertContains(response, "title with a new\\nline") def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ url = reverse("admin:admin_views_section_change", args=(self.s1.pk,)) response = self.client.post(url, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as(self): """ Test "save as". """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-3-section": "1", "article_set-4-section": "1", "article_set-5-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as_delete_inline(self): """ Should be able to "Save as new" while also deleting an inline. """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-2-DELETE": "1", "article_set-3-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # started with 3 articles, one was deleted. self.assertEqual(Section.objects.latest("id").article_set.count(), 2) def test_change_list_column_field_classes(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) # callables display the callable name. self.assertContains(response, "column-callable_year") self.assertContains(response, "field-callable_year") # lambdas display as "lambda" + index that they appear in list_display. self.assertContains(response, "column-lambda8") self.assertContains(response, "field-lambda8") def test_change_list_sorting_callable(self): """ Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_property(self): """ Sort on a list_display field that is a property (column 10 is a property in Article model). """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 10} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on property are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on property are out of order.", ) def test_change_list_sorting_callable_query_expression(self): """Query expressions may be used for admin_order_field.""" tests = [ ("order_by_expression", 9), ("order_by_f_expression", 12), ("order_by_orderby_expression", 13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_callable_query_expression_reverse(self): tests = [ ("order_by_expression", -9), ("order_by_f_expression", -12), ("order_by_orderby_expression", -13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_model(self): """ Ensure we can sort on a list_display field that is a Model method (column 3 is 'model_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-3"} ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on Model method are out of order.", ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on Model method are out of order.", ) def test_change_list_sorting_model_admin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (column 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "4"} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_model_admin_reverse(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method in reverse order (i.e. admin_order_field uses the '-' prefix) (column 6 is 'model_year_reverse' in ArticleAdmin) """ td = '<td class="field-model_property_year">%s</td>' td_2000, td_2008, td_2009 = td % 2000, td % 2008, td % 2009 response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "6"} ) self.assertContentBefore( response, td_2009, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2000, "Results of sorting on ModelAdmin method are out of order.", ) # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-6"} ) self.assertContentBefore( response, td_2000, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2009, "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) # Sort by name, gender response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "1.2"} ) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "-2.1"} ) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def test_change_list_sorting_preserve_queryset_ordering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) response = self.client.get(reverse("admin:admin_views_person_changelist"), {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def test_change_list_sorting_model_meta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso="ur", name="Urdu") l2 = Language.objects.create(iso="ar", name="Arabic") link1 = reverse("admin:admin_views_language_change", args=(quote(l1.pk),)) link2 = reverse("admin:admin_views_language_change", args=(quote(l2.pk),)) response = self.client.get(reverse("admin:admin_views_language_changelist"), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get( reverse("admin:admin_views_language_changelist"), {"o": "-1"} ) self.assertContentBefore(response, link1, link2) def test_change_list_sorting_override_model_admin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_podcast_change", args=(p2.pk,)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # The changelist displays the correct columns if two columns correspond # to the same ordering field. dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(quote(p1.pk),)) link2 = reverse("admin:admin_views_podcast_change", args=(quote(p2.pk),)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse("admin:admin_views_complexsortedperson_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_complexsortedperson_change", args=(p2.pk,)) response = self.client.get( reverse("admin:admin_views_complexsortedperson_changelist"), {} ) # Should have 5 columns (including action checkbox col) self.assertContains(response, '<th scope="col"', count=5) self.assertContains(response, "Name") self.assertContains(response, "Colored name") # Check order self.assertContentBefore(response, "Name", "Colored name") # Check sorting - should be by name self.assertContentBefore(response, link2, link1) def test_sort_indicators_admin_order(self): """ The admin shows default sort indicators for all kinds of 'ordering' fields: field names, method on the model admin and model itself, and other callables. See #17252. """ models = [ (AdminOrderedField, "adminorderedfield"), (AdminOrderedModelMethod, "adminorderedmodelmethod"), (AdminOrderedAdminMethod, "adminorderedadminmethod"), (AdminOrderedCallable, "adminorderedcallable"), ] for model, url in models: model.objects.create(stuff="The Last Item", order=3) model.objects.create(stuff="The First Item", order=1) model.objects.create(stuff="The Middle Item", order=2) response = self.client.get( reverse("admin:admin_views_%s_changelist" % url), {} ) # Should have 3 columns including action checkbox col. self.assertContains(response, '<th scope="col"', count=3, msg_prefix=url) # Check if the correct column was selected. 2 is the index of the # 'order' column in the model admin's 'list_display' with 0 being # the implicit 'action_checkbox' and 1 being the column 'stuff'. self.assertEqual( response.context["cl"].get_ordering_field_columns(), {2: "asc"} ) # Check order of records. self.assertContentBefore(response, "The First Item", "The Middle Item") self.assertContentBefore(response, "The Middle Item", "The Last Item") def test_has_related_field_in_list_display_fk(self): """Joins shouldn't be performed for <FK>_id fields in list display.""" state = State.objects.create(name="Karnataka") City.objects.create(state=state, name="Bangalore") response = self.client.get(reverse("admin:admin_views_city_changelist"), {}) response.context["cl"].list_display = ["id", "name", "state"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["id", "name", "state_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_has_related_field_in_list_display_o2o(self): """Joins shouldn't be performed for <O2O>_id fields in list display.""" media = Media.objects.create(name="Foo") Vodcast.objects.create(media=media) response = self.client.get(reverse("admin:admin_views_vodcast_changelist"), {}) response.context["cl"].list_display = ["media"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["media_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_limited_filter(self): """ Admin changelist filters do not contain objects excluded via limit_choices_to. """ response = self.client.get(reverse("admin:admin_views_thing_changelist")) self.assertContains( response, '<div id="changelist-filter">', msg_prefix="Expected filter not found in changelist view", ) self.assertNotContains( response, '<a href="?color__id__exact=3">Blue</a>', msg_prefix="Changelist filter not correctly limited by limit_choices_to", ) def test_change_list_facet_toggle(self): # Toggle is visible when show_facet is the default of # admin.ShowFacets.ALLOW. admin_url = reverse("admin:admin_views_album_changelist") response = self.client.get(admin_url) self.assertContains( response, '<a href="?_facets=True" class="viewlink">Show counts</a>', msg_prefix="Expected facet filter toggle not found in changelist view", ) response = self.client.get(f"{admin_url}?_facets=True") self.assertContains( response, '<a href="?" class="hidelink">Hide counts</a>', msg_prefix="Expected facet filter toggle not found in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.ALWAYS. response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.NEVER. response = self.client.get(reverse("admin:admin_views_fooddelivery_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) def test_relation_spanning_filters(self): changelist_url = reverse("admin:admin_views_chapterxtra1_changelist") response = self.client.get(changelist_url) self.assertContains(response, '<div id="changelist-filter">') filters = { "chap__id__exact": { "values": [c.id for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.id == value, }, "chap__title": { "values": [c.title for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.title == value, }, "chap__book__id__exact": { "values": [b.id for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.id == value, }, "chap__book__name": { "values": [b.name for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.name == value, }, "chap__book__promo__id__exact": { "values": [p.id for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( id=value ).exists(), }, "chap__book__promo__name": { "values": [p.name for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( name=value ).exists(), }, # A forward relation (book) after a reverse relation (promo). "guest_author__promo__book__id__exact": { "values": [p.id for p in Book.objects.all()], "test": lambda obj, value: obj.guest_author.promo_set.filter( book=value ).exists(), }, } for filter_path, params in filters.items(): for value in params["values"]: query_string = urlencode({filter_path: value}) # ensure filter link exists self.assertContains(response, '<a href="?%s"' % query_string) # ensure link works filtered_response = self.client.get( "%s?%s" % (changelist_url, query_string) ) self.assertEqual(filtered_response.status_code, 200) # ensure changelist contains only valid objects for obj in filtered_response.context["cl"].queryset.all(): self.assertTrue(params["test"](obj, value)) def test_incorrect_lookup_parameters(self): """Ensure incorrect lookup parameters are handled gracefully.""" changelist_url = reverse("admin:admin_views_thing_changelist") response = self.client.get(changelist_url, {"notarealfield": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) # Spanning relationships through a nonexistent related object (Refs #16716) response = self.client.get(changelist_url, {"notarealfield__whatever": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) response = self.client.get( changelist_url, {"color__id__exact": "StringNotInteger!"} ) self.assertRedirects(response, "%s?e=1" % changelist_url) # Regression test for #18530 response = self.client.get(changelist_url, {"pub_date__gte": "foo"}) self.assertRedirects(response, "%s?e=1" % changelist_url) def test_isnull_lookups(self): """Ensure is_null is handled correctly.""" Article.objects.create( title="I Could Go Anywhere", content="Versatile", date=datetime.datetime.now(), ) changelist_url = reverse("admin:admin_views_article_changelist") response = self.client.get(changelist_url) self.assertContains(response, "4 articles") response = self.client.get(changelist_url, {"section__isnull": "false"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "0"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "true"}) self.assertContains(response, "1 article") response = self.client.get(changelist_url, {"section__isnull": "1"}) self.assertContains(response, "1 article") def test_logout_and_password_change_URLs(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains( response, '<form id="logout-form" method="post" action="%s">' % reverse("admin:logout"), ) self.assertContains( response, '<a href="%s">' % reverse("admin:password_change") ) def test_named_group_field_choices_change_list(self): """ Ensures the admin changelist shows correct values in the relevant column for rows corresponding to instances of a model in which a named group has been used in the choices option of a field. """ link1 = reverse("admin:admin_views_fabric_change", args=(self.fab1.pk,)) link2 = reverse("admin:admin_views_fabric_change", args=(self.fab2.pk,)) response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist table isn't showing the right human-readable values " "set by a model field 'choices' option named group." ) self.assertContains( response, '<a href="%s">Horizontal</a>' % link1, msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="%s">Vertical</a>' % link2, msg_prefix=fail_msg, html=True, ) def test_named_group_field_choices_filter(self): """ Ensures the filter UI shows correctly when at least one named group has been used in the choices option of a model field. """ response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist filter isn't showing options contained inside a model " "field 'choices' option named group." ) self.assertContains(response, '<div id="changelist-filter">') self.assertContains( response, '<a href="?surface__exact=x">Horizontal</a>', msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="?surface__exact=y">Vertical</a>', msg_prefix=fail_msg, html=True, ) def test_change_list_null_boolean_display(self): Post.objects.create(public=None) response = self.client.get(reverse("admin:admin_views_post_changelist")) self.assertContains(response, "icon-unknown.svg") def test_display_decorator_with_boolean_and_empty_value(self): msg = ( "The boolean and empty_value arguments to the @display decorator " "are mutually exclusive." ) with self.assertRaisesMessage(ValueError, msg): class BookAdmin(admin.ModelAdmin): @admin.display(boolean=True, empty_value="(Missing)") def is_published(self, obj): return obj.publish_date is not None def test_i18n_language_non_english_default(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English but the selected language is English. See #13388 and #3594 for more details. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("en-us"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "Choisir une heure") def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertContains(response, "Choisir une heure") def test_jsi18n_with_context(self): response = self.client.get(reverse("admin-extra-context:jsi18n")) self.assertEqual(response.status_code, 200) def test_jsi18n_format_fallback(self): """ The JavaScript i18n view doesn't return localized date/time formats when the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="ru"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "%d.%m.%Y %H:%M:%S") self.assertContains(response, "%Y-%m-%d %H:%M:%S") def test_disallowed_filtering(self): with self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): response = self.client.get( "%s?owner__email__startswith=fuzzy" % reverse("admin:admin_views_album_changelist") ) self.assertEqual(response.status_code, 400) # Filters are allowed if explicitly included in list_filter response = self.client.get( "%s?color__value__startswith=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) response = self.client.get( "%s?color__value=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) # Filters should be allowed if they involve a local field without the # need to allow them in list_filter or date_hierarchy. response = self.client.get( "%s?age__gt=30" % reverse("admin:admin_views_person_changelist") ) self.assertEqual(response.status_code, 200) e1 = Employee.objects.create( name="Anonymous", gender=1, age=22, alive=True, code="123" ) e2 = Employee.objects.create( name="Visitor", gender=2, age=19, alive=True, code="124" ) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e1) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e2) response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertContains(response, "employee__person_ptr__exact") response = self.client.get( "%s?employee__person_ptr__exact=%d" % (reverse("admin:admin_views_workhour_changelist"), e1.pk) ) self.assertEqual(response.status_code, 200) def test_disallowed_to_field(self): url = reverse("admin:admin_views_section_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "missing_field"}) self.assertEqual(response.status_code, 400) # Specifying a field that is not referred by any other model registered # to this admin site should raise an exception. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get( reverse("admin:admin_views_section_changelist"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) # Primary key should always be allowed, even if the referenced model # isn't registered. response = self.client.get( reverse("admin:admin_views_notreferenced_changelist"), {TO_FIELD_VAR: "id"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced by another model though a m2m should be # allowed. response = self.client.get( reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced through a reverse m2m relationship # should be allowed. response = self.client.get( reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"} ) self.assertEqual(response.status_code, 200) # Specifying a field that is not referred by any other model directly # registered to this admin site but registered through inheritance # should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyparent_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # Specifying a field that is only referred to by a inline of a # registered model should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyinline_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # #25622 - Specifying a field of a model only referred by a generic # relation should raise DisallowedModelAdminToField. url = reverse("admin:admin_views_referencedbygenrel_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "object_id"}) self.assertEqual(response.status_code, 400) # We also want to prevent the add, change, and delete views from # leaking a disallowed field value. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post( reverse("admin:admin_views_section_add"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) section = Section.objects.create() url = reverse("admin:admin_views_section_change", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) url = reverse("admin:admin_views_section_delete", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) def test_allowed_filtering_15103(self): """ Regressions test for ticket 15103 - filtering on fields defined in a ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields can break. """ # Filters should be allowed if they are defined on a ForeignKey # pointing to this model. url = "%s?leader__name=Palin&leader__age=27" % reverse( "admin:admin_views_inquisition_changelist" ) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_popup_dismiss_related(self): """ Regression test for ticket 20664 - ensure the pk is properly quoted. """ actor = Actor.objects.create(name="Palin", age=27) response = self.client.get( "%s?%s" % (reverse("admin:admin_views_actor_changelist"), IS_POPUP_VAR) ) self.assertContains(response, 'data-popup-opener="%s"' % actor.pk) def test_hide_change_password(self): """ Tests if the "change password" link in the admin is hidden if the User does not have a usable password set. (against 9bea85795705d015cdadc82c68b99196a8554f5c) """ user = User.objects.get(username="super") user.set_unusable_password() user.save() self.client.force_login(user) response = self.client.get(reverse("admin:index")) self.assertNotContains( response, reverse("admin:password_change"), msg_prefix=( 'The "change password" link should not be displayed if a user does not ' "have a usable password." ), ) def test_change_view_with_show_delete_extra_context(self): """ The 'show_delete' context variable in the admin's change view controls the display of the delete button. """ instance = UndeletableObject.objects.create(name="foo") response = self.client.get( reverse("admin:admin_views_undeletableobject_change", args=(instance.pk,)) ) self.assertNotContains(response, "deletelink") def test_change_view_logs_m2m_field_changes(self): """Changes to ManyToManyFields are included in the object's history.""" pizza = ReadablePizza.objects.create(name="Cheese") cheese = Topping.objects.create(name="cheese") post_data = {"name": pizza.name, "toppings": [cheese.pk]} response = self.client.post( reverse("admin:admin_views_readablepizza_change", args=(pizza.pk,)), post_data, ) self.assertRedirects( response, reverse("admin:admin_views_readablepizza_changelist") ) pizza_ctype = ContentType.objects.get_for_model( ReadablePizza, for_concrete_model=False ) log = LogEntry.objects.filter( content_type=pizza_ctype, object_id=pizza.pk ).first() self.assertEqual(log.get_change_message(), "Changed Toppings.") def test_allows_attributeerror_to_bubble_up(self): """ AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there's something to display. Refs: #16655, #18593, and #18747 """ Simple.objects.create() with self.assertRaises(AttributeError): self.client.get(reverse("admin:admin_views_simple_changelist")) def test_changelist_with_no_change_url(self): """ ModelAdmin.changelist_view shouldn't result in a NoReverseMatch if url for change_view is removed from get_urls (#20934). """ o = UnchangeableObject.objects.create() response = self.client.get( reverse("admin:admin_views_unchangeableobject_changelist") ) # Check the format of the shown object -- shouldn't contain a change link self.assertContains( response, '<th class="field-__str__">%s</th>' % o, html=True ) def test_invalid_appindex_url(self): """ #21056 -- URL reversing shouldn't work for nonexistent apps. """ good_url = "/test_admin/admin/admin_views/" confirm_good_url = reverse( "admin:app_list", kwargs={"app_label": "admin_views"} ) self.assertEqual(good_url, confirm_good_url) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", kwargs={"app_label": "this_should_fail"}) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", args=("admin_views2",)) def test_resolve_admin_views(self): index_match = resolve("/test_admin/admin4/") list_match = resolve("/test_admin/admin4/auth/user/") self.assertIs(index_match.func.admin_site, customadmin.simple_site) self.assertIsInstance( list_match.func.model_admin, customadmin.CustomPwdTemplateUserAdmin ) def test_adminsite_display_site_url(self): """ #13749 - Admin should display link to front-end site 'View site' """ url = reverse("admin:index") response = self.client.get(url) self.assertEqual(response.context["site_url"], "/my-site-url/") self.assertContains(response, '<a href="/my-site-url/">View site</a>') def test_date_hierarchy_empty_queryset(self): self.assertIs(Question.objects.exists(), False) response = self.client.get(reverse("admin:admin_views_answer2_changelist")) self.assertEqual(response.status_code, 200) @override_settings(TIME_ZONE="America/Sao_Paulo", USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST. for date in make_aware_datetimes( datetime.datetime(2016, 10, 16, 15), "America/Sao_Paulo" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=16") self.assertContains(response, "question__expires__month=10") self.assertContains(response, "question__expires__year=2016") @override_settings(TIME_ZONE="America/Los_Angeles", USE_TZ=True) def test_date_hierarchy_local_date_differ_from_utc(self): # This datetime is 2017-01-01 in UTC. for date in make_aware_datetimes( datetime.datetime(2016, 12, 31, 16), "America/Los_Angeles" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=31") self.assertContains(response, "question__expires__month=12") self.assertContains(response, "question__expires__year=2016") def test_sortable_by_columns_subset(self): expected_sortable_fields = ("date", "callable_year") expected_not_sortable_fields = ( "content", "model_year", "modeladmin_year", "model_year_reversed", "section", ) response = self.client.get(reverse("admin6:admin_views_article_changelist")) for field_name in expected_sortable_fields: self.assertContains( response, '<th scope="col" class="sortable column-%s">' % field_name ) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) def test_get_sortable_by_columns_subset(self): response = self.client.get(reverse("admin6:admin_views_actor_changelist")) self.assertContains(response, '<th scope="col" class="sortable column-age">') self.assertContains(response, '<th scope="col" class="column-name">') def test_sortable_by_no_column(self): expected_not_sortable_fields = ("title", "book") response = self.client.get(reverse("admin6:admin_views_chapter_changelist")) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) self.assertNotContains(response, '<th scope="col" class="sortable column') def test_get_sortable_by_no_column(self): response = self.client.get(reverse("admin6:admin_views_color_changelist")) self.assertContains(response, '<th scope="col" class="column-value">') self.assertNotContains(response, '<th scope="col" class="sortable column') def test_app_index_context(self): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) self.assertEqual(response.context["title"], "Admin_Views administration") self.assertEqual(response.context["app_label"], "admin_views") # Models are sorted alphabetically by default. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models)) def test_app_index_context_reordered(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) # Models are in reverse order. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models, reverse=True)) def test_change_view_subtitle_per_object(self): response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_view_subtitle_per_object(self): viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True, ) viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", Article._meta)), ) self.client.force_login(viewuser) response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_formset_kwargs_can_be_overridden(self): response = self.client.get(reverse("admin:admin_views_city_add")) self.assertContains(response, "overridden_name") def test_render_views_no_subtitle(self): tests = [ reverse("admin:index"), reverse("admin:password_change"), reverse("admin:app_list", args=("admin_views",)), reverse("admin:admin_views_article_delete", args=(self.a1.pk,)), reverse("admin:admin_views_article_history", args=(self.a1.pk,)), ] for url in tests: with self.subTest(url=url): with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) # Login must be after logout. with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:logout")) self.client.get(reverse("admin:login")) def test_render_delete_selected_confirmation_no_subtitle(self): post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": self.a1.pk, } with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:admin_views_article_changelist"), post_data) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ] ) def test_password_change_helptext(self): response = self.client.get(reverse("admin:password_change")) self.assertContains( response, '<div class="help" id="id_new_password1_helptext">' ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ], TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", # Put this app's and the shared tests templates dirs in DIRS to # take precedence over the admin's templates dir. "DIRS": [ os.path.join(os.path.dirname(__file__), "templates"), os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminCustomTemplateTests(AdminViewBasicTestCase): def test_custom_model_admin_templates(self): # Test custom change list template with custom extra context response = self.client.get( reverse("admin:admin_views_customarticle_changelist") ) self.assertContains(response, "var hello = 'Hello!';") self.assertTemplateUsed(response, "custom_admin/change_list.html") # Test custom add form template response = self.client.get(reverse("admin:admin_views_customarticle_add")) self.assertTemplateUsed(response, "custom_admin/add_form.html") # Add an article so we can test delete, change, and history views post = self.client.post( reverse("admin:admin_views_customarticle_add"), { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", }, ) self.assertRedirects( post, reverse("admin:admin_views_customarticle_changelist") ) self.assertEqual(CustomArticle.objects.count(), 1) article_pk = CustomArticle.objects.all()[0].pk # Test custom delete, change, and object history templates # Test custom change form template response = self.client.get( reverse("admin:admin_views_customarticle_change", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/change_form.html") response = self.client.get( reverse("admin:admin_views_customarticle_delete", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/delete_confirmation.html") response = self.client.post( reverse("admin:admin_views_customarticle_changelist"), data={ "index": 0, "action": ["delete_selected"], "_selected_action": ["1"], }, ) self.assertTemplateUsed( response, "custom_admin/delete_selected_confirmation.html" ) response = self.client.get( reverse("admin:admin_views_customarticle_history", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/object_history.html") # A custom popup response template may be specified by # ModelAdmin.popup_response_template. response = self.client.post( reverse("admin:admin_views_customarticle_add") + "?%s=1" % IS_POPUP_VAR, { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", IS_POPUP_VAR: "1", }, ) self.assertEqual(response.template_name, "custom_admin/popup_response.html") def test_extended_bodyclass_template_change_form(self): """ The admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "bodyclass_consistency_check ") def test_change_password_template(self): user = User.objects.get(username="super") response = self.client.get( reverse("admin:auth_user_password_change", args=(user.id,)) ) # The auth/user/change_password.html template uses super in the # bodyclass block. self.assertContains(response, "bodyclass_consistency_check ") # When a site has multiple passwords in the browser's password manager, # a browser pop up asks which user the new password is for. To prevent # this, the username is added to the change password form. self.assertContains( response, '<input type="text" name="username" value="super" class="hidden">' ) # help text for passwords has an id. self.assertContains( response, '<div class="help" id="id_password1_helptext"><ul><li>' "Your password can’t be too similar to your other personal information." "</li><li>Your password can’t be entirely numeric.</li></ul></div>", ) self.assertContains( response, '<div class="help" id="id_password2_helptext">' "Enter the same password as before, for verification.</div>", ) def test_extended_bodyclass_template_index(self): """ The admin/index.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:index")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_change_list(self): """ The admin/change_list.html' template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_login(self): """ The admin/login.html template uses block.super in the bodyclass block. """ self.client.logout() response = self.client.get(reverse("admin:login")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_confirmation(self): """ The admin/delete_confirmation.html template uses block.super in the bodyclass block. """ group = Group.objects.create(name="foogroup") response = self.client.get(reverse("admin:auth_group_delete", args=(group.id,))) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_selected_confirmation(self): """ The admin/delete_selected_confirmation.html template uses block.super in bodyclass block. """ group = Group.objects.create(name="foogroup") post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": group.id, } response = self.client.post(reverse("admin:auth_group_changelist"), post_data) self.assertEqual(response.context["site_header"], "Django administration") self.assertContains(response, "bodyclass_consistency_check ") def test_filter_with_custom_template(self): """ A custom template can be used to render an admin filter. """ response = self.client.get(reverse("admin:admin_views_color2_changelist")) self.assertTemplateUsed(response, "custom_filter_template.html") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewFormUrlTest(TestCase): current_app = "admin3" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_change_form_URL_has_correct_value(self): """ change_view has form_url in response.context """ response = self.client.get( reverse( "admin:admin_views_section_change", args=(self.s1.pk,), current_app=self.current_app, ) ) self.assertIn( "form_url", response.context, msg="form_url not present in response.context" ) self.assertEqual(response.context["form_url"], "pony") def test_initial_data_can_be_overridden(self): """ The behavior for setting initial form data can be overridden in the ModelAdmin class. Usually, the initial value is set via the GET params. """ response = self.client.get( reverse("admin:admin_views_restaurant_add", current_app=self.current_app), {"name": "test_value"}, ) # this would be the usual behaviour self.assertNotContains(response, 'value="test_value"') # this is the overridden behaviour self.assertContains(response, 'value="overridden_value"') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_js_minified_only_if_debug_is_false(self): """ The minified versions of the JS files are only used when DEBUG is False. """ with override_settings(DEBUG=False): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertNotContains(response, "vendor/jquery/jquery.js") self.assertContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") with override_settings(DEBUG=True): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "vendor/jquery/jquery.js") self.assertNotContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") @override_settings(ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_as_duplication(self): """'save as' creates a new person""" post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), post_data ) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) new_person = Person.objects.latest("id") self.assertRedirects( response, reverse("admin:admin_views_person_change", args=(new_person.pk,)) ) def test_save_as_continue_false(self): """ Saving a new object using "Save as new" redirects to the changelist instead of the change view when ModelAdmin.save_as_continue=False. """ post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} url = reverse( "admin:admin_views_person_change", args=(self.per1.pk,), current_app=site2.name, ) response = self.client.post(url, post_data) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) self.assertRedirects( response, reverse("admin:admin_views_person_changelist", current_app=site2.name), ) def test_save_as_new_with_validation_errors(self): """ When you click "Save as new" and have a validation error, you only see the "Save as new" button and not the other save buttons, and that only the "Save as" button is visible. """ response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), { "_saveasnew": "", "gender": "invalid", "_addanother": "fail", }, ) self.assertContains(response, "Please correct the errors below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_validation_errors_with_inlines(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "Child", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "_invalid", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_inlines_with_validation_errors(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "_invalid", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "Father", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) @override_settings(ROOT_URLCONF="admin_views.urls") class CustomModelAdminTest(AdminViewBasicTestCase): def test_custom_admin_site_login_form(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post( reverse("admin2:login"), { REDIRECT_FIELD_NAME: reverse("admin2:index"), "username": "customform", "password": "secret", }, follow=True, ) self.assertIsInstance(login, TemplateResponse) self.assertContains(login, "custom form error") self.assertContains(login, "path/to/media.css") def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/login.html") self.assertContains(response, "Hello from a custom login template") def test_custom_admin_site_logout_template(self): response = self.client.post(reverse("admin2:logout")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/logout.html") self.assertContains(response, "Hello from a custom logout template") def test_custom_admin_site_index_view_and_template(self): response = self.client.get(reverse("admin2:index")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/index.html") self.assertContains(response, "Hello from a custom index template *bar*") def test_custom_admin_site_app_index_view_and_template(self): response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/app_index.html") self.assertContains(response, "Hello from a custom app_index template") def test_custom_admin_site_password_change_template(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains( response, "Hello from a custom password change form template" ) def test_custom_admin_site_password_change_with_extra_context(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains(response, "eggs") def test_custom_admin_site_password_change_done_template(self): response = self.client.get(reverse("admin2:password_change_done")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_done.html") self.assertContains( response, "Hello from a custom password change done template" ) def test_custom_admin_site_view(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:my_view")) self.assertEqual(response.content, b"Django is a magical pony!") def test_pwd_change_custom_template(self): self.client.force_login(self.superuser) su = User.objects.get(username="super") response = self.client.get( reverse("admin4:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 200) def get_perm(Model, codename): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model, for_concrete_model=False) return Permission.objects.get(content_type=ct, codename=codename) @override_settings( ROOT_URLCONF="admin_views.urls", # Test with the admin's documented list of required context processors. TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.nostaffuser = User.objects.create_user( username="nostaff", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, another_section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) # Setup permissions, for our users who can add, change, and delete. opts = Article._meta # User who can view Articles cls.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", opts)) ) # User who can add Articles cls.adduser.user_permissions.add( get_perm(Article, get_permission_codename("add", opts)) ) # User who can change Articles cls.changeuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) cls.nostaffuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) # User who can delete Articles cls.deleteuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", opts)) ) cls.deleteuser.user_permissions.add( get_perm(Section, get_permission_codename("delete", Section._meta)) ) # login POST dicts cls.index_url = reverse("admin:index") cls.super_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super", "password": "secret", } cls.super_email_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "secret", } cls.super_email_bad_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "notsecret", } cls.adduser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "adduser", "password": "secret", } cls.changeuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "changeuser", "password": "secret", } cls.deleteuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "deleteuser", "password": "secret", } cls.nostaff_login = { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "nostaff", "password": "secret", } cls.joepublic_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "joepublic", "password": "secret", } cls.viewuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "viewuser", "password": "secret", } cls.no_username_login = { REDIRECT_FIELD_NAME: cls.index_url, "password": "secret", } def test_login(self): """ Make sure only staff members can log in. Successful posts to the login page will redirect to the original url. Unsuccessful attempts will continue to render the login page with a 200 status code. """ login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) # Super User response = self.client.get(self.index_url) self.assertRedirects(response, login_url) login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Test if user enters email address response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # only correct passwords get a username hint login = self.client.post(login_url, self.super_email_bad_login) self.assertContains(login, ERROR_MESSAGE) new_user = User(username="jondoe", password="secret", email="[email protected]") new_user.save() # check to ensure if there are multiple email addresses a user doesn't get a 500 login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # View User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.viewuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Add User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.adduser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Change User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.changeuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Delete User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.deleteuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Regular User should not be able to login. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Requests without username should not return 500 errors. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.no_username_login) self.assertEqual(login.status_code, 200) self.assertFormError( login.context["form"], "username", ["This field is required."] ) def test_login_redirect_for_direct_get(self): """ Login redirect should be to the admin index page when going directly to /admin/login/. """ response = self.client.get(reverse("admin:login")) self.assertEqual(response.status_code, 200) self.assertEqual(response.context[REDIRECT_FIELD_NAME], reverse("admin:index")) def test_login_has_permission(self): # Regular User should not be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.joepublic_login ) self.assertContains(login, "permission denied") # User with permissions should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.nostaff_login ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) # Staff should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "deleteuser", "password": "secret", }, ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) def test_login_successfully_redirects_to_original_URL(self): response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) query_string = "the-answer=42" redirect_url = "%s?%s" % (self.index_url, query_string) new_next = {REDIRECT_FIELD_NAME: redirect_url} post_data = self.super_login.copy() post_data.pop(REDIRECT_FIELD_NAME) login = self.client.post( "%s?%s" % (reverse("admin:login"), urlencode(new_next)), post_data ) self.assertRedirects(login, redirect_url) def test_double_login_is_not_allowed(self): """Regression test for #19327""" login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with admin user while already logged in login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) def test_login_page_notice_for_non_staff_users(self): """ A logged-in non-staff user trying to access the admin index should be presented with the login page and a hint indicating that the current user doesn't have access to it. """ hint_template = "You are authenticated as {}" # Anonymous user should not be shown the hint response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertNotContains(response, hint_template.format(""), status_code=200) # Non-staff user should be shown the hint self.client.force_login(self.nostaffuser) response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertContains( response, hint_template.format(self.nostaffuser.username), status_code=200 ) def test_add_view(self): """Test add view restricts access and actually adds items.""" add_dict = { "title": "Døm ikke", "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.post(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "<title>Add article | Django site admin</title>") self.assertContains( response, '<input type="submit" value="Save and view" name="_continue">' ) post = self.client.post( reverse("admin:admin_views_article_add"), add_dict, follow=False ) self.assertEqual(post.status_code, 302) self.assertEqual(Article.objects.count(), 4) article = Article.objects.latest("pk") response = self.client.get( reverse("admin:admin_views_article_change", args=(article.pk,)) ) self.assertContains( response, '<li class="success">The article “Døm ikke” was added successfully.</li>', ) article.delete() self.client.post(reverse("admin:logout")) # Add user may login and POST to add view, then redirect to admin root self.client.force_login(self.adduser) addpage = self.client.get(reverse("admin:admin_views_article_add")) change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse( "admin:admin_views_article_changelist" ) self.assertNotContains( addpage, change_list_link, msg_prefix=( "User restricted to add permission is given link to change list view " "in breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "Greetings from a created object") self.client.post(reverse("admin:logout")) # The addition was logged correctly addition_log = LogEntry.objects.all()[0] new_article = Article.objects.last() article_ct = ContentType.objects.get_for_model(Article) self.assertEqual(addition_log.user_id, self.adduser.pk) self.assertEqual(addition_log.content_type_id, article_ct.pk) self.assertEqual(addition_log.object_id, str(new_article.pk)) self.assertEqual(addition_log.object_repr, "Døm ikke") self.assertEqual(addition_log.action_flag, ADDITION) self.assertEqual(addition_log.get_change_message(), "Added.") # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse("admin:admin_views_article_add")) self.assertContains( addpage, change_list_link, msg_prefix=( "Unrestricted user is not given link to change list view in " "breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, reverse("admin:admin_views_article_changelist")) self.assertEqual(Article.objects.count(), 5) self.client.post(reverse("admin:logout")) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.force_login(self.joepublicuser) # Check and make sure that if user expires, data still persists self.client.force_login(self.superuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) @mock.patch("django.contrib.admin.options.InlineModelAdmin.has_change_permission") def test_add_view_with_view_only_inlines(self, has_change_permission): """User with add permission to a section but view-only for inlines.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("add", Section._meta)) ) self.client.force_login(self.viewuser) # Valid POST creates a new section. data = { "name": "New obj", "article_set-TOTAL_FORMS": 0, "article_set-INITIAL_FORMS": 0, } response = self.client.post(reverse("admin:admin_views_section_add"), data) self.assertRedirects(response, reverse("admin:index")) self.assertEqual(Section.objects.latest("id").name, data["name"]) # InlineModelAdmin.has_change_permission()'s obj argument is always # None during object add. self.assertEqual( [obj for (request, obj), _ in has_change_permission.call_args_list], [None, None], ) def test_change_view(self): """Change view should restrict access and allow users to edit items.""" change_dict = { "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) article_changelist_url = reverse("admin:admin_views_article_changelist") # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get(article_changelist_url) self.assertEqual(response.status_code, 403) response = self.client.get(article_change_url) self.assertEqual(response.status_code, 403) post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.assertContains( response, "<title>Select article to view | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to view</h1>") self.assertEqual(response.context["title"], "Select article to view") response = self.client.get(article_change_url) self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<label>Extra form field:</label>") self.assertContains( response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close' "</a>", ) self.assertEqual(response.context["title"], "View article") post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>Middle content</p>" ) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get(article_changelist_url) self.assertEqual(response.context["title"], "Select article to change") self.assertContains( response, "<title>Select article to change | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to change</h1>") response = self.client.get(article_change_url) self.assertEqual(response.context["title"], "Change article") self.assertContains( response, "<title>Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") post = self.client.post(article_change_url, change_dict) self.assertRedirects(post, article_changelist_url) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>edited article</p>" ) # one error in form should produce singular error message, multiple # errors plural. change_dict["title"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the error below.", msg_prefix=( "Singular error message not found in response to post with one error" ), ) change_dict["content"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the errors below.", msg_prefix=( "Plural error message not found in response to post with multiple " "errors" ), ) self.client.post(reverse("admin:logout")) # Test redirection when using row-level change permissions. Refs #11513. r1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") r2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") r3 = RowLevelChangePermissionModel.objects.create(id=3, name="odd id mult 3") r6 = RowLevelChangePermissionModel.objects.create(id=6, name="even id mult 3") change_url_1 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r1.pk,) ) change_url_2 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r2.pk,) ) change_url_3 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r3.pk,) ) change_url_6 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r6.pk,) ) logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1) self.assertEqual(response.status_code, 403) response = self.client.post(change_url_1, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertEqual(response.status_code, 403) response = self.client.get(change_url_2) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_2, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertRedirects(response, self.index_url) response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {"name": "changed"}) self.assertEqual(response.status_code, 403) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=3).name, "odd id mult 3", ) response = self.client.get(change_url_6) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_6, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=6).name, "changed" ) self.assertRedirects(response, self.index_url) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_1, {"name": "changed"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertContains(response, "login-form") response = self.client.get(change_url_2, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_2, {"name": "changed again"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_change_view_without_object_change_permission(self): """ The object should be read-only if the user has permission to view it and change objects of that type but not to change the current object. """ change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(self.viewuser) response = self.client.get(change_url) self.assertEqual(response.context["title"], "View article") self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains( response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close' "</a>", ) def test_change_view_save_as_new(self): """ 'Save as new' should raise PermissionDenied for users without the 'add' permission. """ change_dict_save_as_new = { "_saveasnew": "Save as new", "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) # Add user can perform "Save as new". article_count = Article.objects.count() self.client.force_login(self.adduser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), article_count + 1) self.client.logout() # Change user cannot perform "Save as new" (no 'add' permission). article_count = Article.objects.count() self.client.force_login(self.changeuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), article_count) # User with both add and change permissions should be redirected to the # change page for the newly created object. article_count = Article.objects.count() self.client.force_login(self.superuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(Article.objects.count(), article_count + 1) new_article = Article.objects.latest("id") self.assertRedirects( post, reverse("admin:admin_views_article_change", args=(new_article.pk,)) ) def test_change_view_with_view_only_inlines(self): """ User with change permission to a section but view-only for inlines. """ self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # Valid POST changes the name. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 3, "article_set-INITIAL_FORMS": 3, } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) def test_change_view_with_view_only_last_inline(self): self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("view", Section._meta)) ) self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # The last inline is not marked as empty. self.assertContains(response, 'id="article_set-2"') def test_change_view_with_view_and_add_inlines(self): """User has view and add permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) # Valid POST creates a new article. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-3-id": [""], "article_set-3-title": ["A title"], "article_set-3-content": ["Added content"], "article_set-3-date_0": ["2008-3-18"], "article_set-3-date_1": ["11:54:58"], "article_set-3-section": [str(self.s1.pk)], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) self.assertEqual(Article.objects.count(), 4) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) def test_change_view_with_view_and_delete_inlines(self): """User has view and delete permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } # Inline POST details are ignored without delete permission. response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 3) # Deletion successful when delete permission is added. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", Article._meta)) ) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 2) def test_delete_view(self): """Delete view should restrict access and actually delete items.""" delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_article_delete", args=(self.a1.pk,)) # add user should not be able to delete articles self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # view user should not be able to delete articles self.client.force_login(self.viewuser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # Delete user can delete self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 3</li>") # test response contains link to related Article self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) response = self.client.get(delete_url) self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 1</li>") post = self.client.post(delete_url, delete_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a deleted object") article_ct = ContentType.objects.get_for_model(Article) logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION) self.assertEqual(logged.object_id, str(self.a1.pk)) def test_delete_view_with_no_default_permissions(self): """ The delete view allows users to delete collected objects without a 'delete' permission (ReadOnlyPizza.Meta.default_permissions is empty). """ pizza = ReadOnlyPizza.objects.create(name="Double Cheese") delete_url = reverse("admin:admin_views_readonlypizza_delete", args=(pizza.pk,)) self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertContains(response, "admin_views/readonlypizza/%s/" % pizza.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Read only pizzas: 1</li>") post = self.client.post(delete_url, {"post": "yes"}) self.assertRedirects( post, reverse("admin:admin_views_readonlypizza_changelist") ) self.assertEqual(ReadOnlyPizza.objects.count(), 0) def test_delete_view_nonexistent_obj(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_article_delete", args=("nonexistent",)) response = self.client.get(url, follow=True) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “nonexistent” doesn’t exist. Perhaps it was deleted?"], ) def test_history_view(self): """History view should restrict access.""" # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view all items self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) # Test redirection when using row-level change permissions. Refs #11513. rl1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") rl2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 403) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_history_view_bad_url(self): self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=("foo",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “foo” doesn’t exist. Perhaps it was deleted?"], ) def test_conditionally_show_add_section_link(self): """ The foreign key widget should only show the "add related" button if the user has permission to add that related item. """ self.client.force_login(self.adduser) # The user can't add sections yet, so they shouldn't see the "add section" link. url = reverse("admin:admin_views_article_add") add_link_text = "add_id_section" response = self.client.get(url) self.assertNotContains(response, add_link_text) # Allow the user to add sections too. Now they can see the "add section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("add", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertContains(response, add_link_text) def test_conditionally_show_change_section_link(self): """ The foreign key widget should only show the "change related" button if the user has permission to change that related item. """ def get_change_related(response): return ( response.context["adminform"] .form.fields["section"] .widget.can_change_related ) self.client.force_login(self.adduser) # The user can't change sections yet, so they shouldn't see the # "change section" link. url = reverse("admin:admin_views_article_add") change_link_text = "change_id_section" response = self.client.get(url) self.assertFalse(get_change_related(response)) self.assertNotContains(response, change_link_text) # Allow the user to change sections too. Now they can see the # "change section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("change", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_change_related(response)) self.assertContains(response, change_link_text) def test_conditionally_show_delete_section_link(self): """ The foreign key widget should only show the "delete related" button if the user has permission to delete that related item. """ def get_delete_related(response): return ( response.context["adminform"] .form.fields["sub_section"] .widget.can_delete_related ) self.client.force_login(self.adduser) # The user can't delete sections yet, so they shouldn't see the # "delete section" link. url = reverse("admin:admin_views_article_add") delete_link_text = "delete_id_sub_section" response = self.client.get(url) self.assertFalse(get_delete_related(response)) self.assertNotContains(response, delete_link_text) # Allow the user to delete sections too. Now they can see the # "delete section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("delete", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_delete_related(response)) self.assertContains(response, delete_link_text) def test_disabled_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_active = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_disabled_staff_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_staff = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_app_list_permissions(self): """ If a user has no module perms, the app list returns a 404. """ opts = Article._meta change_user = User.objects.get(username="changeuser") permission = get_perm(Article, get_permission_codename("change", opts)) self.client.force_login(self.changeuser) # the user has no module permissions change_user.user_permissions.remove(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 404) # the user now has module permissions change_user.user_permissions.add(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 200) def test_shortcut_view_only_available_to_staff(self): """ Only admin users should be able to use the admin shortcut view. """ model_ctype = ContentType.objects.get_for_model(ModelWithStringPrimaryKey) obj = ModelWithStringPrimaryKey.objects.create(string_pk="foo") shortcut_url = reverse("admin:view_on_site", args=(model_ctype.pk, obj.pk)) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") # Logged in? Redirect. self.client.force_login(self.superuser) response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) # Domain may depend on contrib.sites tests also run self.assertRegex(response.url, "http://(testserver|example.com)/dummy/foo/") def test_has_module_permission(self): """ has_module_permission() returns True for all users who have any permission for that module (add, change, or delete), so that the module is displayed on the admin index page. """ self.client.force_login(self.superuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.adduser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") def test_overriding_has_module_permission(self): """ If has_module_permission() always returns False, the module shouldn't be displayed on the admin index page for any users. """ articles = Article._meta.verbose_name_plural.title() sections = Section._meta.verbose_name_plural.title() index_url = reverse("admin7:index") self.client.force_login(self.superuser) response = self.client.get(index_url) self.assertContains(response, sections) self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.adduser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(index_url) self.assertNotContains(response, articles) # The app list displays Sections but not Articles as the latter has # ModelAdmin.has_module_permission() = False. self.client.force_login(self.superuser) response = self.client.get(reverse("admin7:app_list", args=("admin_views",))) self.assertContains(response, sections) self.assertNotContains(response, articles) def test_post_save_message_no_forbidden_links_visible(self): """ Post-save message shouldn't contain a link to the change form if the user doesn't have the change permission. """ self.client.force_login(self.adduser) # Emulate Article creation for user with add-only permission. post_data = { "title": "Fun & games", "content": "Some content", "date_0": "2015-10-31", "date_1": "16:35:00", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_article_add"), post_data, follow=True ) self.assertContains( response, '<li class="success">The article “Fun &amp; games” was added successfully.' "</li>", html=True, ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewProxyModelPermissionsTests(TestCase): """Tests for proxy models permissions in the admin.""" @classmethod def setUpTestData(cls): cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) # Setup permissions. opts = UserProxy._meta cls.viewuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("view", opts)) ) cls.adduser.user_permissions.add( get_perm(UserProxy, get_permission_codename("add", opts)) ) cls.changeuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("change", opts)) ) cls.deleteuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("delete", opts)) ) # UserProxy instances. cls.user_proxy = UserProxy.objects.create( username="user_proxy", password="secret" ) def test_add(self): self.client.force_login(self.adduser) url = reverse("admin:admin_views_userproxy_add") data = { "username": "can_add", "password": "secret", "date_joined_0": "2019-01-15", "date_joined_1": "16:59:10", } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertTrue(UserProxy.objects.filter(username="can_add").exists()) def test_view(self): self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_userproxy_changelist")) self.assertContains(response, "<h1>Select user proxy to view</h1>") response = self.client.get( reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) ) self.assertContains(response, "<h1>View user proxy</h1>") self.assertContains(response, '<div class="readonly">user_proxy</div>') def test_change(self): self.client.force_login(self.changeuser) data = { "password": self.user_proxy.password, "username": self.user_proxy.username, "date_joined_0": self.user_proxy.date_joined.strftime("%Y-%m-%d"), "date_joined_1": self.user_proxy.date_joined.strftime("%H:%M:%S"), "first_name": "first_name", } url = reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) response = self.client.post(url, data) self.assertRedirects( response, reverse("admin:admin_views_userproxy_changelist") ) self.assertEqual( UserProxy.objects.get(pk=self.user_proxy.pk).first_name, "first_name" ) def test_delete(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_userproxy_delete", args=(self.user_proxy.pk,)) response = self.client.post(url, {"post": "yes"}, follow=True) self.assertEqual(response.status_code, 200) self.assertFalse(UserProxy.objects.filter(pk=self.user_proxy.pk).exists()) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewsNoUrlTest(TestCase): """Regression test for #17333""" @classmethod def setUpTestData(cls): # User who can change Reports cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.changeuser.user_permissions.add( get_perm(Report, get_permission_codename("change", Report._meta)) ) def test_no_standard_modeladmin_urls(self): """Admin index views don't break when user's ModelAdmin removes standard urls""" self.client.force_login(self.changeuser) r = self.client.get(reverse("admin:index")) # we shouldn't get a 500 error caused by a NoReverseMatch self.assertEqual(r.status_code, 200) self.client.post(reverse("admin:logout")) @skipUnlessDBFeature("can_defer_constraint_checks") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewDeletedObjectsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.v1 = Villain.objects.create(name="Adam") cls.v2 = Villain.objects.create(name="Sue") cls.sv1 = SuperVillain.objects.create(name="Bob") cls.pl1 = Plot.objects.create( name="World Domination", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name="World Peace", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details="almost finished", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location="underground bunker", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location="floating castle", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location="super floating castle!", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(pk=1, name="I am recursive", two_id=1) cls.cy2 = CyclicTwo.objects.create(pk=1, name="I am recursive too", one_id=1) def setUp(self): self.client.force_login(self.superuser) def test_nesting(self): """ Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ pattern = re.compile( r'<li>Plot: <a href="%s">World Domination</a>\s*<ul>\s*' r'<li>Plot details: <a href="%s">almost finished</a>' % ( reverse("admin:admin_views_plot_change", args=(self.pl1.pk,)), reverse("admin:admin_views_plotdetails_change", args=(self.pd1.pk,)), ) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertRegex(response.content.decode(), pattern) def test_cyclic(self): """ Cyclic relationships should still cause each object to only be listed once. """ one = '<li>Cyclic one: <a href="%s">I am recursive</a>' % ( reverse("admin:admin_views_cyclicone_change", args=(self.cy1.pk,)), ) two = '<li>Cyclic two: <a href="%s">I am recursive too</a>' % ( reverse("admin:admin_views_cyclictwo_change", args=(self.cy2.pk,)), ) response = self.client.get( reverse("admin:admin_views_cyclicone_delete", args=(self.cy1.pk,)) ) self.assertContains(response, one, 1) self.assertContains(response, two, 1) def test_perms_needed(self): self.client.logout() delete_user = User.objects.get(username="deleteuser") delete_user.user_permissions.add( get_perm(Plot, get_permission_codename("delete", Plot._meta)) ) self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(self.pl1.pk,)) ) self.assertContains( response, "your account doesn't have permission to delete the following types of " "objects", ) self.assertContains(response, "<li>plot details</li>") def test_protected(self): q = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q, answer="Because.") a2 = Answer.objects.create(question=q, answer="Yes.") response = self.client.get( reverse("admin:admin_views_question_delete", args=(q.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects" ) self.assertContains( response, '<li>Answer: <a href="%s">Because.</a></li>' % reverse("admin:admin_views_answer_change", args=(a1.pk,)), ) self.assertContains( response, '<li>Answer: <a href="%s">Yes.</a></li>' % reverse("admin:admin_views_answer_change", args=(a2.pk,)), ) def test_post_delete_protected(self): """ A POST request to delete protected objects should display the page which says the deletion is prohibited. """ q = Question.objects.create(question="Why?") Answer.objects.create(question=q, answer="Because.") response = self.client.post( reverse("admin:admin_views_question_delete", args=(q.pk,)), {"post": "yes"} ) self.assertEqual(Question.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects" ) def test_restricted(self): album = Album.objects.create(title="Amaryllis") song = Song.objects.create(album=album, name="Unity") response = self.client.get( reverse("admin:admin_views_album_delete", args=(album.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects", ) self.assertContains( response, '<li>Song: <a href="%s">Unity</a></li>' % reverse("admin:admin_views_song_change", args=(song.pk,)), ) def test_post_delete_restricted(self): album = Album.objects.create(title="Amaryllis") Song.objects.create(album=album, name="Unity") response = self.client.post( reverse("admin:admin_views_album_delete", args=(album.pk,)), {"post": "yes"}, ) self.assertEqual(Album.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects", ) def test_not_registered(self): should_contain = """<li>Secret hideout: underground bunker""" response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain, 1) def test_multiple_fkeys_to_same_model(self): """ If a deleted object has two relationships from another model, both of those should be followed in looking for related objects to delete. """ should_contain = '<li>Plot: <a href="%s">World Domination</a>' % reverse( "admin:admin_views_plot_change", args=(self.pl1.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain) def test_multiple_fkeys_to_same_instance(self): """ If a deleted object has two relationships pointing to it from another object, the other object should still only be listed once. """ should_contain = '<li>Plot: <a href="%s">World Peace</a></li>' % reverse( "admin:admin_views_plot_change", args=(self.pl2.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain, 1) def test_inheritance(self): """ In the case of an inherited model, if either the child or parent-model instance is deleted, both instances are listed for deletion, as well as any relationships they have. """ should_contain = [ '<li>Villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_villain_change", args=(self.sv1.pk,)), '<li>Super villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_supervillain_change", args=(self.sv1.pk,)), "<li>Secret hideout: floating castle", "<li>Super secret hideout: super floating castle!", ] response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) response = self.client.get( reverse("admin:admin_views_supervillain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) def test_generic_relations(self): """ If a deleted object has GenericForeignKeys pointing to it, those objects should be listed for deletion. """ plot = self.pl3 tag = FunkyTag.objects.create(content_object=plot, name="hott") should_contain = '<li>Funky tag: <a href="%s">hott' % reverse( "admin:admin_views_funkytag_change", args=(tag.id,) ) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(plot.pk,)) ) self.assertContains(response, should_contain) def test_generic_relations_with_related_query_name(self): """ If a deleted object has GenericForeignKey with GenericRelation(related_query_name='...') pointing to it, those objects should be listed for deletion. """ bookmark = Bookmark.objects.create(name="djangoproject") tag = FunkyTag.objects.create(content_object=bookmark, name="django") tag_url = reverse("admin:admin_views_funkytag_change", args=(tag.id,)) should_contain = '<li>Funky tag: <a href="%s">django' % tag_url response = self.client.get( reverse("admin:admin_views_bookmark_delete", args=(bookmark.pk,)) ) self.assertContains(response, should_contain) def test_delete_view_uses_get_deleted_objects(self): """The delete view uses ModelAdmin.get_deleted_objects().""" book = Book.objects.create(name="Test Book") response = self.client.get( reverse("admin2:admin_views_book_delete", args=(book.pk,)) ) # BookAdmin.get_deleted_objects() returns custom text. self.assertContains(response, "a deletable object") @override_settings(ROOT_URLCONF="admin_views.urls") class TestGenericRelations(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.v1 = Villain.objects.create(name="Adam") cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) def setUp(self): self.client.force_login(self.superuser) def test_generic_content_object_in_list_display(self): FunkyTag.objects.create(content_object=self.pl3, name="hott") response = self.client.get(reverse("admin:admin_views_funkytag_changelist")) self.assertContains(response, "%s</td>" % self.pl3) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewStringPrimaryKeyTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.pk = ( "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " r"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" ) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) content_type_pk = ContentType.objects.get_for_model( ModelWithStringPrimaryKey ).pk user_pk = cls.superuser.pk LogEntry.objects.log_action( user_pk, content_type_pk, cls.pk, cls.pk, 2, change_message="Changed something", ) def setUp(self): self.client.force_login(self.superuser) def test_get_history_view(self): """ Retrieving the history for an object using urlencoded form of primary key should work. Refs #12349, #18550. """ response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_history", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) self.assertContains(response, "Changed something") def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) def test_changelist_to_changeform_link(self): """ Link to the changeform of the object in changelist should use reverse() and be quoted. """ response = self.client.get( reverse("admin:admin_views_modelwithstringprimarykey_changelist") ) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding pk_final_url = escape(iri_to_uri(quote(self.pk))) change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", pk_final_url) should_contain = '<th class="field-__str__"><a href="%s">%s</a></th>' % ( change_url, escape(self.pk), ) self.assertContains(response, should_contain) def test_recentactions_link(self): """ The link from the recent actions list referring to the changeform of the object should be quoted. """ response = self.client.get(reverse("admin:index")) link = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(self.pk),) ) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(self.pk)) self.assertContains(response, should_contain) def test_deleteconfirmation_link(self): """ " The link from the delete confirmation page referring back to the changeform of the object should be quoted. """ url = reverse( "admin:admin_views_modelwithstringprimarykey_delete", args=(quote(self.pk),) ) response = self.client.get(url) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", escape(iri_to_uri(quote(self.pk)))) should_contain = '<a href="%s">%s</a>' % (change_url, escape(self.pk)) self.assertContains(response, should_contain) def test_url_conflicts_with_add(self): "A model with a primary key that ends with add or is `add` should be visible" add_model = ModelWithStringPrimaryKey.objects.create( pk="i have something to add" ) add_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) add_model2 = ModelWithStringPrimaryKey.objects.create(pk="add") add_url = reverse("admin:admin_views_modelwithstringprimarykey_add") change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model2.pk),), ) self.assertNotEqual(add_url, change_url) def test_url_conflicts_with_delete(self): "A model with a primary key that ends with delete should be visible" delete_model = ModelWithStringPrimaryKey(pk="delete") delete_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(delete_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_url_conflicts_with_history(self): "A model with a primary key that ends with history should be visible" history_model = ModelWithStringPrimaryKey(pk="history") history_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(history_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_shortcut_view_with_escaping(self): "'View on site should' work properly with char fields" model = ModelWithStringPrimaryKey(pk="abc_123") model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(model.pk),), ) ) should_contain = '/%s/" class="viewsitelink">' % model.pk self.assertContains(response, should_contain) def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" url = reverse( "admin:%s_modelwithstringprimarykey_change" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected_link = reverse( "admin:%s_modelwithstringprimarykey_history" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) self.assertContains( response, '<a href="%s" class="historylink"' % escape(expected_link) ) def test_redirect_on_add_view_continue_button(self): """As soon as an object is added using "Save and continue editing" button, the user should be redirected to the object's change_view. In case primary key is a string containing some special characters like slash or underscore, these characters must be escaped (see #22266) """ response = self.client.post( reverse("admin:admin_views_modelwithstringprimarykey_add"), { "string_pk": "123/history", "_continue": "1", # Save and continue editing }, ) self.assertEqual(response.status_code, 302) # temporary redirect self.assertIn("/123_2Fhistory/", response.headers["location"]) # PK is quoted @override_settings(ROOT_URLCONF="admin_views.urls") class SecureViewTests(TestCase): """ Test behavior of a view protected by the staff_member_required decorator. """ def test_secure_view_shows_login_if_not_logged_in(self): secure_url = reverse("secure_view") response = self.client.get(secure_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), secure_url) ) response = self.client.get(secure_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.context[REDIRECT_FIELD_NAME], secure_url) def test_staff_member_required_decorator_works_with_argument(self): """ Staff_member_required decorator works with an argument (redirect_field_name). """ secure_url = "/test_admin/admin/secure-view2/" response = self.client.get(secure_url) self.assertRedirects( response, "%s?myfield=%s" % (reverse("admin:login"), secure_url) ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewUnicodeTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.b1 = Book.objects.create(name="Lærdommer") cls.p1 = Promo.objects.create(name="<Promo for Lærdommer>", book=cls.b1) cls.chap1 = Chapter.objects.create( title="Norske bostaver æøå skaper problemer", content="<p>Svært frustrerende med UnicodeDecodeErro</p>", book=cls.b1, ) cls.chap2 = Chapter.objects.create( title="Kjærlighet", content="<p>La kjærligheten til de lidende seire.</p>", book=cls.b1, ) cls.chap3 = Chapter.objects.create( title="Kjærlighet", content="<p>Noe innhold</p>", book=cls.b1 ) cls.chap4 = ChapterXtra1.objects.create( chap=cls.chap1, xtra="<Xtra(1) Norske bostaver æøå skaper problemer>" ) cls.chap5 = ChapterXtra1.objects.create( chap=cls.chap2, xtra="<Xtra(1) Kjærlighet>" ) cls.chap6 = ChapterXtra1.objects.create( chap=cls.chap3, xtra="<Xtra(1) Kjærlighet>" ) cls.chap7 = ChapterXtra2.objects.create( chap=cls.chap1, xtra="<Xtra(2) Norske bostaver æøå skaper problemer>" ) cls.chap8 = ChapterXtra2.objects.create( chap=cls.chap2, xtra="<Xtra(2) Kjærlighet>" ) cls.chap9 = ChapterXtra2.objects.create( chap=cls.chap3, xtra="<Xtra(2) Kjærlighet>" ) def setUp(self): self.client.force_login(self.superuser) def test_unicode_edit(self): """ A test to ensure that POST on edit_view handles non-ASCII characters. """ post_data = { "name": "Test lærdommer", # inline data "chapter_set-TOTAL_FORMS": "6", "chapter_set-INITIAL_FORMS": "3", "chapter_set-MAX_NUM_FORMS": "0", "chapter_set-0-id": self.chap1.pk, "chapter_set-0-title": "Norske bostaver æøå skaper problemer", "chapter_set-0-content": ( "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;" ), "chapter_set-1-id": self.chap2.id, "chapter_set-1-title": "Kjærlighet.", "chapter_set-1-content": ( "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;" ), "chapter_set-2-id": self.chap3.id, "chapter_set-2-title": "Need a title.", "chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "chapter_set-3-id": "", "chapter_set-3-title": "", "chapter_set-3-content": "", "chapter_set-4-id": "", "chapter_set-4-title": "", "chapter_set-4-content": "", "chapter_set-5-id": "", "chapter_set-5-title": "", "chapter_set-5-content": "", } response = self.client.post( reverse("admin:admin_views_book_change", args=(self.b1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_unicode_delete(self): """ The delete_view handles non-ASCII characters """ delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_book_delete", args=(self.b1.pk,)) response = self.client.get(delete_url) self.assertEqual(response.status_code, 200) response = self.client.post(delete_url, delete_dict) self.assertRedirects(response, reverse("admin:admin_views_book_changelist")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewListEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_inheritance(self): Podcast.objects.create( name="This Week in Django", release_date=datetime.date.today() ) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertEqual(response.status_code, 200) def test_inheritance_2(self): Vodcast.objects.create(name="This Week in Django", released=True) response = self.client.get(reverse("admin:admin_views_vodcast_changelist")) self.assertEqual(response.status_code, 200) def test_custom_pk(self): Language.objects.create(iso="en", name="English", english_name="English") response = self.client.get(reverse("admin:admin_views_language_changelist")) self.assertEqual(response.status_code, 200) def test_changelist_input_html(self): response = self.client.get(reverse("admin:admin_views_person_changelist")) # 2 inputs per object(the field and the hidden id field) = 6 # 4 management hidden fields = 4 # 4 action inputs (3 regular checkboxes, 1 checkbox to select all) # main form submit button = 1 # search field and search submit button = 2 # CSRF field = 2 # field to track 'select all' across paginated views = 1 # 6 + 4 + 4 + 1 + 2 + 2 + 1 = 20 inputs self.assertContains(response, "<input", count=21) # 1 select per object = 3 selects self.assertContains(response, "<select", count=4) def test_post_messages(self): # Ticket 12707: Saving inline editable should not show admin # action warnings data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data, follow=True ) self.assertEqual(len(response.context["messages"]), 1) def test_post_submission(self): data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) # test a filtered page data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "form-0-alive": "checked", "form-1-id": str(self.per3.pk), "form-1-gender": "1", "form-1-alive": "checked", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?gender__exact=1", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) # test a searched page data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?q=john", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) def test_non_field_errors(self): """ Non-field errors are displayed for each of the forms in the changelist's formset. """ fd1 = FoodDelivery.objects.create( reference="123", driver="bill", restaurant="thai" ) fd2 = FoodDelivery.objects.create( reference="456", driver="bill", restaurant="india" ) fd3 = FoodDelivery.objects.create( reference="789", driver="bill", restaurant="pizza" ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "pizza", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 1, html=True, ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", # Same data also. "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "thai", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 2, html=True, ) def test_non_form_errors(self): # test if non-form errors are handled; ticket #12716 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) self.assertContains(response, "Grace is not a Zombie") def test_non_form_errors_is_errorlist(self): # test if non-form errors are correctly handled; ticket #12878 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) non_form_errors = response.context["cl"].formset.non_form_errors() self.assertIsInstance(non_form_errors, ErrorList) self.assertEqual( str(non_form_errors), str(ErrorList(["Grace is not a Zombie"], error_class="nonform")), ) def test_list_editable_ordering(self): collector = Collector.objects.create(id=1, name="Frederick Clegg") Category.objects.create(id=1, order=1, collector=collector) Category.objects.create(id=2, order=2, collector=collector) Category.objects.create(id=3, order=0, collector=collector) Category.objects.create(id=4, order=0, collector=collector) # NB: The order values must be changed so that the items are reordered. data = { "form-TOTAL_FORMS": "4", "form-INITIAL_FORMS": "4", "form-MAX_NUM_FORMS": "0", "form-0-order": "14", "form-0-id": "1", "form-0-collector": "1", "form-1-order": "13", "form-1-id": "2", "form-1-collector": "1", "form-2-order": "1", "form-2-id": "3", "form-2-collector": "1", "form-3-order": "0", "form-3-id": "4", "form-3-collector": "1", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_category_changelist"), data ) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) def test_list_editable_pagination(self): """ Pagination works for list_editable items. """ UnorderedObject.objects.create(id=1, name="Unordered object #1") UnorderedObject.objects.create(id=2, name="Unordered object #2") UnorderedObject.objects.create(id=3, name="Unordered object #3") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") ) self.assertContains(response, "Unordered object #3") self.assertContains(response, "Unordered object #2") self.assertNotContains(response, "Unordered object #1") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") + "?p=2" ) self.assertNotContains(response, "Unordered object #3") self.assertNotContains(response, "Unordered object #2") self.assertContains(response, "Unordered object #1") def test_list_editable_action_submit(self): # List editable changes should not be executed if the action "Go" button is # used to submit the form. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": "1", "form-1-gender": "2", "form-1-id": "2", "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": "3", "index": "0", "_selected_action": ["3"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 1) def test_list_editable_action_choices(self): # List editable changes should be executed if the "Save" button is # used to submit the form - any action choices should be ignored. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", "_selected_action": ["1"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) def test_list_editable_popup(self): """ Fields should not be list-editable in popups. """ response = self.client.get(reverse("admin:admin_views_person_changelist")) self.assertNotEqual(response.context["cl"].list_editable, ()) response = self.client.get( reverse("admin:admin_views_person_changelist") + "?%s" % IS_POPUP_VAR ) self.assertEqual(response.context["cl"].list_editable, ()) def test_pk_hidden_fields(self): """ hidden pk fields aren't displayed in the table body and their corresponding human-readable value is displayed instead. The hidden pk fields are displayed but separately (not in the table) and only once. """ story1 = Story.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland..." ) story2 = Story.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) response = self.client.get(reverse("admin:admin_views_story_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains(response, '<td class="field-id">%d</td>' % story1.id, 1) self.assertContains(response, '<td class="field-id">%d</td>' % story2.id, 1) def test_pk_hidden_fields_with_list_display_links(self): """Similarly as test_pk_hidden_fields, but when the hidden pk fields are referenced in list_display_links. Refs #12475. """ story1 = OtherStory.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland...", ) story2 = OtherStory.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) link1 = reverse("admin:admin_views_otherstory_change", args=(story1.pk,)) link2 = reverse("admin:admin_views_otherstory_change", args=(story2.pk,)) response = self.client.get(reverse("admin:admin_views_otherstory_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link1, story1.id), 1, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link2, story2.id), 1, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSearchTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="John Doe", gender=1) Person.objects.create(name='John O"Hara', gender=1) Person.objects.create(name="John O'Hara", gender=1) cls.t1 = Recommender.objects.create() cls.t2 = Recommendation.objects.create(the_recommender=cls.t1) cls.t3 = Recommender.objects.create() cls.t4 = Recommendation.objects.create(the_recommender=cls.t3) cls.tt1 = TitleTranslation.objects.create(title=cls.t1, text="Bar") cls.tt2 = TitleTranslation.objects.create(title=cls.t2, text="Foo") cls.tt3 = TitleTranslation.objects.create(title=cls.t3, text="Few") cls.tt4 = TitleTranslation.objects.create(title=cls.t4, text="Bas") def setUp(self): self.client.force_login(self.superuser) def test_search_on_sibling_models(self): "A search that mentions sibling models" response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned 1 object self.assertContains(response, "\n1 recommendation\n") def test_with_fk_to_field(self): """ The to_field GET parameter is preserved when a search is performed. Refs #10918. """ response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertContains(response, "\n1 user\n") self.assertContains( response, '<input type="hidden" name="%s" value="id">' % TO_FIELD_VAR, html=True, ) def test_exact_matches(self): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned one object self.assertContains(response, "\n1 recommendation\n") response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=ba" ) # confirm the search returned zero objects self.assertContains(response, "\n0 recommendations\n") def test_beginning_matches(self): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) # confirm the search returned one object self.assertContains(response, "\n1 person\n") self.assertContains(response, "Guido") response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=uido" ) # confirm the search returned zero objects self.assertContains(response, "\n0 persons\n") self.assertNotContains(response, "Guido") def test_pluggable_search(self): PluggableSearchPerson.objects.create(name="Bob", age=10) PluggableSearchPerson.objects.create(name="Amy", age=20) response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=Bob" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Bob") response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=20" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Amy") def test_reset_link(self): """ Test presence of reset link in search bar ("1 result (_x total_)"). """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count # + 1 for total count with self.assertNumQueries(5): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">6 total</a>)</span>""", html=True, ) def test_no_total_count(self): """ #8408 -- "Show all" should be displayed instead of the total count if ModelAdmin.show_full_result_count is False. """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count with self.assertNumQueries(4): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">Show all</a>)</span>""", html=True, ) self.assertTrue(response.context["cl"].show_admin_actions) def test_search_with_spaces(self): url = reverse("admin:admin_views_person_changelist") + "?q=%s" tests = [ ('"John Doe"', 1), ("'John Doe'", 1), ("John Doe", 0), ('"John Doe" John', 1), ("'John Doe' John", 1), ("John Doe John", 0), ('"John Do"', 1), ("'John Do'", 1), ("'John O'Hara'", 0), ("'John O\\'Hara'", 1), ('"John O"Hara"', 0), ('"John O\\"Hara"', 1), ] for search, hits in tests: with self.subTest(search=search): response = self.client.get(url % search) self.assertContains(response, "\n%s person" % hits) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInheritedInlinesTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_inline(self): """ Inline models which inherit from a common parent are correctly handled. """ foo_user = "foo username" bar_user = "bar username" name_re = re.compile(b'name="(.*?)"') # test the add case response = self.client.get(reverse("admin:admin_views_persona_add")) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) # test the add case post_data = { "name": "Test Name", # inline data "accounts-TOTAL_FORMS": "1", "accounts-INITIAL_FORMS": "0", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": foo_user, "accounts-2-TOTAL_FORMS": "1", "accounts-2-INITIAL_FORMS": "0", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": bar_user, } response = self.client.post(reverse("admin:admin_views_persona_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, foo_user) self.assertEqual(BarAccount.objects.all()[0].username, bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) persona_id = Persona.objects.all()[0].id foo_id = FooAccount.objects.all()[0].id bar_id = BarAccount.objects.all()[0].id # test the edit case response = self.client.get( reverse("admin:admin_views_persona_change", args=(persona_id,)) ) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) post_data = { "name": "Test Name", "accounts-TOTAL_FORMS": "2", "accounts-INITIAL_FORMS": "1", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": "%s-1" % foo_user, "accounts-0-account_ptr": str(foo_id), "accounts-0-persona": str(persona_id), "accounts-2-TOTAL_FORMS": "2", "accounts-2-INITIAL_FORMS": "1", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": "%s-1" % bar_user, "accounts-2-0-account_ptr": str(bar_id), "accounts-2-0-persona": str(persona_id), } response = self.client.post( reverse("admin:admin_views_persona_change", args=(persona_id,)), post_data ) self.assertEqual(response.status_code, 302) self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, "%s-1" % foo_user) self.assertEqual(BarAccount.objects.all()[0].username, "%s-1" % bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) @override_settings(ROOT_URLCONF="admin_views.urls") class TestCustomChangeList(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_custom_changelist(self): """ Validate that a custom ChangeList class can be used (#9749) """ # Insert some data post_data = {"name": "First Gadget"} response = self.client.post(reverse("admin:admin_views_gadget_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere # Hit the page once to get messages out of the queue message list response = self.client.get(reverse("admin:admin_views_gadget_changelist")) # Data is still not visible on the page response = self.client.get(reverse("admin:admin_views_gadget_changelist")) self.assertNotContains(response, "First Gadget") @override_settings(ROOT_URLCONF="admin_views.urls") class TestInlineNotEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_GET_parent_add(self): """ InlineModelAdmin broken? """ response = self.client.get(reverse("admin:admin_views_parent_add")) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomQuerysetTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.pks = [EmptyModel.objects.create().id for i in range(3)] def setUp(self): self.client.force_login(self.superuser) self.super_login = { REDIRECT_FIELD_NAME: reverse("admin:index"), "username": "super", "password": "secret", } def test_changelist_view(self): response = self.client.get(reverse("admin:admin_views_emptymodel_changelist")) for i in self.pks: if i > 1: self.assertContains(response, "Primary key = %s" % i) else: self.assertNotContains(response, "Primary key = %s" % i) def test_changelist_view_count_queries(self): # create 2 Person objects Person.objects.create(name="person1", gender=1) Person.objects.create(name="person2", gender=2) changelist_url = reverse("admin:admin_views_person_changelist") # 5 queries are expected: 1 for the session, 1 for the user, # 2 for the counts and 1 for the objects on the page with self.assertNumQueries(5): resp = self.client.get(changelist_url) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"q": "not_in_name"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 0 selected") self.assertEqual(resp.context["selection_note_all"], "All 0 selected") with self.assertNumQueries(5): extra = {"q": "person"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"gender__exact": "1"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 1 selected") self.assertEqual(resp.context["selection_note_all"], "1 selected") def test_change_view(self): for i in self.pks: url = reverse("admin:admin_views_emptymodel_change", args=(i,)) response = self.client.get(url, follow=True) if i > 1: self.assertEqual(response.status_code, 200) else: self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["empty model with ID “1” doesn’t exist. Perhaps it was deleted?"], ) def test_add_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(CoverLetter.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "author": "Candidate, Best", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_coverletter_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name pk = CoverLetter.objects.all()[0].pk self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "Candidate, Best</a>” was added successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(ShortMessage.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "content": "What's this SMS thing?", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_shortmessage_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name sm = ShortMessage.objects.all()[0] self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_add_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(Telegram.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "Urgent telegram", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name pk = Telegram.objects.all()[0].pk self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Urgent telegram</a>” was added successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(Paper.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name p = Paper.objects.all()[0] self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_edit_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method cl = CoverLetter.objects.create(author="John Doe") self.assertEqual(CoverLetter.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "author": "John Doe II", "_save": "Save", } url = reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name. Instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "John Doe II</a>” was changed successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(cl.pk,)), html=True, ) # model has no __str__ method sm = ShortMessage.objects.create(content="This is expensive") self.assertEqual(ShortMessage.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "content": "Too expensive", "_save": "Save", } url = reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_edit_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method t = Telegram.objects.create(title="First Telegram") self.assertEqual(Telegram.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_telegram_change", args=(t.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "Telegram without typo", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_change", args=(t.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name. The instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Telegram without typo</a>” was changed successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(t.pk,)), html=True, ) # model has no __str__ method p = Paper.objects.create(title="My Paper Title") self.assertEqual(Paper.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_paper_change", args=(p.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_change", args=(p.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_history_view_custom_qs(self): """ Custom querysets are considered for the admin history view. """ self.client.post(reverse("admin:login"), self.super_login) FilteredManager.objects.create(pk=1) FilteredManager.objects.create(pk=2) response = self.client.get( reverse("admin:admin_views_filteredmanager_changelist") ) self.assertContains(response, "PK=1") self.assertContains(response, "PK=2") self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(1,)) ).status_code, 200, ) self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(2,)) ).status_code, 200, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineFileUploadTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) file1 = tempfile.NamedTemporaryFile(suffix=".file1") file1.write(b"a" * (2**21)) filename = file1.name file1.close() cls.gallery = Gallery.objects.create(name="Test Gallery") cls.picture = Picture.objects.create( name="Test Picture", image=filename, gallery=cls.gallery, ) def setUp(self): self.client.force_login(self.superuser) def test_form_has_multipart_enctype(self): response = self.client.get( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)) ) self.assertIs(response.context["has_file_field"], True) self.assertContains(response, MULTIPART_ENCTYPE) def test_inline_file_upload_edit_validation_error_post(self): """ Inline file uploads correctly display prior data (#10002). """ post_data = { "name": "Test Gallery", "pictures-TOTAL_FORMS": "2", "pictures-INITIAL_FORMS": "1", "pictures-MAX_NUM_FORMS": "0", "pictures-0-id": str(self.picture.id), "pictures-0-gallery": str(self.gallery.id), "pictures-0-name": "Test Picture", "pictures-0-image": "", "pictures-1-id": "", "pictures-1-gallery": str(self.gallery.id), "pictures-1-name": "Test Picture 2", "pictures-1-image": "", } response = self.client.post( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)), post_data, ) self.assertContains(response, b"Currently") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.collector = Collector.objects.create(pk=1, name="John Fowles") def setUp(self): self.post_data = { "name": "Test Name", "widget_set-TOTAL_FORMS": "3", "widget_set-INITIAL_FORMS": "0", "widget_set-MAX_NUM_FORMS": "0", "widget_set-0-id": "", "widget_set-0-owner": "1", "widget_set-0-name": "", "widget_set-1-id": "", "widget_set-1-owner": "1", "widget_set-1-name": "", "widget_set-2-id": "", "widget_set-2-owner": "1", "widget_set-2-name": "", "doohickey_set-TOTAL_FORMS": "3", "doohickey_set-INITIAL_FORMS": "0", "doohickey_set-MAX_NUM_FORMS": "0", "doohickey_set-0-owner": "1", "doohickey_set-0-code": "", "doohickey_set-0-name": "", "doohickey_set-1-owner": "1", "doohickey_set-1-code": "", "doohickey_set-1-name": "", "doohickey_set-2-owner": "1", "doohickey_set-2-code": "", "doohickey_set-2-name": "", "grommet_set-TOTAL_FORMS": "3", "grommet_set-INITIAL_FORMS": "0", "grommet_set-MAX_NUM_FORMS": "0", "grommet_set-0-code": "", "grommet_set-0-owner": "1", "grommet_set-0-name": "", "grommet_set-1-code": "", "grommet_set-1-owner": "1", "grommet_set-1-name": "", "grommet_set-2-code": "", "grommet_set-2-owner": "1", "grommet_set-2-name": "", "whatsit_set-TOTAL_FORMS": "3", "whatsit_set-INITIAL_FORMS": "0", "whatsit_set-MAX_NUM_FORMS": "0", "whatsit_set-0-owner": "1", "whatsit_set-0-index": "", "whatsit_set-0-name": "", "whatsit_set-1-owner": "1", "whatsit_set-1-index": "", "whatsit_set-1-name": "", "whatsit_set-2-owner": "1", "whatsit_set-2-index": "", "whatsit_set-2-name": "", "fancydoodad_set-TOTAL_FORMS": "3", "fancydoodad_set-INITIAL_FORMS": "0", "fancydoodad_set-MAX_NUM_FORMS": "0", "fancydoodad_set-0-doodad_ptr": "", "fancydoodad_set-0-owner": "1", "fancydoodad_set-0-name": "", "fancydoodad_set-0-expensive": "on", "fancydoodad_set-1-doodad_ptr": "", "fancydoodad_set-1-owner": "1", "fancydoodad_set-1-name": "", "fancydoodad_set-1-expensive": "on", "fancydoodad_set-2-doodad_ptr": "", "fancydoodad_set-2-owner": "1", "fancydoodad_set-2-name": "", "fancydoodad_set-2-expensive": "on", "category_set-TOTAL_FORMS": "3", "category_set-INITIAL_FORMS": "0", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "", "category_set-0-id": "", "category_set-0-collector": "1", "category_set-1-order": "", "category_set-1-id": "", "category_set-1-collector": "1", "category_set-2-order": "", "category_set-2-id": "", "category_set-2-collector": "1", } self.client.force_login(self.superuser) def test_simple_inline(self): "A simple model can be saved as inlines" # First add a new inline self.post_data["widget_set-0-name"] = "Widget 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") widget_id = Widget.objects.all()[0].id # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="widget_set-0-id"') # No file or image fields, no enctype on the forms self.assertIs(response.context["has_file_field"], False) self.assertNotContains(response, MULTIPART_ENCTYPE) # Now resave that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") # Now modify that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_explicit_autofield_inline(self): """ A model with an explicit autofield primary key can be saved as inlines. """ # First add a new inline self.post_data["grommet_set-0-name"] = "Grommet 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="grommet_set-0-code"') # Now resave that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # Now modify that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1 Updated") def test_char_pk_inline(self): "A model with a character PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="doohickey_set-0-code"') # Now resave that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # Now modify that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1 Updated") def test_integer_pk_inline(self): "A model with an integer PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="whatsit_set-0-index"') # Now resave that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # Now modify that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1 Updated") def test_inherited_inline(self): "An inherited model can be saved as inlines. Regression for #11042" # First add a new inline self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") doodad_pk = FancyDoodad.objects.all()[0].pk # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="fancydoodad_set-0-doodad_ptr"') # Now resave that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") # Now modify that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1 Updated") def test_ordered_inline(self): """ An inline with an editable ordering fields is updated correctly. """ # Create some objects with an initial ordering Category.objects.create(id=1, order=1, collector=self.collector) Category.objects.create(id=2, order=2, collector=self.collector) Category.objects.create(id=3, order=0, collector=self.collector) Category.objects.create(id=4, order=0, collector=self.collector) # NB: The order values must be changed so that the items are reordered. self.post_data.update( { "name": "Frederick Clegg", "category_set-TOTAL_FORMS": "7", "category_set-INITIAL_FORMS": "4", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "14", "category_set-0-id": "1", "category_set-0-collector": "1", "category_set-1-order": "13", "category_set-1-id": "2", "category_set-1-collector": "1", "category_set-2-order": "1", "category_set-2-id": "3", "category_set-2-collector": "1", "category_set-3-order": "0", "category_set-3-id": "4", "category_set-3-collector": "1", "category_set-4-order": "", "category_set-4-id": "", "category_set-4-collector": "1", "category_set-5-order": "", "category_set-5-id": "", "category_set-5-collector": "1", "category_set-6-order": "", "category_set-6-id": "", "category_set-6-collector": "1", } ) collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(self.collector.category_set.count(), 4) self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) @override_settings(ROOT_URLCONF="admin_views.urls") class NeverCacheTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") def setUp(self): self.client.force_login(self.superuser) def test_admin_index(self): "Check the never-cache status of the main index" response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_app_index(self): "Check the never-cache status of an application index" response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(get_max_age(response), 0) def test_model_index(self): "Check the never-cache status of a model index" response = self.client.get(reverse("admin:admin_views_fabric_changelist")) self.assertEqual(get_max_age(response), 0) def test_model_add(self): "Check the never-cache status of a model add page" response = self.client.get(reverse("admin:admin_views_fabric_add")) self.assertEqual(get_max_age(response), 0) def test_model_view(self): "Check the never-cache status of a model edit page" response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_history(self): "Check the never-cache status of a model history page" response = self.client.get( reverse("admin:admin_views_section_history", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_delete(self): "Check the never-cache status of a model delete page" response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_login(self): "Check the never-cache status of login views" self.client.logout() response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_logout(self): "Check the never-cache status of logout view" response = self.client.post(reverse("admin:logout")) self.assertEqual(get_max_age(response), 0) def test_password_change(self): "Check the never-cache status of the password change view" self.client.logout() response = self.client.get(reverse("admin:password_change")) self.assertIsNone(get_max_age(response)) def test_password_change_done(self): "Check the never-cache status of the password change done view" response = self.client.get(reverse("admin:password_change_done")) self.assertIsNone(get_max_age(response)) def test_JS_i18n(self): "Check the never-cache status of the JavaScript i18n view" response = self.client.get(reverse("admin:jsi18n")) self.assertIsNone(get_max_age(response)) @override_settings(ROOT_URLCONF="admin_views.urls") class PrePopulatedTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_prepopulated_on(self): response = self.client.get(reverse("admin:admin_views_prepopulatedpost_add")) self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) def test_prepopulated_off(self): response = self.client.get( reverse("admin:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, "A Long Title") self.assertNotContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertNotContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertNotContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_prepopulated_maxlength_localized(self): """ Regression test for #15938: if USE_THOUSAND_SEPARATOR is set, make sure that maxLength (in the JavaScript) is rendered without separators. """ response = self.client.get( reverse("admin:admin_views_prepopulatedpostlargeslug_add") ) self.assertContains(response, "&quot;maxLength&quot;: 1000") # instead of 1,000 def test_view_only_add_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug' which is present in the add view, even if the ModelAdmin.has_change_permission() returns False. """ response = self.client.get(reverse("admin7:admin_views_prepopulatedpost_add")) self.assertContains(response, "data-prepopulated-fields=") self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") def test_view_only_change_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug'. That doesn't break a view-only change view. """ response = self.client.get( reverse("admin7:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, 'data-prepopulated-fields="[]"') self.assertContains(response, '<div class="readonly">%s</div>' % self.p1.slug) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) self.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def test_login_button_centered(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) button = self.selenium.find_element(By.CSS_SELECTOR, ".submit-row input") offset_left = button.get_property("offsetLeft") offset_right = button.get_property("offsetParent").get_property( "offsetWidth" ) - (offset_left + button.get_property("offsetWidth")) # Use assertAlmostEqual to avoid pixel rounding errors. self.assertAlmostEqual(offset_left, offset_right, delta=3) def test_prepopulated_fields(self): """ The JavaScript-automated prepopulated fields work with the main form and with stacked and tabular inlines. Refs #13068, #9264, #9983, #9784. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_mainprepopulated_add") ) self.wait_for(".select2") # Main form ---------------------------------------------------------- self.selenium.find_element(By.ID, "id_pubdate").send_keys("2012-02-18") self.select_option("#id_status", "option two") self.selenium.find_element(By.ID, "id_name").send_keys( " the mAin nÀMë and it's awεšomeıııİ" ) slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") slug3 = self.selenium.find_element(By.ID, "id_slug3").get_attribute("value") self.assertEqual(slug1, "the-main-name-and-its-awesomeiiii-2012-02-18") self.assertEqual(slug2, "option-two-the-main-name-and-its-awesomeiiii") self.assertEqual( slug3, "the-main-n\xe0m\xeb-and-its-aw\u03b5\u0161ome\u0131\u0131\u0131i" ) # Stacked inlines with fieldsets ------------------------------------- # Initial inline self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-pubdate" ).send_keys("2011-12-17") self.select_option("#id_relatedprepopulated_set-0-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-name" ).send_keys(" here is a sŤāÇkeð inline ! ") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "here-is-a-stacked-inline-2011-12-17") self.assertEqual(slug2, "option-one-here-is-a-stacked-inline") initial_select2_inputs = self.selenium.find_elements( By.CLASS_NAME, "select2-selection" ) # Inline formsets have empty/invisible forms. # Only the 4 visible select2 inputs are initialized. num_initial_select2_inputs = len(initial_select2_inputs) self.assertEqual(num_initial_select2_inputs, 4) # Add an inline self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 0 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 2, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-pubdate" ).send_keys("1999-01-25") self.select_option("#id_relatedprepopulated_set-1-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-name" ).send_keys( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog " "text... " ) slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug2" ).get_attribute("value") # 50 characters maximum for slug1 field self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") # 60 characters maximum for slug2 field self.assertEqual( slug2, "option-two-now-you-have-another-stacked-inline-with-a-very-l" ) # Tabular inlines ---------------------------------------------------- # Initial inline element = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-status" ) self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-pubdate" ).send_keys("1234-12-07") self.select_option("#id_relatedprepopulated_set-2-0-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-name" ).send_keys("And now, with a tÃbűlaŘ inline !!!") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "and-now-with-a-tabular-inline-1234-12-07") self.assertEqual(slug2, "option-two-and-now-with-a-tabular-inline") # Add an inline # Button may be outside the browser frame. element = self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated" )[1] self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) element.click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 4, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-pubdate" ).send_keys("1981-08-22") self.select_option("#id_relatedprepopulated_set-2-1-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-name" ).send_keys(r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug2" ).get_attribute("value") self.assertEqual(slug1, "tabular-inline-with-ignored-characters-1981-08-22") self.assertEqual(slug2, "option-one-tabular-inline-with-ignored-characters") # Add an inline without an initial inline. # The button is outside of the browser frame. self.selenium.execute_script("window.scrollTo(0, document.body.scrollHeight);") self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 2 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 6, ) # Stacked Inlines without fieldsets ---------------------------------- # Initial inline. row_id = "id_relatedprepopulated_set-4-0-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("2011-12-12") self.select_option(f"#{row_id}status", "option one") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " sŤāÇkeð inline ! " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "stacked-inline-2011-12-12") self.assertEqual(slug2, "option-one") # Add inline. self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated", )[3].click() row_id = "id_relatedprepopulated_set-4-1-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("1999-01-20") self.select_option(f"#{row_id}status", "option two") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " now you haVe anöther sŤāÇkeð inline with a very loooong " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") self.assertEqual(slug2, "option-two") # Save and check that everything is properly stored in the database with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.assertEqual(MainPrepopulated.objects.count(), 1) MainPrepopulated.objects.get( name=" the mAin nÀMë and it's awεšomeıııİ", pubdate="2012-02-18", status="option two", slug1="the-main-name-and-its-awesomeiiii-2012-02-18", slug2="option-two-the-main-name-and-its-awesomeiiii", slug3="the-main-nàmë-and-its-awεšomeıııi", ) self.assertEqual(RelatedPrepopulated.objects.count(), 6) RelatedPrepopulated.objects.get( name=" here is a sŤāÇkeð inline ! ", pubdate="2011-12-17", status="option one", slug1="here-is-a-stacked-inline-2011-12-17", slug2="option-one-here-is-a-stacked-inline", ) RelatedPrepopulated.objects.get( # 75 characters in name field name=( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooo" ), pubdate="1999-01-25", status="option two", slug1="now-you-have-another-stacked-inline-with-a-very-lo", slug2="option-two-now-you-have-another-stacked-inline-with-a-very-l", ) RelatedPrepopulated.objects.get( name="And now, with a tÃbűlaŘ inline !!!", pubdate="1234-12-07", status="option two", slug1="and-now-with-a-tabular-inline-1234-12-07", slug2="option-two-and-now-with-a-tabular-inline", ) RelatedPrepopulated.objects.get( name=r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', pubdate="1981-08-22", status="option one", slug1="tabular-inline-with-ignored-characters-1981-08-22", slug2="option-one-tabular-inline-with-ignored-characters", ) def test_populate_existing_object(self): """ The prepopulation works for existing objects too, as long as the original field is empty (#19082). """ from selenium.webdriver.common.by import By # Slugs are empty to start with. item = MainPrepopulated.objects.create( name=" this is the mAin nÀMë", pubdate="2012-02-18", status="option two", slug1="", slug2="", ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) object_url = self.live_server_url + reverse( "admin:admin_views_mainprepopulated_change", args=(item.id,) ) self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" the best") # The slugs got prepopulated since they were originally empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") # Save the object with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" hello") # The slugs got prepopulated didn't change since they were originally not empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") def test_collapsible_fieldset(self): """ The 'collapse' class in fieldsets definition allows to show/hide the appropriate field section. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_add") ) self.assertFalse(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() self.assertTrue(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "fieldsetcollapser0").text, "Hide" ) def test_selectbox_height_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_pizza_add") self.selenium.get(url) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() from_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter") from_box = self.selenium.find_element(By.ID, "id_toppings_from") to_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter_selected") to_box = self.selenium.find_element(By.ID, "id_toppings_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_selectbox_height_not_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_question_add") self.selenium.get(url) from_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter" ) from_box = self.selenium.find_element(By.ID, "id_related_questions_from") to_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter_selected" ) to_box = self.selenium.find_element(By.ID, "id_related_questions_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_first_field_focus(self): """JavaScript-assisted auto-focus on first usable form field.""" from selenium.webdriver.common.by import By # First form field has a single widget self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_picture_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_name"), ) # First form field has a MultiWidget with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_reservation_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_start_date_0"), ) def test_cancel_delete_confirmation(self): "Cancelling the deletion of an object takes the user back one page." from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) def test_cancel_delete_related_confirmation(self): """ Cancelling the deletion of an object with relations takes the user back one page. """ from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") topping1 = Topping.objects.create(name="Cheddar") topping2 = Topping.objects.create(name="Mozzarella") pizza.toppings.add(topping1, topping2) url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) self.assertEqual(Topping.objects.count(), 2) def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name="Test section") Article.objects.create( title="foo", content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=s1, ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_changelist") ) # Change popup self.selenium.find_element(By.ID, "change_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Change section") name_input = self.selenium.find_element(By.ID, "id_name") name_input.clear() name_input.send_keys("<i>edited section</i>") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Hide sidebar. toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "<i>edited section</i>") # Rendered select2 input. select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\n<i>edited section</i>") # Add popup self.selenium.find_element(By.ID, "add_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Add section") self.selenium.find_element(By.ID, "id_name").send_keys("new section") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "new section") select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\nnew section") def test_inline_uuid_pk_edit_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "change_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(select.first_selected_option.text, str(parent.id)) self.assertEqual( select.first_selected_option.get_attribute("value"), str(parent.id) ) def test_inline_uuid_pk_add_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_relatedwithuuidpkmodel_add") ) self.selenium.find_element(By.ID, "add_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) uuid_id = str(ParentWithUUIDPK.objects.first().id) self.assertEqual(select.first_selected_option.text, uuid_id) self.assertEqual(select.first_selected_option.get_attribute("value"), uuid_id) def test_inline_uuid_pk_delete_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Yes, I’m sure"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(ParentWithUUIDPK.objects.count(), 0) self.assertEqual(select.first_selected_option.text, "---------") self.assertEqual(select.first_selected_option.get_attribute("value"), "") def test_inline_with_popup_cancel_delete(self): """Clicking ""No, take me back" on a delete popup closes the window.""" from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//a[text()="No, take me back"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertEqual(len(self.selenium.window_handles), 1) def test_list_editable_raw_id_fields(self): from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") parent2 = ParentWithUUIDPK.objects.create(title="test2") RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_changelist", current_app=site2.name, ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "lookup_id_form-0-parent").click() self.wait_for_and_switch_to_popup() # Select "parent2" in the popup. self.selenium.find_element(By.LINK_TEXT, str(parent2.pk)).click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # The newly selected pk should appear in the raw id input. value = self.selenium.find_element(By.ID, "id_form-0-parent").get_attribute( "value" ) self.assertEqual(value, str(parent2.pk)) def test_input_element_font(self): """ Browsers' default stylesheets override the font of inputs. The admin adds additional CSS to handle this. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) element = self.selenium.find_element(By.ID, "id_username") # Some browsers quotes the fonts, some don't. fonts = [ font.strip().strip('"') for font in element.value_of_css_property("font-family").split(",") ] self.assertEqual( fonts, [ "-apple-system", "BlinkMacSystemFont", "Segoe UI", "system-ui", "Roboto", "Helvetica Neue", "Arial", "sans-serif", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", ], ) def test_search_input_filtered_page(self): from selenium.webdriver.common.by import By Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="Grace Hopper", gender=1, alive=False) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) person_url = reverse("admin:admin_views_person_changelist") + "?q=Gui" self.selenium.get(self.live_server_url + person_url) self.assertGreater( self.selenium.find_element(By.ID, "searchbar").rect["width"], 50, ) def test_related_popup_index(self): """ Create a chain of 'self' related objects via popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) base_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() popup_window_test = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) popup_window_test2 = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.selenium.find_element(By.ID, "id_title").send_keys("test3") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test2) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test3").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test2").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(base_window) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) def test_related_popup_incorrect_close(self): """ Cleanup child popups when closing a parent popup. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() test_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) test2_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.assertEqual(len(self.selenium.window_handles), 4) self.selenium.switch_to.window(test2_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 2, 1) self.assertEqual(len(self.selenium.window_handles), 2) # Close final popup to clean up test. self.selenium.switch_to.window(test_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[-1]) def test_hidden_fields_small_window(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) self.selenium.get(self.live_server_url + reverse("admin:admin_views_story_add")) field_title = self.selenium.find_element(By.CLASS_NAME, "field-title") current_size = self.selenium.get_window_size() try: self.selenium.set_window_size(1024, 768) self.assertIs(field_title.is_displayed(), False) self.selenium.set_window_size(767, 575) self.assertIs(field_title.is_displayed(), False) finally: self.selenium.set_window_size(current_size["width"], current_size["height"]) def test_updating_related_objects_updates_fk_selects_except_autocompletes(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select born_country_select_id = "id_born_country" living_country_select_id = "id_living_country" living_country_select2_textbox_id = "select2-id_living_country-container" favorite_country_to_vacation_select_id = "id_favorite_country_to_vacation" continent_select_id = "id_continent" def _get_HTML_inside_element_by_id(id_): return self.selenium.find_element(By.ID, id_).get_attribute("innerHTML") def _get_text_inside_element_by_selector(selector): return self.selenium.find_element(By.CSS_SELECTOR, selector).get_attribute( "innerText" ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_traveler_add") self.selenium.get(self.live_server_url + add_url) # Add new Country from the born_country select. self.selenium.find_element(By.ID, f"add_{born_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Argentina") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("South America") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> """, ) # Argentina isn't added to the living_country select nor selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id}"), "" ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "", ) # Argentina won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add new Country from the living_country select. self.selenium.find_element(By.ID, f"add_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Spain") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Europe") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Spain</option> """, ) # Spain is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Spain", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Spain", ) # Spain won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Edit second Country created from living_country select. favorite_select = Select( self.selenium.find_element(By.ID, living_country_select_id) ) favorite_select.select_by_visible_text("Spain") self.selenium.find_element(By.ID, f"change_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.clear() favorite_name_input.send_keys("Italy") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Italy</option> """, ) # Italy is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Italy", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Italy", ) # favorite_country_to_vacation field has no options. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add a new Asian country. self.selenium.find_element( By.ID, f"add_{favorite_country_to_vacation_select_id}" ).click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.send_keys("Qatar") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Asia") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Submit the new Traveler. self.selenium.find_element(By.CSS_SELECTOR, '[name="_save"]').click() traveler = Traveler.objects.get() self.assertEqual(traveler.born_country.name, "Argentina") self.assertEqual(traveler.living_country.name, "Italy") self.assertEqual(traveler.favorite_country_to_vacation.name, "Qatar") def test_redirect_on_add_view_add_another_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 2") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 2) def test_redirect_on_add_view_continue_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and continue editing"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input_value = name_input.get_attribute("value") self.assertEqual(name_input_value, "Test section 1") @override_settings(ROOT_URLCONF="admin_views.urls") class ReadonlyTest(AdminFieldExtractionMixin, TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) @ignore_warnings(category=RemovedInDjango60Warning) def test_readonly_get(self): response = self.client.get(reverse("admin:admin_views_post_add")) self.assertNotContains(response, 'name="posted"') # 3 fields + 2 submit buttons + 5 inline management form fields, + 2 # hidden fields for inlines + 1 field for the inline + 2 empty form # + 1 logout form. self.assertContains(response, "<input", count=17) self.assertContains(response, formats.localize(datetime.date.today())) self.assertContains(response, "<label>Awesomeness level:</label>") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") # Multiline text in a readonly field gets <br> tags self.assertContains(response, "Multiline<br>test<br>string") self.assertContains( response, '<div class="readonly">Multiline<br>html<br>content</div>', html=True, ) self.assertContains(response, "InlineMultiline<br>test<br>string") self.assertContains( response, formats.localize(datetime.date.today() - datetime.timedelta(days=7)), ) self.assertContains(response, '<div class="form-row field-coolness">') self.assertContains(response, '<div class="form-row field-awesomeness_level">') self.assertContains(response, '<div class="form-row field-posted">') self.assertContains(response, '<div class="form-row field-value">') self.assertContains(response, '<div class="form-row">') self.assertContains(response, '<div class="help"', 3) self.assertContains( response, '<div class="help" id="id_title_helptext"><div>Some help text for the ' "title (with Unicode ŠĐĆŽćžšđ)</div></div>", html=True, ) self.assertContains( response, '<div class="help" id="id_content_helptext"><div>Some help text for the ' "content (with Unicode ŠĐĆŽćžšđ)</div></div>", html=True, ) self.assertContains( response, '<div class="help"><div>Some help text for the date (with Unicode ŠĐĆŽćžšđ)' "</div></div>", html=True, ) p = Post.objects.create( title="I worked on readonly_fields", content="Its good stuff" ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) self.assertContains(response, "%d amount of cool" % p.pk) @ignore_warnings(category=RemovedInDjango60Warning) def test_readonly_text_field(self): p = Post.objects.create( title="Readonly test", content="test", readonly_content="test\r\n\r\ntest\r\n\r\ntest\r\n\r\ntest", ) Link.objects.create( url="http://www.djangoproject.com", post=p, readonly_link_content="test\r\nlink", ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) # Checking readonly field. self.assertContains(response, "test<br><br>test<br><br>test<br><br>test") # Checking readonly field in inline. self.assertContains(response, "test<br>link") @ignore_warnings(category=RemovedInDjango60Warning) def test_readonly_post(self): data = { "title": "Django Got Readonly Fields", "content": "This is an incredible development.", "link_set-TOTAL_FORMS": "1", "link_set-INITIAL_FORMS": "0", "link_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) p = Post.objects.get() self.assertEqual(p.posted, datetime.date.today()) data["posted"] = "10-8-1990" # some date that's not today response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) p = Post.objects.order_by("-id")[0] self.assertEqual(p.posted, datetime.date.today()) def test_readonly_manytomany(self): "Regression test for #13004" response = self.client.get(reverse("admin:admin_views_pizza_add")) self.assertEqual(response.status_code, 200) def test_user_password_change_limited_queryset(self): su = User.objects.filter(is_superuser=True)[0] response = self.client.get( reverse("admin2:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 404) def test_change_form_renders_correct_null_choice_value(self): """ Regression test for #17911. """ choice = Choice.objects.create(choice=None) response = self.client.get( reverse("admin:admin_views_choice_change", args=(choice.pk,)) ) self.assertContains( response, '<div class="readonly">No opinion</div>', html=True ) def _test_readonly_foreignkey_links(self, admin_site): """ ForeignKey readonly fields render as links if the target model is registered in admin. """ chapter = Chapter.objects.create( title="Chapter 1", content="content", book=Book.objects.create(name="Book 1"), ) language = Language.objects.create(iso="_40", name="Test") obj = ReadOnlyRelatedField.objects.create( chapter=chapter, language=language, user=self.superuser, ) response = self.client.get( reverse( f"{admin_site}:admin_views_readonlyrelatedfield_change", args=(obj.pk,) ), ) # Related ForeignKey object registered in admin. user_url = reverse(f"{admin_site}:auth_user_change", args=(self.superuser.pk,)) self.assertContains( response, '<div class="readonly"><a href="%s">super</a></div>' % user_url, html=True, ) # Related ForeignKey with the string primary key registered in admin. language_url = reverse( f"{admin_site}:admin_views_language_change", args=(quote(language.pk),), ) self.assertContains( response, '<div class="readonly"><a href="%s">_40</a></div>' % language_url, html=True, ) # Related ForeignKey object not registered in admin. self.assertContains( response, '<div class="readonly">Chapter 1</div>', html=True ) def test_readonly_foreignkey_links_default_admin_site(self): self._test_readonly_foreignkey_links("admin") def test_readonly_foreignkey_links_custom_admin_site(self): self._test_readonly_foreignkey_links("namespaced_admin") def test_readonly_manytomany_backwards_ref(self): """ Regression test for #16433 - backwards references for related objects broke if the related field is read-only due to the help_text attribute """ topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get(reverse("admin:admin_views_topping_add")) self.assertEqual(response.status_code, 200) def test_readonly_manytomany_forwards_ref(self): topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get( reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) ) self.assertContains(response, "<label>Toppings:</label>", html=True) self.assertContains(response, '<div class="readonly">Salami</div>', html=True) def test_readonly_onetoone_backwards_ref(self): """ Can reference a reverse OneToOneField in ModelAdmin.readonly_fields. """ v1 = Villain.objects.create(name="Adam") pl = Plot.objects.create(name="Test Plot", team_leader=v1, contact=v1) pd = PlotDetails.objects.create(details="Brand New Plot", plot=pl) response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") pd_url = reverse("admin:admin_views_plotdetails_change", args=(pd.pk,)) self.assertEqual(field.contents(), '<a href="%s">Brand New Plot</a>' % pd_url) # The reverse relation also works if the OneToOneField is null. pd.plot = None pd.save() response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") self.assertEqual(field.contents(), "-") # default empty value @ignore_warnings(category=RemovedInDjango60Warning) def test_readonly_field_overrides(self): """ Regression test for #22087 - ModelForm Meta overrides are ignored by AdminReadonlyField """ p = FieldOverridePost.objects.create(title="Test Post", content="Test Content") response = self.client.get( reverse("admin:admin_views_fieldoverridepost_change", args=(p.pk,)) ) self.assertContains( response, '<div class="help"><div>Overridden help text for the date</div></div>', html=True, ) self.assertContains( response, '<label for="id_public">Overridden public label:</label>', html=True, ) self.assertNotContains( response, "Some help text for the date (with Unicode ŠĐĆŽćžšđ)" ) def test_correct_autoescaping(self): """ Make sure that non-field readonly elements are properly autoescaped (#24461) """ section = Section.objects.create(name="<a>evil</a>") response = self.client.get( reverse("admin:admin_views_section_change", args=(section.pk,)) ) self.assertNotContains(response, "<a>evil</a>", status_code=200) self.assertContains(response, "&lt;a&gt;evil&lt;/a&gt;", status_code=200) def test_label_suffix_translated(self): pizza = Pizza.objects.create(name="Americano") url = reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) with self.settings(LANGUAGE_CODE="fr"): response = self.client.get(url) self.assertContains(response, "<label>Toppings\u00A0:</label>", html=True) @override_settings(ROOT_URLCONF="admin_views.urls") class LimitChoicesToInAdminTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to_as_callable(self): """Test for ticket 2445 changes to admin.""" threepwood = Character.objects.create( username="threepwood", last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) marley = Character.objects.create( username="marley", last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) response = self.client.get(reverse("admin:admin_views_stumpjoke_add")) # The allowed option should appear twice; the limited option should not appear. self.assertContains(response, threepwood.username, count=2) self.assertNotContains(response, marley.username) @override_settings(ROOT_URLCONF="admin_views.urls") class RawIdFieldsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to(self): """Regression test for 14880""" actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") Inquisition.objects.create(expected=False, leader=actor, country="Spain") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_inquisition"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step also tests integers, strings and booleans in the # lookup query string; in model we define inquisition field to have a # limit_choices_to option that includes a filter on a string field # (inquisition__actor__name), a filter on an integer field # (inquisition__actor__age), and a filter on a boolean field # (inquisition__expected). response2 = self.client.get(popup_url) self.assertContains(response2, "Spain") self.assertNotContains(response2, "England") def test_limit_choices_to_isnull_false(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant0"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=0 gets parsed correctly from the # lookup query string; in model we define defendant0 field to have a # limit_choices_to option that includes "actor__title__isnull=False". response2 = self.client.get(popup_url) self.assertContains(response2, "Kilbraken") self.assertNotContains(response2, "Palin") def test_limit_choices_to_isnull_true(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant1"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=1 gets parsed correctly from the # lookup query string; in model we define defendant1 field to have a # limit_choices_to option that includes "actor__title__isnull=True". response2 = self.client.get(popup_url) self.assertNotContains(response2, "Kilbraken") self.assertContains(response2, "Palin") def test_list_display_method_same_name_as_reverse_accessor(self): """ Should be able to use a ModelAdmin method in list_display that has the same name as a reverse model field ("sketch" in this case). """ actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") response = self.client.get(reverse("admin:admin_views_inquisition_changelist")) self.assertContains(response, "list-display-sketch") @override_settings(ROOT_URLCONF="admin_views.urls") class UserAdminTest(TestCase): """ Tests user CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", }, ) new_user = User.objects.get(username="newuser") self.assertRedirects( response, reverse("admin:auth_user_change", args=(new_user.pk,)) ) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_save_continue_editing_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_continue": "1", }, ) new_user = User.objects.get(username="newuser") new_user_url = reverse("admin:auth_user_change", args=(new_user.pk,)) self.assertRedirects(response, new_user_url, fetch_redirect_response=False) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) response = self.client.get(new_user_url) self.assertContains( response, '<li class="success">The user “<a href="%s">' "%s</a>” was added successfully. You may edit it again below.</li>" % (new_user_url, new_user), html=True, ) def test_password_mismatch(self): response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "mismatch", }, ) self.assertEqual(response.status_code, 200) self.assertFormError(response.context["adminform"], "password1", []) self.assertFormError( response.context["adminform"], "password2", ["The two password fields didn’t match."], ) def test_user_fk_add_popup(self): """ User addition through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains(response, reverse("admin:auth_user_add")) self.assertContains( response, 'class="related-widget-wrapper-link add-related" id="add_id_owner"', ) response = self.client.get( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR ) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR, data, follow=True ) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") def test_user_fk_change_popup(self): """ User change through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_change", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_change", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") self.assertContains(response, "&quot;action&quot;: &quot;change&quot;") def test_user_fk_delete_popup(self): """ User deletion through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_delete", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_delete", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertEqual(response.status_code, 200) data = { "post": "yes", IS_POPUP_VAR: "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;action&quot;: &quot;delete&quot;") def test_save_add_another_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_addanother": "1", }, ) new_user = User.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_user_add")) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_user_permission_performance(self): u = User.objects.all()[0] # Don't depend on a warm cache, see #17377. ContentType.objects.clear_cache() expected_num_queries = 10 if connection.features.uses_savepoints else 8 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_user_change", args=(u.pk,))) self.assertEqual(response.status_code, 200) def test_form_url_present_in_context(self): u = User.objects.all()[0] response = self.client.get( reverse("admin3:auth_user_password_change", args=(u.pk,)) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.context["form_url"], "pony") @override_settings(ROOT_URLCONF="admin_views.urls") class GroupAdminTest(TestCase): """ Tests group CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): group_count = Group.objects.count() response = self.client.post( reverse("admin:auth_group_add"), { "name": "newgroup", }, ) Group.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_group_changelist")) self.assertEqual(Group.objects.count(), group_count + 1) def test_group_permission_performance(self): g = Group.objects.create(name="test_group") # Ensure no queries are skipped due to cached content type for Group. ContentType.objects.clear_cache() expected_num_queries = 8 if connection.features.uses_savepoints else 6 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_group_change", args=(g.pk,))) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class CSSTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) @ignore_warnings(category=RemovedInDjango60Warning) def test_field_prefix_css_classes(self): """ Fields have a CSS class name with a 'field-' prefix. """ response = self.client.get(reverse("admin:admin_views_post_add")) # The main form self.assertContains(response, 'class="form-row field-title"') self.assertContains(response, 'class="form-row field-content"') self.assertContains(response, 'class="form-row field-public"') self.assertContains(response, 'class="form-row field-awesomeness_level"') self.assertContains(response, 'class="form-row field-coolness"') self.assertContains(response, 'class="form-row field-value"') self.assertContains(response, 'class="form-row"') # The lambda function # The tabular inline self.assertContains(response, '<td class="field-url">') self.assertContains(response, '<td class="field-posted">') def test_index_css_classes(self): """ CSS class names are used for each app and model on the admin index pages (#17050). """ # General index page response = self.client.get(reverse("admin:index")) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') # App index page response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') def test_app_model_in_form_body_class(self): """ Ensure app and model tag are correctly read by change_form template """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_list_body_class(self): """ Ensure app and model tag are correctly read by change_list template """ response = self.client.get(reverse("admin:admin_views_section_changelist")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_delete_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_confirmation template """ response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_app_index_body_class(self): """ Ensure app and model tag are correctly read by app_index template """ response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<body class=" dashboard app-admin_views') def test_app_model_in_delete_selected_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_selected_confirmation template """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "delete_selected", "index": 0, } response = self.client.post( reverse("admin:admin_views_section_changelist"), action_data ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_changelist_field_classes(self): """ Cells of the change list table should contain the field name in their class attribute. """ Podcast.objects.create(name="Django Dose", release_date=datetime.date.today()) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertContains(response, '<th class="field-name">') self.assertContains(response, '<td class="field-release_date nowrap">') self.assertContains(response, '<td class="action-checkbox">') try: import docutils except ImportError: docutils = None @unittest.skipUnless(docutils, "no docutils installed.") @override_settings(ROOT_URLCONF="admin_views.urls") @modify_settings( INSTALLED_APPS={"append": ["django.contrib.admindocs", "django.contrib.flatpages"]} ) class AdminDocsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_tags(self): response = self.client.get(reverse("django-admindocs-tags")) # The builtin tag group exists self.assertContains(response, "<h2>Built-in tags</h2>", count=2, html=True) # A builtin tag exists in both the index and detail self.assertContains( response, '<h3 id="built_in-autoescape">autoescape</h3>', html=True ) self.assertContains( response, '<li><a href="#built_in-autoescape">autoescape</a></li>', html=True, ) # An app tag exists in both the index and detail self.assertContains( response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>', html=True ) self.assertContains( response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>', html=True, ) # The admin list tag group exists self.assertContains(response, "<h2>admin_list</h2>", count=2, html=True) # An admin list tag exists in both the index and detail self.assertContains( response, '<h3 id="admin_list-admin_actions">admin_actions</h3>', html=True ) self.assertContains( response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>', html=True, ) def test_filters(self): response = self.client.get(reverse("django-admindocs-filters")) # The builtin filter group exists self.assertContains(response, "<h2>Built-in filters</h2>", count=2, html=True) # A builtin filter exists in both the index and detail self.assertContains(response, '<h3 id="built_in-add">add</h3>', html=True) self.assertContains( response, '<li><a href="#built_in-add">add</a></li>', html=True ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class ValidXHTMLTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_lang_name_present(self): with translation.override(None): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertNotContains(response, ' lang=""') self.assertNotContains(response, ' xml:lang=""') @override_settings(ROOT_URLCONF="admin_views.urls", USE_THOUSAND_SEPARATOR=True) class DateHierarchyTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def assert_non_localized_year(self, response, year): """ The year is not localized with USE_THOUSAND_SEPARATOR (#15234). """ self.assertNotContains(response, formats.number_format(year)) def assert_contains_year_link(self, response, date): self.assertContains(response, '?release_date__year=%d"' % date.year) def assert_contains_month_link(self, response, date): self.assertContains( response, '?release_date__month=%d&amp;release_date__year=%d"' % (date.month, date.year), ) def assert_contains_day_link(self, response, date): self.assertContains( response, "?release_date__day=%d&amp;" 'release_date__month=%d&amp;release_date__year=%d"' % (date.day, date.month, date.year), ) def test_empty(self): """ No date hierarchy links display with empty changelist. """ response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertNotContains(response, "release_date__year=") self.assertNotContains(response, "release_date__month=") self.assertNotContains(response, "release_date__day=") def test_single(self): """ Single day-level date hierarchy appears for single object. """ DATE = datetime.date(2000, 6, 30) Podcast.objects.create(release_date=DATE) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) self.assert_contains_day_link(response, DATE) self.assert_non_localized_year(response, 2000) def test_within_month(self): """ day-level links appear for changelist within single month. """ DATES = ( datetime.date(2000, 6, 30), datetime.date(2000, 6, 15), datetime.date(2000, 6, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) for date in DATES: self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) def test_within_year(self): """ month-level links appear for changelist within single year. """ DATES = ( datetime.date(2000, 1, 30), datetime.date(2000, 3, 15), datetime.date(2000, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) # no day-level links self.assertNotContains(response, "release_date__day=") for date in DATES: self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) def test_multiple_years(self): """ year-level links appear for year-spanning changelist. """ DATES = ( datetime.date(2001, 1, 30), datetime.date(2003, 3, 15), datetime.date(2005, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) # no day/month-level links self.assertNotContains(response, "release_date__day=") self.assertNotContains(response, "release_date__month=") for date in DATES: self.assert_contains_year_link(response, date) # and make sure GET parameters still behave correctly for date in DATES: url = "%s?release_date__year=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, ) response = self.client.get(url) self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) url = "%s?release_date__year=%d&release_date__month=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, date.month, ) response = self.client.get(url) self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) def test_related_field(self): questions_data = ( # (posted data, number of answers), (datetime.date(2001, 1, 30), 0), (datetime.date(2003, 3, 15), 1), (datetime.date(2005, 5, 3), 2), ) for date, answer_count in questions_data: question = Question.objects.create(posted=date) for i in range(answer_count): question.answer_set.create() response = self.client.get(reverse("admin:admin_views_answer_changelist")) for date, answer_count in questions_data: link = '?question__posted__year=%d"' % date.year if answer_count > 0: self.assertContains(response, link) else: self.assertNotContains(response, link) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomSaveRelatedTests(TestCase): """ One can easily customize the way related objects are saved. Refs #16115. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_should_be_able_to_edit_related_objects_on_add_view(self): post = { "child_set-TOTAL_FORMS": "3", "child_set-INITIAL_FORMS": "0", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-1-name": "Catherine", } self.client.post(reverse("admin:admin_views_parent_add"), post) self.assertEqual(1, Parent.objects.count()) self.assertEqual(2, Child.objects.count()) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_change_view(self): parent = Parent.objects.create(name="Josh Stone") paul = Child.objects.create(parent=parent, name="Paul") catherine = Child.objects.create(parent=parent, name="Catherine") post = { "child_set-TOTAL_FORMS": "5", "child_set-INITIAL_FORMS": "2", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-0-id": paul.id, "child_set-1-name": "Catherine", "child_set-1-id": catherine.id, } self.client.post( reverse("admin:admin_views_parent_change", args=(parent.id,)), post ) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_changelist_view(self): parent = Parent.objects.create(name="Josh Rock") Child.objects.create(parent=parent, name="Paul") Child.objects.create(parent=parent, name="Catherine") post = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": parent.id, "form-0-name": "Josh Stone", "_save": "Save", } self.client.post(reverse("admin:admin_views_parent_changelist"), post) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewLogoutTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def test_logout(self): self.client.force_login(self.superuser) response = self.client.post(reverse("admin:logout")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "registration/logged_out.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:logout")) self.assertFalse(response.context["has_permission"]) self.assertNotContains( response, "user-tools" ) # user-tools div shouldn't visible. def test_client_logout_url_can_be_used_to_login(self): response = self.client.post(reverse("admin:logout")) self.assertEqual( response.status_code, 302 ) # we should be redirected to the login page. # follow the redirect and test results. response = self.client.post(reverse("admin:logout"), follow=True) self.assertContains( response, '<input type="hidden" name="next" value="%s">' % reverse("admin:index"), ) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:login")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminUserMessageTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def send_message(self, level): """ Helper that sends a post to the dummy test methods and asserts that a message with the level has appeared in the response. """ action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_%s" % level, "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="%s">Test %s</li>' % (level, level), html=True ) @override_settings(MESSAGE_LEVEL=10) # Set to DEBUG for this request def test_message_debug(self): self.send_message("debug") def test_message_info(self): self.send_message("info") def test_message_success(self): self.send_message("success") def test_message_warning(self): self.send_message("warning") def test_message_error(self): self.send_message("error") def test_message_extra_tags(self): action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_extra_tags", "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="extra_tag info">Test tags</li>', html=True ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminKeepChangeListFiltersTests(TestCase): admin_site = site @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) def setUp(self): self.client.force_login(self.superuser) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are equal despite the ordering of their querystring. Refs #22360. """ parsed_url1 = urlparse(url1) path1 = parsed_url1.path parsed_qs1 = dict(parse_qsl(parsed_url1.query)) parsed_url2 = urlparse(url2) path2 = parsed_url2.path parsed_qs2 = dict(parse_qsl(parsed_url2.query)) for parsed_qs in [parsed_qs1, parsed_qs2]: if "_changelist_filters" in parsed_qs: changelist_filters = parsed_qs["_changelist_filters"] parsed_filters = dict(parse_qsl(changelist_filters)) parsed_qs["_changelist_filters"] = parsed_filters self.assertEqual(path1, path2) self.assertEqual(parsed_qs1, parsed_qs2) def test_assert_url_equal(self): # Test equality. change_user_url = reverse( "admin:auth_user_change", args=(self.joepublicuser.pk,) ) self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Test inequality. with self.assertRaises(AssertionError): self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D1%26is_superuser__exact%3D1".format(change_user_url), ) # Ignore scheme and host. self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Ignore ordering of querystring. self.assertURLEqual( "{}?is_staff__exact=0&is_superuser__exact=0".format( reverse("admin:auth_user_changelist") ), "{}?is_superuser__exact=0&is_staff__exact=0".format( reverse("admin:auth_user_changelist") ), ) # Ignore ordering of _changelist_filters. self.assertURLEqual( "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_superuser__exact%3D0%26is_staff__exact%3D0".format(change_user_url), ) def get_changelist_filters(self): return { "is_superuser__exact": 0, "is_staff__exact": 0, } def get_changelist_filters_querystring(self): return urlencode(self.get_changelist_filters()) def get_preserved_filters_querystring(self): return urlencode( {"_changelist_filters": self.get_changelist_filters_querystring()} ) def get_sample_user_id(self): return self.joepublicuser.pk def get_changelist_url(self): return "%s?%s" % ( reverse("admin:auth_user_changelist", current_app=self.admin_site.name), self.get_changelist_filters_querystring(), ) def get_add_url(self, add_preserved_filters=True): url = reverse("admin:auth_user_add", current_app=self.admin_site.name) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_change_url(self, user_id=None, add_preserved_filters=True): if user_id is None: user_id = self.get_sample_user_id() url = reverse( "admin:auth_user_change", args=(user_id,), current_app=self.admin_site.name ) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_history_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_history", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def get_delete_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_delete", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def test_changelist_view(self): response = self.client.get(self.get_changelist_url()) self.assertEqual(response.status_code, 200) # Check the `change_view` link has the correct querystring. detail_link = re.search( '<a href="(.*?)">{}</a>'.format(self.joepublicuser.username), response.content.decode(), ) self.assertURLEqual(detail_link[1], self.get_change_url()) def test_change_view(self): # Get the `change_view`. response = self.client.get(self.get_change_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) # Check the history link. history_link = re.search( '<a href="(.*?)" class="historylink">History</a>', response.content.decode() ) self.assertURLEqual(history_link[1], self.get_history_url()) # Check the delete link. delete_link = re.search( '<a href="(.*?)" class="deletelink">Delete</a>', response.content.decode() ) self.assertURLEqual(delete_link[1], self.get_delete_url()) # Test redirect on "Save". post_data = { "username": "joepublic", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", } post_data["_save"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_changelist_url()) post_data.pop("_save") # Test redirect on "Save and continue". post_data["_continue"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_change_url()) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["_addanother"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_change_view_close_link(self): viewuser = User.objects.create_user( username="view", password="secret", is_staff=True ) viewuser.user_permissions.add( get_perm(User, get_permission_codename("view", User._meta)) ) self.client.force_login(viewuser) response = self.client.get(self.get_change_url()) close_link = re.search( '<a href="(.*?)" class="closelink">Close</a>', response.content.decode() ) close_link = close_link[1].replace("&amp;", "&") self.assertURLEqual(close_link, self.get_changelist_url()) def test_change_view_without_preserved_filters(self): response = self.client.get(self.get_change_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_add_view(self): # Get the `add_view`. response = self.client.get(self.get_add_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) post_data = { "username": "dummy", "password1": "test", "password2": "test", } # Test redirect on "Save". post_data["_save"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy").pk) ) post_data.pop("_save") # Test redirect on "Save and continue". post_data["username"] = "dummy2" post_data["_continue"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy2").pk) ) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["username"] = "dummy3" post_data["_addanother"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_add_view_without_preserved_filters(self): response = self.client.get(self.get_add_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_delete_view(self): # Test redirect on "Delete". response = self.client.post(self.get_delete_url(), {"post": "yes"}) self.assertRedirects(response, self.get_changelist_url()) def test_url_prefix(self): context = { "preserved_filters": self.get_preserved_filters_querystring(), "opts": User._meta, } prefixes = ("", "/prefix/", "/後台/") for prefix in prefixes: with self.subTest(prefix=prefix), override_script_prefix(prefix): url = reverse( "admin:auth_user_changelist", current_app=self.admin_site.name ) self.assertURLEqual( self.get_changelist_url(), add_preserved_filters(context, url), ) class NamespacedAdminKeepChangeListFiltersTests(AdminKeepChangeListFiltersTests): admin_site = site2 @override_settings(ROOT_URLCONF="admin_views.urls") class TestLabelVisibility(TestCase): """#11277 -Labels of hidden fields in admin were not hidden.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_all_fields_visible(self): response = self.client.get(reverse("admin:admin_views_emptymodelvisible_add")) self.assert_fieldline_visible(response) self.assert_field_visible(response, "first") self.assert_field_visible(response, "second") def test_all_fields_hidden(self): response = self.client.get(reverse("admin:admin_views_emptymodelhidden_add")) self.assert_fieldline_hidden(response) self.assert_field_hidden(response, "first") self.assert_field_hidden(response, "second") def test_mixin(self): response = self.client.get(reverse("admin:admin_views_emptymodelmixin_add")) self.assert_fieldline_visible(response) self.assert_field_hidden(response, "first") self.assert_field_visible(response, "second") def assert_field_visible(self, response, field_name): self.assertContains( response, f'<div class="flex-container fieldBox field-{field_name}">' ) def assert_field_hidden(self, response, field_name): self.assertContains( response, f'<div class="flex-container fieldBox field-{field_name} hidden">' ) def assert_fieldline_visible(self, response): self.assertContains(response, '<div class="form-row field-first field-second">') def assert_fieldline_hidden(self, response): self.assertContains(response, '<div class="form-row hidden') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewOnSiteTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_add_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data. Also, assertFormError() and assertFormSetError() is usable for admin forms and formsets. """ # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test1", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": "", "dependentchild_set-0-family_name": "Test2", } response = self.client.post( reverse("admin:admin_views_parentwithdependentchildren_add"), post_data ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormError(response.context["adminform"], None, []) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) self.assertFormSetError( response.context["inline_admin_formset"], None, None, [] ) def test_change_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data """ pwdc = ParentWithDependentChildren.objects.create( some_required_info=6, family_name="Test1" ) # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test2", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": str(pwdc.id), "dependentchild_set-0-family_name": "Test1", } response = self.client.post( reverse( "admin:admin_views_parentwithdependentchildren_change", args=(pwdc.id,) ), post_data, ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) def test_check(self): "The view_on_site value is either a boolean or a callable" try: admin = CityAdmin(City, AdminSite()) CityAdmin.view_on_site = True self.assertEqual(admin.check(), []) CityAdmin.view_on_site = False self.assertEqual(admin.check(), []) CityAdmin.view_on_site = lambda obj: obj.get_absolute_url() self.assertEqual(admin.check(), []) CityAdmin.view_on_site = [] self.assertEqual( admin.check(), [ Error( "The value of 'view_on_site' must be a callable or a boolean " "value.", obj=CityAdmin, id="admin.E025", ), ], ) finally: # Restore the original values for the benefit of other tests. CityAdmin.view_on_site = True def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, 1)) ) def test_true(self): "The default behavior is followed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_worker_change", args=(self.w1.pk,)) ) self.assertContains( response, '"/worker/%s/%s/"' % (self.w1.surname, self.w1.name) ) def test_missing_get_absolute_url(self): "None is returned if model doesn't have get_absolute_url" model_admin = ModelAdmin(Worker, None) self.assertIsNone(model_admin.get_view_on_site_url(Worker())) def test_custom_admin_site(self): model_admin = ModelAdmin(City, customadmin.site) content_type_pk = ContentType.objects.get_for_model(City).pk redirect_url = model_admin.get_view_on_site_url(self.c1) self.assertEqual( redirect_url, reverse( f"{customadmin.site.name}:view_on_site", kwargs={ "content_type_id": content_type_pk, "object_id": self.c1.pk, }, ), ) @override_settings(ROOT_URLCONF="admin_views.urls") class InlineAdminViewOnSiteTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_state_change", args=(self.s1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_true(self): "The 'View on site' button is displayed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.r1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) self.assertContains( response, '"/worker_inline/%s/%s/"' % (self.w1.surname, self.w1.name) ) @override_settings(ROOT_URLCONF="admin_views.urls") class GetFormsetsWithInlinesArgumentTest(TestCase): """ #23934 - When adding a new model instance in the admin, the 'obj' argument of get_formsets_with_inlines() should be None. When changing, it should be equal to the existing model instance. The GetFormsetsArgumentCheckingAdmin ModelAdmin throws an exception if obj is not None during add_view or obj is None during change_view. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_explicitly_provided_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) def test_implicitly_generated_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSiteFinalCatchAllPatternTests(TestCase): """ Verifies the behaviour of the admin catch-all view. * Anonynous/non-staff users are redirected to login for all URLs, whether otherwise valid or not. * APPEND_SLASH is applied for staff if needed. * Otherwise Http404. * Catch-all view disabled via AdminSite.final_catch_all_view. """ @classmethod def setUpTestData(cls): cls.staff_user = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) cls.non_staff_user = User.objects.create_user( username="user", password="secret", email="[email protected]", is_staff=False, ) def test_unknown_url_redirects_login_if_not_authenticated(self): unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), unknown_url) ) def test_unknown_url_404_if_authenticated(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_known_url_missing_slash_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist")[:-1] response = self.client.get(known_url) # Redirects with the next URL also missing the slash. self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_non_admin_url_shares_url_prefix(self): url = reverse("non_admin")[:-1] response = self.client.get(url) # Redirects with the next URL also missing the slash. self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_unkown_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json")[:-1] response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_query_string(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, f"{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_script_name(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1], SCRIPT_NAME="/prefix/") self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_script_name_query_string(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1], SCRIPT_NAME="/prefix/") self.assertRedirects( response, f"/prefix{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True, FORCE_SCRIPT_NAME="/prefix/") def test_missing_slash_append_slash_true_force_script_name(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_non_staff_user(self): self.client.force_login(self.non_staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/test_admin/admin/login/?next=/test_admin/admin/admin_views/article", ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_non_staff_user_query_string(self): self.client.force_login(self.non_staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, "/test_admin/admin/login/?next=/test_admin/admin/admin_views/article" "%3Fid%3D1", ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_single_model_no_append_slash(self): self.client.force_login(self.staff_user) known_url = reverse("admin9:admin_views_actor_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Same tests above with final_catch_all_view=False. def test_unknown_url_404_if_not_authenticated_without_final_catch_all_view(self): unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_unknown_url_404_if_authenticated_without_final_catch_all_view(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_auth_without_final_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin10:login"), known_url) ) def test_known_url_missing_slash_redirects_with_slash_if_not_auth_no_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, fetch_redirect_response=False ) def test_non_admin_url_shares_url_prefix_without_final_catch_all_view(self): url = reverse("non_admin10") response = self.client.get(url[:-1]) self.assertRedirects(response, url, status_code=301) def test_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin10:login"), url)) def test_unknown_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json")[:-1] response = self.client.get(url) # Matches test_admin/admin10/admin_views/article/<path:object_id>/ self.assertRedirects( response, url + "/", status_code=301, fetch_redirect_response=False ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url_without_final_catch_all_view( self, ): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_query_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, f"{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Outside admin. def test_non_admin_url_404_if_not_authenticated(self): unknown_url = "/unknown/" response = self.client.get(unknown_url) # Does not redirect to the admin login. self.assertEqual(response.status_code, 404)
09565dbd35856079cc29ffc1cec4dd25e22b5688b849dfb0c44b0f68f8925c9d
from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import reverse @override_settings(ROOT_URLCONF="admin_views.urls") class AdminBreadcrumbsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) def setUp(self): self.client.force_login(self.superuser) def test_breadcrumbs_absent(self): response = self.client.get(reverse("admin:index")) self.assertNotContains(response, '<nav aria-label="Breadcrumbs">') def test_breadcrumbs_present(self): response = self.client.get(reverse("admin:auth_user_add")) self.assertContains(response, '<nav aria-label="Breadcrumbs">') response = self.client.get( reverse("admin:app_list", kwargs={"app_label": "auth"}) ) self.assertContains(response, '<nav aria-label="Breadcrumbs">')
56f0fdbf559e37c22e4f405e1184754b818a8d83191de0cfd8c01ba353cc55b4
import sys import unittest from django.conf import settings from django.contrib import admin from django.contrib.admindocs import utils, views from django.contrib.admindocs.views import get_return_data_type, simplify_regex from django.contrib.sites.models import Site from django.db import models from django.db.models import fields from django.test import SimpleTestCase, modify_settings, override_settings from django.test.utils import captured_stderr from django.urls import include, path, reverse from django.utils.functional import SimpleLazyObject from .models import Company, Person from .tests import AdminDocsTestCase, TestDataMixin @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) def test_index(self): response = self.client.get(reverse("django-admindocs-docroot")) self.assertContains(response, "<h1>Documentation</h1>", html=True) self.assertContains( response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>', ) self.client.logout() response = self.client.get(reverse("django-admindocs-docroot"), follow=True) # Should display the login screen self.assertContains( response, '<input type="hidden" name="next" value="/admindocs/">', html=True ) def test_bookmarklets(self): response = self.client.get(reverse("django-admindocs-bookmarklets")) self.assertContains(response, "/admindocs/views/") def test_templatetag_index(self): response = self.client.get(reverse("django-admindocs-tags")) self.assertContains( response, '<h3 id="built_in-extends">extends</h3>', html=True ) def test_templatefilter_index(self): response = self.client.get(reverse("django-admindocs-filters")) self.assertContains(response, '<h3 id="built_in-first">first</h3>', html=True) def test_view_index(self): response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains( response, '<h3><a href="/admindocs/views/django.contrib.admindocs.views.' 'BaseAdminDocsView/">/admindocs/</a></h3>', html=True, ) self.assertContains(response, "Views by namespace test") self.assertContains(response, "Name: <code>test:func</code>.") self.assertContains( response, '<h3><a href="/admindocs/views/admin_docs.views.XViewCallableObject/">' "/xview/callable_object_without_xview/</a></h3>", html=True, ) def test_view_index_with_method(self): """ Views that are methods are listed correctly. """ response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains( response, "<h3>" '<a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">' "/admin/</a></h3>", html=True, ) def test_view_detail(self): url = reverse( "django-admindocs-views-detail", args=["django.contrib.admindocs.views.BaseAdminDocsView"], ) response = self.client.get(url) # View docstring self.assertContains(response, "Base view for admindocs views.") @override_settings(ROOT_URLCONF="admin_docs.namespace_urls") def test_namespaced_view_detail(self): url = reverse( "django-admindocs-views-detail", args=["admin_docs.views.XViewClass"] ) response = self.client.get(url) self.assertContains(response, "<h1>admin_docs.views.XViewClass</h1>") def test_view_detail_illegal_import(self): url = reverse( "django-admindocs-views-detail", args=["urlpatterns_reverse.nonimported_module.view"], ) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) def test_view_detail_as_method(self): """ Views that are methods can be displayed. """ url = reverse( "django-admindocs-views-detail", args=["django.contrib.admin.sites.AdminSite.index"], ) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_model_index(self): response = self.client.get(reverse("django-admindocs-models-index")) self.assertContains( response, '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)' "</h2>", html=True, ) def test_template_detail(self): response = self.client.get( reverse( "django-admindocs-templates", args=["admin_doc/template_detail.html"] ) ) self.assertContains( response, "<h1>Template: <q>admin_doc/template_detail.html</q></h1>", html=True, ) def test_missing_docutils(self): utils.docutils_is_available = False try: response = self.client.get(reverse("django-admindocs-docroot")) self.assertContains( response, "<h3>The admin documentation system requires Python’s " '<a href="https://docutils.sourceforge.io/">docutils</a> ' "library.</h3>" "<p>Please ask your administrators to install " '<a href="https://pypi.org/project/docutils/">docutils</a>.</p>', html=True, ) self.assertContains( response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>', ) finally: utils.docutils_is_available = True @modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}) @override_settings(SITE_ID=None) # will restore SITE_ID after the test def test_no_sites_framework(self): """ Without the sites framework, should not access SITE_ID or Site objects. Deleting settings is fine here as UserSettingsHolder is used. """ Site.objects.all().delete() del settings.SITE_ID response = self.client.get(reverse("django-admindocs-views-index")) self.assertContains(response, "View documentation") def test_callable_urlconf(self): """ Index view should correctly resolve view patterns when ROOT_URLCONF is not a string. """ def urlpatterns(): return ( path("admin/doc/", include("django.contrib.admindocs.urls")), path("admin/", admin.site.urls), ) with self.settings(ROOT_URLCONF=SimpleLazyObject(urlpatterns)): response = self.client.get(reverse("django-admindocs-views-index")) self.assertEqual(response.status_code, 200) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) def test_template_detail_path_traversal(self): cases = ["/etc/passwd", "../passwd"] for fpath in cases: with self.subTest(path=fpath): response = self.client.get( reverse("django-admindocs-templates", args=[fpath]), ) self.assertEqual(response.status_code, 400) @override_settings( TEMPLATES=[ { "NAME": "ONE", "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, { "NAME": "TWO", "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, ] ) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class AdminDocViewWithMultipleEngines(AdminDocViewTests): def test_templatefilter_index(self): # Overridden because non-trivial TEMPLATES settings aren't supported # but the page shouldn't crash (#24125). response = self.client.get(reverse("django-admindocs-filters")) self.assertContains(response, "<title>Template filters</title>", html=True) def test_templatetag_index(self): # Overridden because non-trivial TEMPLATES settings aren't supported # but the page shouldn't crash (#24125). response = self.client.get(reverse("django-admindocs-tags")) self.assertContains(response, "<title>Template tags</title>", html=True) @unittest.skipUnless(utils.docutils_is_available, "no docutils installed.") class TestModelDetailView(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) with captured_stderr() as self.docutils_stderr: self.response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "Person"]) ) def test_method_excludes(self): """ Methods that begin with strings defined in ``django.contrib.admindocs.views.MODEL_METHODS_EXCLUDE`` shouldn't be displayed in the admin docs. """ self.assertContains(self.response, "<td>get_full_name</td>") self.assertNotContains(self.response, "<td>_get_full_name</td>") self.assertNotContains(self.response, "<td>add_image</td>") self.assertNotContains(self.response, "<td>delete_image</td>") self.assertNotContains(self.response, "<td>set_status</td>") self.assertNotContains(self.response, "<td>save_changes</td>") def test_methods_with_arguments(self): """ Methods that take arguments should also displayed. """ self.assertContains(self.response, "<h3>Methods with arguments</h3>") self.assertContains(self.response, "<td>rename_company</td>") self.assertContains(self.response, "<td>dummy_function</td>") self.assertContains(self.response, "<td>suffix_company_name</td>") def test_methods_with_arguments_display_arguments(self): """ Methods with arguments should have their arguments displayed. """ self.assertContains(self.response, "<td>new_name</td>") def test_methods_with_arguments_display_arguments_default_value(self): """ Methods with keyword arguments should have their arguments displayed. """ self.assertContains(self.response, "<td>suffix=&#x27;ltd&#x27;</td>") def test_methods_with_multiple_arguments_display_arguments(self): """ Methods with multiple arguments should have all their arguments displayed, but omitting 'self'. """ self.assertContains( self.response, "<td>baz, rox, *some_args, **some_kwargs</td>" ) def test_instance_of_property_methods_are_displayed(self): """Model properties are displayed as fields.""" self.assertContains(self.response, "<td>a_property</td>") def test_instance_of_cached_property_methods_are_displayed(self): """Model cached properties are displayed as fields.""" self.assertContains(self.response, "<td>a_cached_property</td>") def test_method_data_types(self): company = Company.objects.create(name="Django") person = Person.objects.create( first_name="Human", last_name="User", company=company ) self.assertEqual( get_return_data_type(person.get_status_count.__name__), "Integer" ) self.assertEqual(get_return_data_type(person.get_groups_list.__name__), "List") def test_descriptions_render_correctly(self): """ The ``description`` field should render correctly for each field type. """ # help text in fields self.assertContains( self.response, "<td>first name - The person's first name</td>" ) self.assertContains( self.response, "<td>last name - The person's last name</td>" ) # method docstrings self.assertContains(self.response, "<p>Get the full name of the person</p>") link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>' markup = "<p>the related %s object</p>" company_markup = markup % (link % ("admin_docs.company", "admin_docs.Company")) # foreign keys self.assertContains(self.response, company_markup) # foreign keys with help text self.assertContains(self.response, "%s\n - place of work" % company_markup) # many to many fields self.assertContains( self.response, "number of related %s objects" % (link % ("admin_docs.group", "admin_docs.Group")), ) self.assertContains( self.response, "all related %s objects" % (link % ("admin_docs.group", "admin_docs.Group")), ) # "raw" and "include" directives are disabled self.assertContains( self.response, "<p>&quot;raw&quot; directive disabled.</p>", ) self.assertContains( self.response, ".. raw:: html\n :file: admin_docs/evilfile.txt" ) self.assertContains( self.response, "<p>&quot;include&quot; directive disabled.</p>", ) self.assertContains(self.response, ".. include:: admin_docs/evilfile.txt") out = self.docutils_stderr.getvalue() self.assertIn('"raw" directive disabled', out) self.assertIn('"include" directive disabled', out) def test_model_with_many_to_one(self): link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>' response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "company"]) ) self.assertContains( response, "number of related %s objects" % (link % ("admin_docs.person", "admin_docs.Person")), ) self.assertContains( response, "all related %s objects" % (link % ("admin_docs.person", "admin_docs.Person")), ) def test_model_with_no_backward_relations_render_only_relevant_fields(self): """ A model with ``related_name`` of `+` shouldn't show backward relationship links. """ response = self.client.get( reverse("django-admindocs-models-detail", args=["admin_docs", "family"]) ) fields = response.context_data.get("fields") self.assertEqual(len(fields), 2) def test_model_docstring_renders_correctly(self): summary = ( '<h2 class="subhead"><p>Stores information about a person, related to ' '<a class="reference external" href="/admindocs/models/myapp.company/">' "myapp.Company</a>.</p></h2>" ) subheading = "<p><strong>Notes</strong></p>" body = ( '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this ' "object.</p>" ) model_body = ( '<dl class="docutils"><dt><tt class="' 'docutils literal">company</tt></dt><dd>Field storing <a class="' 'reference external" href="/admindocs/models/myapp.company/">' "myapp.Company</a> where the person works.</dd></dl>" ) self.assertContains(self.response, "DESCRIPTION") self.assertContains(self.response, summary, html=True) self.assertContains(self.response, subheading, html=True) self.assertContains(self.response, body, html=True) self.assertContains(self.response, model_body, html=True) def test_model_detail_title(self): self.assertContains(self.response, "<h1>admin_docs.Person</h1>", html=True) def test_app_not_found(self): response = self.client.get( reverse("django-admindocs-models-detail", args=["doesnotexist", "Person"]) ) self.assertEqual(response.context["exception"], "App 'doesnotexist' not found") self.assertEqual(response.status_code, 404) def test_model_not_found(self): response = self.client.get( reverse( "django-admindocs-models-detail", args=["admin_docs", "doesnotexist"] ) ) self.assertEqual( response.context["exception"], "Model 'doesnotexist' not found in app 'admin_docs'", ) self.assertEqual(response.status_code, 404) class CustomField(models.Field): description = "A custom field type" class DescriptionLackingField(models.Field): pass class TestFieldType(unittest.TestCase): def test_field_name(self): with self.assertRaises(AttributeError): views.get_readable_field_data_type("NotAField") def test_builtin_fields(self): self.assertEqual( views.get_readable_field_data_type(fields.BooleanField()), "Boolean (Either True or False)", ) def test_char_fields(self): self.assertEqual( views.get_readable_field_data_type(fields.CharField(max_length=255)), "String (up to 255)", ) self.assertEqual( views.get_readable_field_data_type(fields.CharField()), "String (unlimited)", ) def test_custom_fields(self): self.assertEqual( views.get_readable_field_data_type(CustomField()), "A custom field type" ) self.assertEqual( views.get_readable_field_data_type(DescriptionLackingField()), "Field of type: DescriptionLackingField", ) class AdminDocViewFunctionsTests(SimpleTestCase): def test_simplify_regex(self): tests = ( # Named and unnamed groups. (r"^(?P<a>\w+)/b/(?P<c>\w+)/$", "/<a>/b/<c>/"), (r"^(?P<a>\w+)/b/(?P<c>\w+)$", "/<a>/b/<c>"), (r"^(?P<a>\w+)/b/(?P<c>\w+)", "/<a>/b/<c>"), (r"^(?P<a>\w+)/b/(\w+)$", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/(\w+)", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/((x|y)\w+)$", "/<a>/b/<var>"), (r"^(?P<a>\w+)/b/((x|y)\w+)", "/<a>/b/<var>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)$", "/<a>/b/<c>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)", "/<a>/b/<c>"), (r"^(?P<a>(x|y))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"), (r"^(?P<a>(x|y)(\(|\)))/b/(?P<c>\w+)ab", "/<a>/b/<c>ab"), # Non-capturing groups. (r"^a(?:\w+)b", "/ab"), (r"^a(?:(x|y))", "/a"), (r"^(?:\w+(?:\w+))a", "/a"), (r"^a(?:\w+)/b(?:\w+)", "/a/b"), (r"(?P<a>\w+)/b/(?:\w+)c(?:\w+)", "/<a>/b/c"), (r"(?P<a>\w+)/b/(\w+)/(?:\w+)c(?:\w+)", "/<a>/b/<var>/c"), # Single and repeated metacharacters. (r"^a", "/a"), (r"^^a", "/a"), (r"^^^a", "/a"), (r"a$", "/a"), (r"a$$", "/a"), (r"a$$$", "/a"), (r"a?", "/a"), (r"a??", "/a"), (r"a???", "/a"), (r"a*", "/a"), (r"a**", "/a"), (r"a***", "/a"), (r"a+", "/a"), (r"a++", "/a"), (r"a+++", "/a"), (r"\Aa", "/a"), (r"\A\Aa", "/a"), (r"\A\A\Aa", "/a"), (r"a\Z", "/a"), (r"a\Z\Z", "/a"), (r"a\Z\Z\Z", "/a"), (r"\ba", "/a"), (r"\b\ba", "/a"), (r"\b\b\ba", "/a"), (r"a\B", "/a"), (r"a\B\B", "/a"), (r"a\B\B\B", "/a"), # Multiple mixed metacharacters. (r"^a/?$", "/a/"), (r"\Aa\Z", "/a"), (r"\ba\B", "/a"), # Escaped single metacharacters. (r"\^a", r"/^a"), (r"\\^a", r"/\\a"), (r"\\\^a", r"/\\^a"), (r"\\\\^a", r"/\\\\a"), (r"\\\\\^a", r"/\\\\^a"), (r"a\$", r"/a$"), (r"a\\$", r"/a\\"), (r"a\\\$", r"/a\\$"), (r"a\\\\$", r"/a\\\\"), (r"a\\\\\$", r"/a\\\\$"), (r"a\?", r"/a?"), (r"a\\?", r"/a\\"), (r"a\\\?", r"/a\\?"), (r"a\\\\?", r"/a\\\\"), (r"a\\\\\?", r"/a\\\\?"), (r"a\*", r"/a*"), (r"a\\*", r"/a\\"), (r"a\\\*", r"/a\\*"), (r"a\\\\*", r"/a\\\\"), (r"a\\\\\*", r"/a\\\\*"), (r"a\+", r"/a+"), (r"a\\+", r"/a\\"), (r"a\\\+", r"/a\\+"), (r"a\\\\+", r"/a\\\\"), (r"a\\\\\+", r"/a\\\\+"), (r"\\Aa", r"/\Aa"), (r"\\\Aa", r"/\\a"), (r"\\\\Aa", r"/\\\Aa"), (r"\\\\\Aa", r"/\\\\a"), (r"\\\\\\Aa", r"/\\\\\Aa"), (r"a\\Z", r"/a\Z"), (r"a\\\Z", r"/a\\"), (r"a\\\\Z", r"/a\\\Z"), (r"a\\\\\Z", r"/a\\\\"), (r"a\\\\\\Z", r"/a\\\\\Z"), # Escaped mixed metacharacters. (r"^a\?$", r"/a?"), (r"^a\\?$", r"/a\\"), (r"^a\\\?$", r"/a\\?"), (r"^a\\\\?$", r"/a\\\\"), (r"^a\\\\\?$", r"/a\\\\?"), # Adjacent escaped metacharacters. (r"^a\?\$", r"/a?$"), (r"^a\\?\\$", r"/a\\\\"), (r"^a\\\?\\\$", r"/a\\?\\$"), (r"^a\\\\?\\\\$", r"/a\\\\\\\\"), (r"^a\\\\\?\\\\\$", r"/a\\\\?\\\\$"), # Complex examples with metacharacters and (un)named groups. (r"^\b(?P<slug>\w+)\B/(\w+)?", "/<slug>/<var>"), (r"^\A(?P<slug>\w+)\Z", "/<slug>"), ) for pattern, output in tests: with self.subTest(pattern=pattern): self.assertEqual(simplify_regex(pattern), output)
9eff01a7ef1d08710128bb999885bda823e3351d13bd8f23a4bc21ff6e681f71
from django.db.models import ProtectedError, Q, Sum from django.forms.models import modelform_factory from django.test import TestCase, skipIfDBFeature from .models import ( A, Address, B, Board, C, Cafe, CharLink, Company, Contact, Content, D, Guild, HasLinkThing, Link, Node, Note, OddRelation1, OddRelation2, Organization, Person, Place, Related, Restaurant, Tag, Team, TextLink, ) class GenericRelationTests(TestCase): def test_inherited_models_content_type(self): """ GenericRelations on inherited classes use the correct content type. """ p = Place.objects.create(name="South Park") r = Restaurant.objects.create(name="Chubby's") l1 = Link.objects.create(content_object=p) l2 = Link.objects.create(content_object=r) self.assertEqual(list(p.links.all()), [l1]) self.assertEqual(list(r.links.all()), [l2]) def test_reverse_relation_pk(self): """ The correct column name is used for the primary key on the originating model of a query. See #12664. """ p = Person.objects.create(account=23, name="Chef") Address.objects.create( street="123 Anywhere Place", city="Conifer", state="CO", zipcode="80433", content_object=p, ) qs = Person.objects.filter(addresses__zipcode="80433") self.assertEqual(1, qs.count()) self.assertEqual("Chef", qs[0].name) def test_charlink_delete(self): oddrel = OddRelation1.objects.create(name="clink") CharLink.objects.create(content_object=oddrel) oddrel.delete() def test_textlink_delete(self): oddrel = OddRelation2.objects.create(name="tlink") TextLink.objects.create(content_object=oddrel) oddrel.delete() def test_charlink_filter(self): oddrel = OddRelation1.objects.create(name="clink") CharLink.objects.create(content_object=oddrel, value="value") self.assertSequenceEqual( OddRelation1.objects.filter(clinks__value="value"), [oddrel] ) def test_textlink_filter(self): oddrel = OddRelation2.objects.create(name="clink") TextLink.objects.create(content_object=oddrel, value="value") self.assertSequenceEqual( OddRelation2.objects.filter(tlinks__value="value"), [oddrel] ) def test_coerce_object_id_remote_field_cache_persistence(self): restaurant = Restaurant.objects.create() CharLink.objects.create(content_object=restaurant) charlink = CharLink.objects.latest("pk") self.assertIs(charlink.content_object, charlink.content_object) # If the model (Cafe) uses more than one level of multi-table inheritance. cafe = Cafe.objects.create() CharLink.objects.create(content_object=cafe) charlink = CharLink.objects.latest("pk") self.assertIs(charlink.content_object, charlink.content_object) def test_q_object_or(self): """ SQL query parameters for generic relations are properly grouped when OR is used (#11535). In this bug the first query (below) works while the second, with the query parameters the same but in reverse order, does not. The issue is that the generic relation conditions do not get properly grouped in parentheses. """ note_contact = Contact.objects.create() org_contact = Contact.objects.create() Note.objects.create(note="note", content_object=note_contact) org = Organization.objects.create(name="org name") org.contacts.add(org_contact) # search with a non-matching note and a matching org name qs = Contact.objects.filter( Q(notes__note__icontains=r"other note") | Q(organizations__name__icontains=r"org name") ) self.assertIn(org_contact, qs) # search again, with the same query parameters, in reverse order qs = Contact.objects.filter( Q(organizations__name__icontains=r"org name") | Q(notes__note__icontains=r"other note") ) self.assertIn(org_contact, qs) def test_join_reuse(self): qs = Person.objects.filter(addresses__street="foo").filter( addresses__street="bar" ) self.assertEqual(str(qs.query).count("JOIN"), 2) def test_generic_relation_ordering(self): """ Ordering over a generic relation does not include extraneous duplicate results, nor excludes rows not participating in the relation. """ p1 = Place.objects.create(name="South Park") p2 = Place.objects.create(name="The City") c = Company.objects.create(name="Chubby's Intl.") Link.objects.create(content_object=p1) Link.objects.create(content_object=c) places = list(Place.objects.order_by("links__id")) def count_places(place): return len([p for p in places if p.id == place.id]) self.assertEqual(len(places), 2) self.assertEqual(count_places(p1), 1) self.assertEqual(count_places(p2), 1) def test_target_model_len_zero(self): """ Saving a model with a GenericForeignKey to a model instance whose __len__ method returns 0 (Team.__len__() here) shouldn't fail (#13085). """ team1 = Team.objects.create(name="Backend devs") note = Note(note="Deserve a bonus", content_object=team1) note.save() def test_target_model_bool_false(self): """ Saving a model with a GenericForeignKey to a model instance whose __bool__ method returns False (Guild.__bool__() here) shouldn't fail (#13085). """ g1 = Guild.objects.create(name="First guild") note = Note(note="Note for guild", content_object=g1) note.save() @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_gfk_to_model_with_empty_pk(self): """Test related to #13085""" # Saving model with GenericForeignKey to model instance with an # empty CharField PK b1 = Board.objects.create(name="") tag = Tag(label="VP", content_object=b1) tag.save() def test_ticket_20378(self): # Create a couple of extra HasLinkThing so that the autopk value # isn't the same for Link and HasLinkThing. hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() hs3 = HasLinkThing.objects.create() hs4 = HasLinkThing.objects.create() l1 = Link.objects.create(content_object=hs3) l2 = Link.objects.create(content_object=hs4) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l1), [hs3]) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l2), [hs4]) self.assertSequenceEqual( HasLinkThing.objects.exclude(links=l2), [hs1, hs2, hs3] ) self.assertSequenceEqual( HasLinkThing.objects.exclude(links=l1), [hs1, hs2, hs4] ) def test_ticket_20564(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() c1 = C.objects.create(b=b1) c2 = C.objects.create(b=b2) c3 = C.objects.create(b=b3) A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(C.objects.filter(b__a__flag=None), [c1, c3]) self.assertSequenceEqual(C.objects.exclude(b__a__flag=None), [c2]) def test_ticket_20564_nullable_fk(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() d1 = D.objects.create(b=b1) d2 = D.objects.create(b=b2) d3 = D.objects.create(b=b3) d4 = D.objects.create() A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(D.objects.exclude(b__a__flag=None), [d2]) self.assertSequenceEqual(D.objects.filter(b__a__flag=None), [d1, d3, d4]) self.assertSequenceEqual(B.objects.filter(a__flag=None), [b1, b3]) self.assertSequenceEqual(B.objects.exclude(a__flag=None), [b2]) def test_extra_join_condition(self): # A crude check that content_type_id is taken in account in the # join/subquery condition. self.assertIn( "content_type_id", str(B.objects.exclude(a__flag=None).query).lower() ) # No need for any joins - the join from inner query can be trimmed in # this case (but not in the above case as no a objects at all for given # B would then fail). self.assertNotIn(" join ", str(B.objects.exclude(a__flag=True).query).lower()) self.assertIn( "content_type_id", str(B.objects.exclude(a__flag=True).query).lower() ) def test_annotate(self): hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() HasLinkThing.objects.create() b = Board.objects.create(name=str(hs1.pk)) Link.objects.create(content_object=hs2) link = Link.objects.create(content_object=hs1) Link.objects.create(content_object=b) qs = HasLinkThing.objects.annotate(Sum("links")).filter(pk=hs1.pk) # If content_type restriction isn't in the query's join condition, # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, link.id) link.delete() # Now if we don't have proper left join, we will not produce any # results at all here. # clear cached results qs = qs.all() self.assertEqual(qs.count(), 1) # Note - 0 here would be a nicer result... self.assertIs(qs[0].links__sum, None) # Finally test that filtering works. self.assertEqual(qs.filter(links__sum__isnull=True).count(), 1) self.assertEqual(qs.filter(links__sum__isnull=False).count(), 0) def test_filter_targets_related_pk(self): # Use hardcoded PKs to ensure different PKs for "link" and "hs2" # objects. HasLinkThing.objects.create(pk=1) hs2 = HasLinkThing.objects.create(pk=2) link = Link.objects.create(content_object=hs2, pk=1) self.assertNotEqual(link.object_id, link.pk) self.assertSequenceEqual(HasLinkThing.objects.filter(links=link.pk), [hs2]) def test_editable_generic_rel(self): GenericRelationForm = modelform_factory(HasLinkThing, fields="__all__") form = GenericRelationForm() self.assertIn("links", form.fields) form = GenericRelationForm({"links": None}) self.assertTrue(form.is_valid()) form.save() links = HasLinkThing._meta.get_field("links") self.assertEqual(links.save_form_data_calls, 1) def test_ticket_22998(self): related = Related.objects.create() content = Content.objects.create(related_obj=related) Node.objects.create(content=content) # deleting the Related cascades to the Content cascades to the Node, # where the pre_delete signal should fire and prevent deletion. with self.assertRaises(ProtectedError): related.delete() def test_ticket_22982(self): place = Place.objects.create(name="My Place") self.assertIn("GenericRelatedObjectManager", str(place.links)) def test_filter_on_related_proxy_model(self): place = Place.objects.create() Link.objects.create(content_object=place) self.assertEqual(Place.objects.get(link_proxy__object_id=place.id), place) def test_generic_reverse_relation_with_mti(self): """ Filtering with a reverse generic relation, where the GenericRelation comes from multi-table inheritance. """ place = Place.objects.create(name="Test Place") link = Link.objects.create(content_object=place) result = Link.objects.filter(places=place) self.assertCountEqual(result, [link]) def test_generic_reverse_relation_with_abc(self): """ The reverse generic relation accessor (targets) is created if the GenericRelation comes from an abstract base model (HasLinks). """ thing = HasLinkThing.objects.create() link = Link.objects.create(content_object=thing) self.assertCountEqual(link.targets.all(), [thing]) def test_generic_reverse_relation_exclude_filter(self): place1 = Place.objects.create(name="Test Place 1") place2 = Place.objects.create(name="Test Place 2") Link.objects.create(content_object=place1) link2 = Link.objects.create(content_object=place2) qs = Link.objects.filter(~Q(places__name="Test Place 1")) self.assertSequenceEqual(qs, [link2]) qs = Link.objects.exclude(places__name="Test Place 1") self.assertSequenceEqual(qs, [link2])
f228f7c367d26b88c23a6b322a7b6cca1514cb007157548ebf5a35f18c14564d
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models __all__ = ( "Link", "Place", "Restaurant", "Person", "Address", "CharLink", "TextLink", "OddRelation1", "OddRelation2", "Contact", "Organization", "Note", "Company", ) class Link(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class LinkProxy(Link): class Meta: proxy = True class Place(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link, related_query_name="places") link_proxy = GenericRelation(LinkProxy) class Restaurant(Place): pass class Cafe(Restaurant): pass class Address(models.Model): street = models.CharField(max_length=80) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.CharField(max_length=5) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Person(models.Model): account = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) addresses = GenericRelation(Address) class CharLink(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.CharField(max_length=100) content_object = GenericForeignKey() value = models.CharField(max_length=250) class TextLink(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.TextField() content_object = GenericForeignKey() value = models.CharField(max_length=250) class OddRelation1(models.Model): name = models.CharField(max_length=100) clinks = GenericRelation(CharLink) class OddRelation2(models.Model): name = models.CharField(max_length=100) tlinks = GenericRelation(TextLink) # models for test_q_object_or: class Note(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() note = models.TextField() class Contact(models.Model): notes = GenericRelation(Note) class Organization(models.Model): name = models.CharField(max_length=255) contacts = models.ManyToManyField(Contact, related_name="organizations") class Company(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link) class Team(models.Model): name = models.CharField(max_length=15) def __len__(self): return 0 class Guild(models.Model): name = models.CharField(max_length=15) def __bool__(self): return False class Tag(models.Model): content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="g_r_r_tags" ) object_id = models.CharField(max_length=15) content_object = GenericForeignKey() label = models.CharField(max_length=15) class Board(models.Model): name = models.CharField(primary_key=True, max_length=25) class SpecialGenericRelation(GenericRelation): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.editable = True self.save_form_data_calls = 0 def save_form_data(self, *args, **kwargs): self.save_form_data_calls += 1 class HasLinks(models.Model): links = SpecialGenericRelation(Link, related_query_name="targets") class Meta: abstract = True class HasLinkThing(HasLinks): pass class A(models.Model): flag = models.BooleanField(null=True) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class B(models.Model): a = GenericRelation(A) class Meta: ordering = ("id",) class C(models.Model): b = models.ForeignKey(B, models.CASCADE) class Meta: ordering = ("id",) class D(models.Model): b = models.ForeignKey(B, models.SET_NULL, null=True) class Meta: ordering = ("id",) # Ticket #22998 class Node(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content = GenericForeignKey("content_type", "object_id") class Content(models.Model): nodes = GenericRelation(Node) related_obj = models.ForeignKey("Related", models.CASCADE) class Related(models.Model): pass def prevent_deletes(sender, instance, **kwargs): raise models.ProtectedError("Not allowed to delete.", [instance]) models.signals.pre_delete.connect(prevent_deletes, sender=Node)
bf33020663bd7a19a9f439e2240eb6635a6bd69514bab4d0ec10bf746705e20e
""" Test PostgreSQL full text search. These tests use dialogue from the 1975 film Monty Python and the Holy Grail. All text copyright Python (Monty) Pictures. Thanks to sacred-texts.com for the transcript. """ from django.db.models import F, Value from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase from .models import Character, Line, LineSavedSearch, Scene try: from django.contrib.postgres.search import ( SearchConfig, SearchHeadline, SearchQuery, SearchRank, SearchVector, ) except ImportError: pass class GrailTestData: @classmethod def setUpTestData(cls): cls.robin = Scene.objects.create( scene="Scene 10", setting="The dark forest of Ewing" ) cls.minstrel = Character.objects.create(name="Minstrel") verses = [ ( "Bravely bold Sir Robin, rode forth from Camelot. " "He was not afraid to die, o Brave Sir Robin. " "He was not at all afraid to be killed in nasty ways. " "Brave, brave, brave, brave Sir Robin" ), ( "He was not in the least bit scared to be mashed into a pulp, " "Or to have his eyes gouged out, and his elbows broken. " "To have his kneecaps split, and his body burned away, " "And his limbs all hacked and mangled, brave Sir Robin!" ), ( "His head smashed in and his heart cut out, " "And his liver removed and his bowels unplugged, " "And his nostrils ripped and his bottom burned off," "And his --" ), ] cls.verses = [ Line.objects.create( scene=cls.robin, character=cls.minstrel, dialogue=verse, ) for verse in verses ] cls.verse0, cls.verse1, cls.verse2 = cls.verses cls.witch_scene = Scene.objects.create( scene="Scene 5", setting="Sir Bedemir's Castle" ) bedemir = Character.objects.create(name="Bedemir") crowd = Character.objects.create(name="Crowd") witch = Character.objects.create(name="Witch") duck = Character.objects.create(name="Duck") cls.bedemir0 = Line.objects.create( scene=cls.witch_scene, character=bedemir, dialogue="We shall use my larger scales!", dialogue_config="english", ) cls.bedemir1 = Line.objects.create( scene=cls.witch_scene, character=bedemir, dialogue="Right, remove the supports!", dialogue_config="english", ) cls.duck = Line.objects.create( scene=cls.witch_scene, character=duck, dialogue=None ) cls.crowd = Line.objects.create( scene=cls.witch_scene, character=crowd, dialogue="A witch! A witch!" ) cls.witch = Line.objects.create( scene=cls.witch_scene, character=witch, dialogue="It's a fair cop." ) trojan_rabbit = Scene.objects.create( scene="Scene 8", setting="The castle of Our Master Ruiz' de lu la Ramper" ) guards = Character.objects.create(name="French Guards") cls.french = Line.objects.create( scene=trojan_rabbit, character=guards, dialogue="Oh. Un beau cadeau. Oui oui.", dialogue_config="french", ) class SimpleSearchTest(GrailTestData, PostgreSQLTestCase): def test_simple(self): searched = Line.objects.filter(dialogue__search="elbows") self.assertSequenceEqual(searched, [self.verse1]) def test_non_exact_match(self): self.check_default_text_search_config() searched = Line.objects.filter(dialogue__search="hearts") self.assertSequenceEqual(searched, [self.verse2]) def test_search_two_terms(self): self.check_default_text_search_config() searched = Line.objects.filter(dialogue__search="heart bowel") self.assertSequenceEqual(searched, [self.verse2]) def test_search_two_terms_with_partial_match(self): searched = Line.objects.filter(dialogue__search="Robin killed") self.assertSequenceEqual(searched, [self.verse0]) def test_search_query_config(self): searched = Line.objects.filter( dialogue__search=SearchQuery("nostrils", config="simple"), ) self.assertSequenceEqual(searched, [self.verse2]) def test_search_with_F_expression(self): # Non-matching query. LineSavedSearch.objects.create(line=self.verse1, query="hearts") # Matching query. match = LineSavedSearch.objects.create(line=self.verse1, query="elbows") for query_expression in [F("query"), SearchQuery(F("query"))]: with self.subTest(query_expression): searched = LineSavedSearch.objects.filter( line__dialogue__search=query_expression, ) self.assertSequenceEqual(searched, [match]) class SearchVectorFieldTest(GrailTestData, PostgreSQLTestCase): def test_existing_vector(self): Line.objects.update(dialogue_search_vector=SearchVector("dialogue")) searched = Line.objects.filter( dialogue_search_vector=SearchQuery("Robin killed") ) self.assertSequenceEqual(searched, [self.verse0]) def test_existing_vector_config_explicit(self): Line.objects.update(dialogue_search_vector=SearchVector("dialogue")) searched = Line.objects.filter( dialogue_search_vector=SearchQuery("cadeaux", config="french") ) self.assertSequenceEqual(searched, [self.french]) def test_single_coalesce_expression(self): searched = Line.objects.annotate(search=SearchVector("dialogue")).filter( search="cadeaux" ) self.assertNotIn("COALESCE(COALESCE", str(searched.query)) def test_values_with_percent(self): searched = Line.objects.annotate( search=SearchVector(Value("This week everything is 10% off")) ).filter(search="10 % off") self.assertEqual(len(searched), 9) class SearchConfigTests(PostgreSQLSimpleTestCase): def test_from_parameter(self): self.assertIsNone(SearchConfig.from_parameter(None)) self.assertEqual(SearchConfig.from_parameter("foo"), SearchConfig("foo")) self.assertEqual( SearchConfig.from_parameter(SearchConfig("bar")), SearchConfig("bar") ) class MultipleFieldsTest(GrailTestData, PostgreSQLTestCase): def test_simple_on_dialogue(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="elbows") self.assertSequenceEqual(searched, [self.verse1]) def test_simple_on_scene(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="Forest") self.assertCountEqual(searched, self.verses) def test_non_exact_match(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="heart") self.assertSequenceEqual(searched, [self.verse2]) def test_search_two_terms(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="heart forest") self.assertSequenceEqual(searched, [self.verse2]) def test_terms_adjacent(self): searched = Line.objects.annotate( search=SearchVector("character__name", "dialogue"), ).filter(search="minstrel") self.assertCountEqual(searched, self.verses) searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="minstrelbravely") self.assertSequenceEqual(searched, []) def test_search_with_null(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search="bedemir") self.assertCountEqual( searched, [self.bedemir0, self.bedemir1, self.crowd, self.witch, self.duck] ) def test_search_with_non_text(self): searched = Line.objects.annotate( search=SearchVector("id"), ).filter(search=str(self.crowd.id)) self.assertSequenceEqual(searched, [self.crowd]) def test_phrase_search(self): line_qs = Line.objects.annotate(search=SearchVector("dialogue")) searched = line_qs.filter( search=SearchQuery("burned body his away", search_type="phrase") ) self.assertSequenceEqual(searched, []) searched = line_qs.filter( search=SearchQuery("his body burned away", search_type="phrase") ) self.assertSequenceEqual(searched, [self.verse1]) def test_phrase_search_with_config(self): line_qs = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue", config="french"), ) searched = line_qs.filter( search=SearchQuery("cadeau beau un", search_type="phrase", config="french"), ) self.assertSequenceEqual(searched, []) searched = line_qs.filter( search=SearchQuery("un beau cadeau", search_type="phrase", config="french"), ) self.assertSequenceEqual(searched, [self.french]) def test_raw_search(self): line_qs = Line.objects.annotate(search=SearchVector("dialogue")) searched = line_qs.filter(search=SearchQuery("Robin", search_type="raw")) self.assertCountEqual(searched, [self.verse0, self.verse1]) searched = line_qs.filter( search=SearchQuery("Robin & !'Camelot'", search_type="raw") ) self.assertSequenceEqual(searched, [self.verse1]) def test_raw_search_with_config(self): line_qs = Line.objects.annotate( search=SearchVector("dialogue", config="french") ) searched = line_qs.filter( search=SearchQuery( "'cadeaux' & 'beaux'", search_type="raw", config="french" ), ) self.assertSequenceEqual(searched, [self.french]) def test_web_search(self): line_qs = Line.objects.annotate(search=SearchVector("dialogue")) searched = line_qs.filter( search=SearchQuery( '"burned body" "split kneecaps"', search_type="websearch", ), ) self.assertSequenceEqual(searched, []) searched = line_qs.filter( search=SearchQuery( '"body burned" "kneecaps split" -"nostrils"', search_type="websearch", ), ) self.assertSequenceEqual(searched, [self.verse1]) searched = line_qs.filter( search=SearchQuery( '"Sir Robin" ("kneecaps" OR "Camelot")', search_type="websearch", ), ) self.assertSequenceEqual(searched, [self.verse0, self.verse1]) def test_web_search_with_config(self): line_qs = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue", config="french"), ) searched = line_qs.filter( search=SearchQuery( "cadeau -beau", search_type="websearch", config="french" ), ) self.assertSequenceEqual(searched, []) searched = line_qs.filter( search=SearchQuery("beau cadeau", search_type="websearch", config="french"), ) self.assertSequenceEqual(searched, [self.french]) def test_bad_search_type(self): with self.assertRaisesMessage( ValueError, "Unknown search_type argument 'foo'." ): SearchQuery("kneecaps", search_type="foo") def test_config_query_explicit(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue", config="french"), ).filter(search=SearchQuery("cadeaux", config="french")) self.assertSequenceEqual(searched, [self.french]) def test_config_query_implicit(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue", config="french"), ).filter(search="cadeaux") self.assertSequenceEqual(searched, [self.french]) def test_config_from_field_explicit(self): searched = Line.objects.annotate( search=SearchVector( "scene__setting", "dialogue", config=F("dialogue_config") ), ).filter(search=SearchQuery("cadeaux", config=F("dialogue_config"))) self.assertSequenceEqual(searched, [self.french]) def test_config_from_field_implicit(self): searched = Line.objects.annotate( search=SearchVector( "scene__setting", "dialogue", config=F("dialogue_config") ), ).filter(search="cadeaux") self.assertSequenceEqual(searched, [self.french]) class TestCombinations(GrailTestData, PostgreSQLTestCase): def test_vector_add(self): searched = Line.objects.annotate( search=SearchVector("scene__setting") + SearchVector("character__name"), ).filter(search="bedemir") self.assertCountEqual( searched, [self.bedemir0, self.bedemir1, self.crowd, self.witch, self.duck] ) def test_vector_add_multi(self): searched = Line.objects.annotate( search=( SearchVector("scene__setting") + SearchVector("character__name") + SearchVector("dialogue") ), ).filter(search="bedemir") self.assertCountEqual( searched, [self.bedemir0, self.bedemir1, self.crowd, self.witch, self.duck] ) def test_vector_combined_mismatch(self): msg = ( "SearchVector can only be combined with other SearchVector " "instances, got NoneType." ) with self.assertRaisesMessage(TypeError, msg): Line.objects.filter(dialogue__search=None + SearchVector("character__name")) def test_combine_different_vector_configs(self): self.check_default_text_search_config() searched = Line.objects.annotate( search=( SearchVector("dialogue", config="english") + SearchVector("dialogue", config="french") ), ).filter( search=SearchQuery("cadeaux", config="french") | SearchQuery("nostrils") ) self.assertCountEqual(searched, [self.french, self.verse2]) def test_query_and(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter(search=SearchQuery("bedemir") & SearchQuery("scales")) self.assertSequenceEqual(searched, [self.bedemir0]) def test_query_multiple_and(self): searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter( search=SearchQuery("bedemir") & SearchQuery("scales") & SearchQuery("nostrils") ) self.assertSequenceEqual(searched, []) searched = Line.objects.annotate( search=SearchVector("scene__setting", "dialogue"), ).filter( search=SearchQuery("shall") & SearchQuery("use") & SearchQuery("larger") ) self.assertSequenceEqual(searched, [self.bedemir0]) def test_query_or(self): searched = Line.objects.filter( dialogue__search=SearchQuery("kneecaps") | SearchQuery("nostrils") ) self.assertCountEqual(searched, [self.verse1, self.verse2]) def test_query_multiple_or(self): searched = Line.objects.filter( dialogue__search=SearchQuery("kneecaps") | SearchQuery("nostrils") | SearchQuery("Sir Robin") ) self.assertCountEqual(searched, [self.verse1, self.verse2, self.verse0]) def test_query_invert(self): searched = Line.objects.filter( character=self.minstrel, dialogue__search=~SearchQuery("kneecaps") ) self.assertCountEqual(searched, [self.verse0, self.verse2]) def test_combine_different_configs(self): searched = Line.objects.filter( dialogue__search=( SearchQuery("cadeau", config="french") | SearchQuery("nostrils", config="english") ) ) self.assertCountEqual(searched, [self.french, self.verse2]) def test_combined_configs(self): searched = Line.objects.filter( dialogue__search=( SearchQuery("nostrils", config="simple") & SearchQuery("bowels", config="simple") ), ) self.assertSequenceEqual(searched, [self.verse2]) def test_combine_raw_phrase(self): self.check_default_text_search_config() searched = Line.objects.filter( dialogue__search=( SearchQuery("burn:*", search_type="raw", config="simple") | SearchQuery("rode forth from Camelot", search_type="phrase") ) ) self.assertCountEqual(searched, [self.verse0, self.verse1, self.verse2]) def test_query_combined_mismatch(self): msg = ( "SearchQuery can only be combined with other SearchQuery " "instances, got NoneType." ) with self.assertRaisesMessage(TypeError, msg): Line.objects.filter(dialogue__search=None | SearchQuery("kneecaps")) with self.assertRaisesMessage(TypeError, msg): Line.objects.filter(dialogue__search=None & SearchQuery("kneecaps")) class TestRankingAndWeights(GrailTestData, PostgreSQLTestCase): def test_ranking(self): searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank( SearchVector("dialogue"), SearchQuery("brave sir robin") ), ) .order_by("rank") ) self.assertSequenceEqual(searched, [self.verse2, self.verse1, self.verse0]) def test_rank_passing_untyped_args(self): searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank("dialogue", "brave sir robin"), ) .order_by("rank") ) self.assertSequenceEqual(searched, [self.verse2, self.verse1, self.verse0]) def test_weights_in_vector(self): vector = SearchVector("dialogue", weight="A") + SearchVector( "character__name", weight="D" ) searched = ( Line.objects.filter(scene=self.witch_scene) .annotate( rank=SearchRank(vector, SearchQuery("witch")), ) .order_by("-rank")[:2] ) self.assertSequenceEqual(searched, [self.crowd, self.witch]) vector = SearchVector("dialogue", weight="D") + SearchVector( "character__name", weight="A" ) searched = ( Line.objects.filter(scene=self.witch_scene) .annotate( rank=SearchRank(vector, SearchQuery("witch")), ) .order_by("-rank")[:2] ) self.assertSequenceEqual(searched, [self.witch, self.crowd]) def test_ranked_custom_weights(self): vector = SearchVector("dialogue", weight="D") + SearchVector( "character__name", weight="A" ) weights = [1.0, 0.0, 0.0, 0.5] searched = ( Line.objects.filter(scene=self.witch_scene) .annotate( rank=SearchRank(vector, SearchQuery("witch"), weights=weights), ) .order_by("-rank")[:2] ) self.assertSequenceEqual(searched, [self.crowd, self.witch]) def test_ranking_chaining(self): searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank( SearchVector("dialogue"), SearchQuery("brave sir robin") ), ) .filter(rank__gt=0.3) ) self.assertSequenceEqual(searched, [self.verse0]) def test_cover_density_ranking(self): not_dense_verse = Line.objects.create( scene=self.robin, character=self.minstrel, dialogue=( "Bravely taking to his feet, he beat a very brave retreat. " "A brave retreat brave Sir Robin." ), ) searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank( SearchVector("dialogue"), SearchQuery("brave robin"), cover_density=True, ), ) .order_by("rank", "-pk") ) self.assertSequenceEqual( searched, [self.verse2, not_dense_verse, self.verse1, self.verse0], ) def test_ranking_with_normalization(self): short_verse = Line.objects.create( scene=self.robin, character=self.minstrel, dialogue="A brave retreat brave Sir Robin.", ) searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank( SearchVector("dialogue"), SearchQuery("brave sir robin"), # Divide the rank by the document length. normalization=2, ), ) .order_by("rank") ) self.assertSequenceEqual( searched, [self.verse2, self.verse1, self.verse0, short_verse], ) def test_ranking_with_masked_normalization(self): short_verse = Line.objects.create( scene=self.robin, character=self.minstrel, dialogue="A brave retreat brave Sir Robin.", ) searched = ( Line.objects.filter(character=self.minstrel) .annotate( rank=SearchRank( SearchVector("dialogue"), SearchQuery("brave sir robin"), # Divide the rank by the document length and by the number of # unique words in document. normalization=Value(2).bitor(Value(8)), ), ) .order_by("rank") ) self.assertSequenceEqual( searched, [self.verse2, self.verse1, self.verse0, short_verse], ) class SearchQueryTests(PostgreSQLSimpleTestCase): def test_str(self): tests = ( (~SearchQuery("a"), "~SearchQuery(Value('a'))"), ( (SearchQuery("a") | SearchQuery("b")) & (SearchQuery("c") | SearchQuery("d")), "((SearchQuery(Value('a')) || SearchQuery(Value('b'))) && " "(SearchQuery(Value('c')) || SearchQuery(Value('d'))))", ), ( SearchQuery("a") & (SearchQuery("b") | SearchQuery("c")), "(SearchQuery(Value('a')) && (SearchQuery(Value('b')) || " "SearchQuery(Value('c'))))", ), ( (SearchQuery("a") | SearchQuery("b")) & SearchQuery("c"), "((SearchQuery(Value('a')) || SearchQuery(Value('b'))) && " "SearchQuery(Value('c')))", ), ( SearchQuery("a") & (SearchQuery("b") & (SearchQuery("c") | SearchQuery("d"))), "(SearchQuery(Value('a')) && (SearchQuery(Value('b')) && " "(SearchQuery(Value('c')) || SearchQuery(Value('d')))))", ), ) for query, expected_str in tests: with self.subTest(query=query): self.assertEqual(str(query), expected_str) class SearchHeadlineTests(GrailTestData, PostgreSQLTestCase): def test_headline(self): self.check_default_text_search_config() searched = Line.objects.annotate( headline=SearchHeadline( F("dialogue"), SearchQuery("brave sir robin"), config=SearchConfig("english"), ), ).get(pk=self.verse0.pk) self.assertEqual( searched.headline, "<b>Robin</b>. He was not at all afraid to be killed in nasty " "ways. <b>Brave</b>, <b>brave</b>, <b>brave</b>, <b>brave</b> " "<b>Sir</b> <b>Robin</b>", ) def test_headline_untyped_args(self): self.check_default_text_search_config() searched = Line.objects.annotate( headline=SearchHeadline("dialogue", "killed", config="english"), ).get(pk=self.verse0.pk) self.assertEqual( searched.headline, "Robin. He was not at all afraid to be <b>killed</b> in nasty " "ways. Brave, brave, brave, brave Sir Robin", ) def test_headline_with_config(self): searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", SearchQuery("cadeaux", config="french"), config="french", ), ).get(pk=self.french.pk) self.assertEqual( searched.headline, "Oh. Un beau <b>cadeau</b>. Oui oui.", ) def test_headline_with_config_from_field(self): searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", SearchQuery("cadeaux", config=F("dialogue_config")), config=F("dialogue_config"), ), ).get(pk=self.french.pk) self.assertEqual( searched.headline, "Oh. Un beau <b>cadeau</b>. Oui oui.", ) def test_headline_separator_options(self): searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", "brave sir robin", start_sel="<span>", stop_sel="</span>", ), ).get(pk=self.verse0.pk) self.assertEqual( searched.headline, "<span>Robin</span>. He was not at all afraid to be killed in " "nasty ways. <span>Brave</span>, <span>brave</span>, <span>brave" "</span>, <span>brave</span> <span>Sir</span> <span>Robin</span>", ) def test_headline_highlight_all_option(self): self.check_default_text_search_config() searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", SearchQuery("brave sir robin", config="english"), highlight_all=True, ), ).get(pk=self.verse0.pk) self.assertIn( "<b>Bravely</b> bold <b>Sir</b> <b>Robin</b>, rode forth from " "Camelot. He was not afraid to die, o ", searched.headline, ) def test_headline_short_word_option(self): self.check_default_text_search_config() searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", SearchQuery("Camelot", config="english"), short_word=5, min_words=8, ), ).get(pk=self.verse0.pk) self.assertEqual( searched.headline, ( "<b>Camelot</b>. He was not afraid to die, o Brave Sir Robin. He " "was not at all afraid" ), ) def test_headline_fragments_words_options(self): self.check_default_text_search_config() searched = Line.objects.annotate( headline=SearchHeadline( "dialogue", SearchQuery("brave sir robin", config="english"), fragment_delimiter="...<br>", max_fragments=4, max_words=3, min_words=1, ), ).get(pk=self.verse0.pk) self.assertEqual( searched.headline, "<b>Sir</b> <b>Robin</b>, rode...<br>" "<b>Brave</b> <b>Sir</b> <b>Robin</b>...<br>" "<b>Brave</b>, <b>brave</b>, <b>brave</b>...<br>" "<b>brave</b> <b>Sir</b> <b>Robin</b>", )
a023fb88415ba767deb3a358ab2cd03a94b049c927d9af57f8f526b3455f48d9
from unittest import mock from django.contrib.postgres.indexes import ( BloomIndex, BrinIndex, BTreeIndex, GinIndex, GistIndex, HashIndex, OpClass, PostgresIndex, SpGistIndex, ) from django.db import NotSupportedError, connection from django.db.models import CharField, F, Index, Q from django.db.models.functions import Cast, Collate, Length, Lower from django.test import skipUnlessDBFeature from django.test.utils import register_lookup from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase from .fields import SearchVector, SearchVectorField from .models import CharFieldModel, IntegerArrayModel, Scene, TextFieldModel class IndexTestMixin: def test_name_auto_generation(self): index = self.index_class(fields=["field"]) index.set_name_with_model(CharFieldModel) self.assertRegex( index.name, r"postgres_te_field_[0-9a-f]{6}_%s" % self.index_class.suffix ) def test_deconstruction_no_customization(self): index = self.index_class( fields=["title"], name="test_title_%s" % self.index_class.suffix ) path, args, kwargs = index.deconstruct() self.assertEqual( path, "django.contrib.postgres.indexes.%s" % self.index_class.__name__ ) self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_%s" % self.index_class.suffix}, ) def test_deconstruction_with_expressions_no_customization(self): name = f"test_title_{self.index_class.suffix}" index = self.index_class(Lower("title"), name=name) path, args, kwargs = index.deconstruct() self.assertEqual( path, f"django.contrib.postgres.indexes.{self.index_class.__name__}", ) self.assertEqual(args, (Lower("title"),)) self.assertEqual(kwargs, {"name": name}) class BloomIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BloomIndex def test_suffix(self): self.assertEqual(BloomIndex.suffix, "bloom") def test_deconstruction(self): index = BloomIndex(fields=["title"], name="test_bloom", length=80, columns=[4]) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BloomIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_bloom", "length": 80, "columns": [4], }, ) def test_invalid_fields(self): msg = "Bloom indexes support a maximum of 32 fields." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"] * 33, name="test_bloom") def test_invalid_columns(self): msg = "BloomIndex.columns must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns="x") msg = "BloomIndex.columns cannot have more values than fields." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns=[4, 3]) def test_invalid_columns_value(self): msg = "BloomIndex.columns must contain integers from 1 to 4095." for length in (0, 4096): with self.subTest(length), self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns=[length]) def test_invalid_length(self): msg = "BloomIndex.length must be None or an integer from 1 to 4096." for length in (0, 4097): with self.subTest(length), self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", length=length) class BrinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BrinIndex def test_suffix(self): self.assertEqual(BrinIndex.suffix, "brin") def test_deconstruction(self): index = BrinIndex( fields=["title"], name="test_title_brin", autosummarize=True, pages_per_range=16, ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BrinIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_brin", "autosummarize": True, "pages_per_range": 16, }, ) def test_invalid_pages_per_range(self): with self.assertRaisesMessage( ValueError, "pages_per_range must be None or a positive integer" ): BrinIndex(fields=["title"], name="test_title_brin", pages_per_range=0) class BTreeIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BTreeIndex def test_suffix(self): self.assertEqual(BTreeIndex.suffix, "btree") def test_deconstruction(self): index = BTreeIndex(fields=["title"], name="test_title_btree", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BTreeIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_btree", "fillfactor": 80} ) class GinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = GinIndex def test_suffix(self): self.assertEqual(GinIndex.suffix, "gin") def test_deconstruction(self): index = GinIndex( fields=["title"], name="test_title_gin", fastupdate=True, gin_pending_list_limit=128, ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.GinIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_gin", "fastupdate": True, "gin_pending_list_limit": 128, }, ) class GistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = GistIndex def test_suffix(self): self.assertEqual(GistIndex.suffix, "gist") def test_deconstruction(self): index = GistIndex( fields=["title"], name="test_title_gist", buffering=False, fillfactor=80 ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.GistIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_gist", "buffering": False, "fillfactor": 80, }, ) class HashIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = HashIndex def test_suffix(self): self.assertEqual(HashIndex.suffix, "hash") def test_deconstruction(self): index = HashIndex(fields=["title"], name="test_title_hash", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.HashIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_hash", "fillfactor": 80} ) class SpGistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = SpGistIndex def test_suffix(self): self.assertEqual(SpGistIndex.suffix, "spgist") def test_deconstruction(self): index = SpGistIndex(fields=["title"], name="test_title_spgist", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.SpGistIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_spgist", "fillfactor": 80} ) class SchemaTests(PostgreSQLTestCase): get_opclass_query = """ SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s """ def get_constraints(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_gin_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn( "field", self.get_constraints(IntegerArrayModel._meta.db_table) ) # Add the index index_name = "integer_array_model_field_gin" index = GinIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) # Check gin index was added self.assertEqual(constraints[index_name]["type"], GinIndex.suffix) # Drop the index with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_gin_fastupdate(self): index_name = "integer_array_gin_fastupdate" index = GinIndex(fields=["field"], name=index_name, fastupdate=False) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") self.assertEqual(constraints[index_name]["options"], ["fastupdate=off"]) with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_partial_gin_index(self): with register_lookup(CharField, Length): index_name = "char_field_gin_partial_idx" index = GinIndex( fields=["field"], name=index_name, condition=Q(field__length=40) ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_partial_gin_index_with_tablespace(self): with register_lookup(CharField, Length): index_name = "char_field_gin_partial_idx" index = GinIndex( fields=["field"], name=index_name, condition=Q(field__length=40), db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) self.assertIn( 'TABLESPACE "pg_default" ', str(index.create_sql(CharFieldModel, editor)), ) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gin_parameters(self): index_name = "integer_array_gin_params" index = GinIndex( fields=["field"], name=index_name, fastupdate=True, gin_pending_list_limit=64, db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) self.assertIn( ") WITH (gin_pending_list_limit = 64, fastupdate = on) TABLESPACE", str(index.create_sql(IntegerArrayModel, editor)), ) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") self.assertEqual( constraints[index_name]["options"], ["gin_pending_list_limit=64", "fastupdate=on"], ) with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_trigram_op_class_gin_index(self): index_name = "trigram_op_class_gin" index = GinIndex(OpClass(F("scene"), name="gin_trgm_ops"), name=index_name) with connection.schema_editor() as editor: editor.add_index(Scene, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("gin_trgm_ops", index_name)]) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GinIndex.suffix) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_cast_search_vector_gin_index(self): index_name = "cast_search_vector_gin" index = GinIndex(Cast("field", SearchVectorField()), name=index_name) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) sql = index.create_sql(TextFieldModel, editor) table = TextFieldModel._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GinIndex.suffix) self.assertIs(sql.references_column(table, "field"), True) self.assertIn("::tsvector", str(sql)) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_bloom_index(self): index_name = "char_field_model_field_bloom" index = BloomIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_bloom_parameters(self): index_name = "char_field_model_field_bloom_params" index = BloomIndex(fields=["field"], name=index_name, length=512, columns=[3]) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["length=512", "col1=3"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_brin_index(self): index_name = "char_field_model_field_brin" index = BrinIndex(fields=["field"], name=index_name, pages_per_range=4) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["pages_per_range=4"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_brin_parameters(self): index_name = "char_field_brin_params" index = BrinIndex(fields=["field"], name=index_name, autosummarize=True) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["autosummarize=on"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_btree_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_btree" index = BTreeIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_btree_parameters(self): index_name = "integer_array_btree_fillfactor" index = BTreeIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_gist" index = GistIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_parameters(self): index_name = "integer_array_gist_buffering" index = GistIndex( fields=["field"], name=index_name, buffering=True, fillfactor=80 ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) self.assertEqual( constraints[index_name]["options"], ["buffering=on", "fillfactor=80"] ) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_include(self): index_name = "scene_gist_include_setting" index = GistIndex(name=index_name, fields=["scene"], include=["setting"]) with connection.schema_editor() as editor: editor.add_index(Scene, index) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"]) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_tsvector_op_class_gist_index(self): index_name = "tsvector_op_class_gist" index = GistIndex( OpClass( SearchVector("scene", "setting", config="english"), name="tsvector_ops", ), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(Scene, index) sql = index.create_sql(Scene, editor) table = Scene._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GistIndex.suffix) self.assertIs(sql.references_column(table, "scene"), True) self.assertIs(sql.references_column(table, "setting"), True) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_search_vector(self): """SearchVector generates IMMUTABLE SQL in order to be indexable.""" index_name = "test_search_vector" index = Index(SearchVector("id", "scene", config="english"), name=index_name) # Indexed function must be IMMUTABLE. with connection.schema_editor() as editor: editor.add_index(Scene, index) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertIs(constraints[index_name]["index"], True) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_hash_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_hash" index = HashIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], HashIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_hash_parameters(self): index_name = "integer_array_hash_fillfactor" index = HashIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], HashIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_spgist_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(TextFieldModel._meta.db_table)) # Add the index. index_name = "text_field_model_field_spgist" index = SpGistIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) constraints = self.get_constraints(TextFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn( index_name, self.get_constraints(TextFieldModel._meta.db_table) ) def test_spgist_parameters(self): index_name = "text_field_model_spgist_fillfactor" index = SpGistIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn( index_name, self.get_constraints(TextFieldModel._meta.db_table) ) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_spgist_include(self): index_name = "scene_spgist_include_setting" index = SpGistIndex(name=index_name, fields=["scene"], include=["setting"]) with connection.schema_editor() as editor: editor.add_index(Scene, index) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"]) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_spgist_include_not_supported(self): index_name = "spgist_include_exception" index = SpGistIndex(fields=["scene"], name=index_name, include=["setting"]) msg = "Covering SP-GiST indexes require PostgreSQL 14+." with self.assertRaisesMessage(NotSupportedError, msg): with mock.patch( "django.db.backends.postgresql.features.DatabaseFeatures." "supports_covering_spgist_indexes", False, ): with connection.schema_editor() as editor: editor.add_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_custom_suffix(self): class CustomSuffixIndex(PostgresIndex): suffix = "sfx" def create_sql(self, model, schema_editor, using="gin", **kwargs): return super().create_sql(model, schema_editor, using=using, **kwargs) index = CustomSuffixIndex(fields=["field"], name="custom_suffix_idx") self.assertEqual(index.suffix, "sfx") with connection.schema_editor() as editor: self.assertIn( " USING gin ", str(index.create_sql(CharFieldModel, editor)), ) def test_op_class(self): index_name = "test_op_class" index = Index( OpClass(Lower("field"), name="text_pattern_ops"), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) def test_op_class_descending_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") index_name = "test_op_class_descending_collation" index = Index( Collate( OpClass(Lower("field"), name="text_pattern_ops").desc(nulls_last=True), collation=collation, ), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) self.assertIn( "COLLATE %s" % editor.quote_name(collation), str(index.create_sql(TextFieldModel, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) table = TextFieldModel._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"]) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_op_class_descending_partial(self): index_name = "test_op_class_descending_partial" index = Index( OpClass(Lower("field"), name="text_pattern_ops").desc(), name=index_name, condition=Q(field__contains="China"), ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"]) def test_op_class_descending_partial_tablespace(self): index_name = "test_op_class_descending_partial_tablespace" index = Index( OpClass(Lower("field").desc(), name="text_pattern_ops"), name=index_name, condition=Q(field__contains="China"), db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) self.assertIn( 'TABLESPACE "pg_default" ', str(index.create_sql(TextFieldModel, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"])
38be5d1de636eb01288564235a664f1ea7c883e85773a08b415cdc8b891cf7d4
import copy from io import BytesIO from itertools import chain from urllib.parse import urlencode from django.core.exceptions import DisallowedHost from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpHeaders, HttpRequest, RawPostDataException, UnreadablePostError, ) from django.http.multipartparser import MultiPartParserError from django.http.request import split_domain_port from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client import FakePayload class RequestsTests(SimpleTestCase): def test_httprequest(self): request = HttpRequest() self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual(list(request.META), []) # .GET and .POST should be QueryDicts self.assertEqual(request.GET.urlencode(), "") self.assertEqual(request.POST.urlencode(), "") # and FILES should be MultiValueDict self.assertEqual(request.FILES.getlist("foo"), []) self.assertIsNone(request.content_type) self.assertIsNone(request.content_params) def test_httprequest_full_path(self): request = HttpRequest() request.path = "/;some/?awful/=path/foo:bar/" request.path_info = "/prefix" + request.path request.META["QUERY_STRING"] = ";some=query&+query=string" expected = "/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string" self.assertEqual(request.get_full_path(), expected) self.assertEqual(request.get_full_path_info(), "/prefix" + expected) def test_httprequest_full_path_with_query_string_and_fragment(self): request = HttpRequest() request.path = "/foo#bar" request.path_info = "/prefix" + request.path request.META["QUERY_STRING"] = "baz#quux" self.assertEqual(request.get_full_path(), "/foo%23bar?baz#quux") self.assertEqual(request.get_full_path_info(), "/prefix/foo%23bar?baz#quux") def test_httprequest_repr(self): request = HttpRequest() request.path = "/somepath/" request.method = "GET" request.GET = {"get-key": "get-value"} request.POST = {"post-key": "post-value"} request.COOKIES = {"post-key": "post-value"} request.META = {"post-key": "post-value"} self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>") def test_httprequest_repr_invalid_method_and_path(self): request = HttpRequest() self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.method = "GET" self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.path = "" self.assertEqual(repr(request), "<HttpRequest>") def test_wsgirequest(self): request = WSGIRequest( { "PATH_INFO": "bogus", "REQUEST_METHOD": "bogus", "CONTENT_TYPE": "text/html; charset=utf8", "wsgi.input": BytesIO(b""), } ) self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual( set(request.META), { "PATH_INFO", "REQUEST_METHOD", "SCRIPT_NAME", "CONTENT_TYPE", "wsgi.input", }, ) self.assertEqual(request.META["PATH_INFO"], "bogus") self.assertEqual(request.META["REQUEST_METHOD"], "bogus") self.assertEqual(request.META["SCRIPT_NAME"], "") self.assertEqual(request.content_type, "text/html") self.assertEqual(request.content_params, {"charset": "utf8"}) def test_wsgirequest_with_script_name(self): """ The request's path is correctly assembled, regardless of whether or not the SCRIPT_NAME has a trailing slash (#20169). """ # With trailing slash request = WSGIRequest( { "PATH_INFO": "/somepath/", "SCRIPT_NAME": "/PREFIX/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/PREFIX/somepath/") # Without trailing slash request = WSGIRequest( { "PATH_INFO": "/somepath/", "SCRIPT_NAME": "/PREFIX", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/PREFIX/somepath/") def test_wsgirequest_script_url_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest should take that into account when populating request.path and request.META['SCRIPT_NAME'] (#17133). """ request = WSGIRequest( { "SCRIPT_URL": "/mst/milestones//accounts/login//help", "PATH_INFO": "/milestones/accounts/login/help", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/mst/milestones/accounts/login/help") self.assertEqual(request.META["SCRIPT_NAME"], "/mst") def test_wsgirequest_with_force_script_name(self): """ The FORCE_SCRIPT_NAME setting takes precedence over the request's SCRIPT_NAME environment parameter (#20169). """ with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/"): request = WSGIRequest( { "PATH_INFO": "/somepath/", "SCRIPT_NAME": "/PREFIX/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/FORCED_PREFIX/somepath/") def test_wsgirequest_path_with_force_script_name_trailing_slash(self): """ The request's path is correctly assembled, regardless of whether or not the FORCE_SCRIPT_NAME setting has a trailing slash (#20169). """ # With trailing slash with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/"): request = WSGIRequest( { "PATH_INFO": "/somepath/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/FORCED_PREFIX/somepath/") # Without trailing slash with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX"): request = WSGIRequest( { "PATH_INFO": "/somepath/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/FORCED_PREFIX/somepath/") def test_wsgirequest_repr(self): request = WSGIRequest({"REQUEST_METHOD": "get", "wsgi.input": BytesIO(b"")}) self.assertEqual(repr(request), "<WSGIRequest: GET '/'>") request = WSGIRequest( { "PATH_INFO": "/somepath/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) request.GET = {"get-key": "get-value"} request.POST = {"post-key": "post-value"} request.COOKIES = {"post-key": "post-value"} request.META = {"post-key": "post-value"} self.assertEqual(repr(request), "<WSGIRequest: GET '/somepath/'>") def test_wsgirequest_path_info(self): def wsgi_str(path_info, encoding="utf-8"): path_info = path_info.encode( encoding ) # Actual URL sent by the browser (bytestring) path_info = path_info.decode( "iso-8859-1" ) # Value in the WSGI environ dict (native string) return path_info # Regression for #19468 request = WSGIRequest( { "PATH_INFO": wsgi_str("/سلام/"), "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) self.assertEqual(request.path, "/سلام/") # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971) request = WSGIRequest( { "PATH_INFO": wsgi_str("/café/", encoding="iso-8859-1"), "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), } ) # Since it's impossible to decide the (wrong) encoding of the URL, it's # left percent-encoded in the path. self.assertEqual(request.path, "/caf%E9/") def test_wsgirequest_copy(self): request = WSGIRequest({"REQUEST_METHOD": "get", "wsgi.input": BytesIO(b"")}) request_copy = copy.copy(request) self.assertIs(request_copy.environ, request.environ) def test_limited_stream(self): # Read all of a limited stream stream = LimitedStream(BytesIO(b"test"), 2) self.assertEqual(stream.read(), b"te") # Reading again returns nothing. self.assertEqual(stream.read(), b"") # Read a number of characters greater than the stream has to offer stream = LimitedStream(BytesIO(b"test"), 2) self.assertEqual(stream.read(5), b"te") # Reading again returns nothing. self.assertEqual(stream.readline(5), b"") # Read sequentially from a stream stream = LimitedStream(BytesIO(b"12345678"), 8) self.assertEqual(stream.read(5), b"12345") self.assertEqual(stream.read(5), b"678") # Reading again returns nothing. self.assertEqual(stream.readline(5), b"") # Read lines from a stream stream = LimitedStream(BytesIO(b"1234\n5678\nabcd\nefgh\nijkl"), 24) # Read a full line, unconditionally self.assertEqual(stream.readline(), b"1234\n") # Read a number of characters less than a line self.assertEqual(stream.readline(2), b"56") # Read the rest of the partial line self.assertEqual(stream.readline(), b"78\n") # Read a full line, with a character limit greater than the line length self.assertEqual(stream.readline(6), b"abcd\n") # Read the next line, deliberately terminated at the line end self.assertEqual(stream.readline(4), b"efgh") # Read the next line... just the line end self.assertEqual(stream.readline(), b"\n") # Read everything else. self.assertEqual(stream.readline(), b"ijkl") # Regression for #15018 # If a stream contains a newline, but the provided length # is less than the number of provided characters, the newline # doesn't reset the available character count stream = LimitedStream(BytesIO(b"1234\nabcdef"), 9) self.assertEqual(stream.readline(10), b"1234\n") self.assertEqual(stream.readline(3), b"abc") # Now expire the available characters self.assertEqual(stream.readline(3), b"d") # Reading again returns nothing. self.assertEqual(stream.readline(2), b"") # Same test, but with read, not readline. stream = LimitedStream(BytesIO(b"1234\nabcdef"), 9) self.assertEqual(stream.read(6), b"1234\na") self.assertEqual(stream.read(2), b"bc") self.assertEqual(stream.read(2), b"d") self.assertEqual(stream.read(2), b"") self.assertEqual(stream.read(), b"") def test_stream_read(self): payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, }, ) self.assertEqual(request.read(), b"name=value") def test_stream_readline(self): payload = FakePayload("name=value\nother=string") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, }, ) self.assertEqual(request.readline(), b"name=value\n") self.assertEqual(request.readline(), b"other=string") def test_read_after_value(self): """ Reading from request is allowed after accessing request contents as POST or body. """ payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(request.POST, {"name": ["value"]}) self.assertEqual(request.body, b"name=value") self.assertEqual(request.read(), b"name=value") def test_value_after_read(self): """ Construction of POST or body is not allowed after reading from request. """ payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(request.read(2), b"na") with self.assertRaises(RawPostDataException): request.body self.assertEqual(request.POST, {}) def test_non_ascii_POST(self): payload = FakePayload(urlencode({"key": "España"})) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": "application/x-www-form-urlencoded", "wsgi.input": payload, } ) self.assertEqual(request.POST, {"key": ["España"]}) def test_alternate_charset_POST(self): """ Test a POST with non-utf-8 payload encoding. """ payload = FakePayload(urlencode({"key": "España".encode("latin-1")})) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": "application/x-www-form-urlencoded; charset=iso-8859-1", "wsgi.input": payload, } ) self.assertEqual(request.POST, {"key": ["España"]}) def test_body_after_POST_multipart_form_data(self): """ Reading body after parsing multipart/form-data is not allowed """ # Because multipart is used for large amounts of data i.e. file uploads, # we don't want the data held in memory twice, and we don't want to # silence the error by setting body = '' either. payload = FakePayload( "\r\n".join( [ "--boundary", 'Content-Disposition: form-data; name="name"', "", "value", "--boundary--", ] ) ) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=boundary", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(request.POST, {"name": ["value"]}) with self.assertRaises(RawPostDataException): request.body def test_body_after_POST_multipart_related(self): """ Reading body after parsing multipart that isn't form-data is allowed """ # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join( [ b"--boundary", b'Content-ID: id; name="name"', b"", b"value", b"--boundary--", ] ) payload = FakePayload(payload_data) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/related; boundary=boundary", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(request.POST, {}) self.assertEqual(request.body, payload_data) def test_POST_multipart_with_content_length_zero(self): """ Multipart POST requests with Content-Length >= 0 are valid and need to be handled. """ # According to RFC 9110 Section 8.6 every POST with Content-Length >= 0 # is a valid request, so ensure that we handle Content-Length == 0. payload = FakePayload( "\r\n".join( [ "--boundary", 'Content-Disposition: form-data; name="name"', "", "value", "--boundary--", ] ) ) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=boundary", "CONTENT_LENGTH": 0, "wsgi.input": payload, } ) self.assertEqual(request.POST, {}) def test_POST_binary_only(self): payload = b"\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@" environ = { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/octet-stream", "CONTENT_LENGTH": len(payload), "wsgi.input": BytesIO(payload), } request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) # Same test without specifying content-type environ.update({"CONTENT_TYPE": "", "wsgi.input": BytesIO(payload)}) request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) def test_read_by_lines(self): payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(list(request), [b"name=value"]) def test_POST_after_body_read(self): """ POST should be populated even if body is read first """ payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) request.body # evaluate self.assertEqual(request.POST, {"name": ["value"]}) def test_POST_after_body_read_and_stream_read(self): """ POST should be populated even if body is read first, and then the stream is read second. """ payload = FakePayload("name=value") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) request.body # evaluate self.assertEqual(request.read(1), b"n") self.assertEqual(request.POST, {"name": ["value"]}) def test_POST_after_body_read_and_stream_read_multipart(self): """ POST should be populated even if body is read first, and then the stream is read second. Using multipart/form-data instead of urlencoded. """ payload = FakePayload( "\r\n".join( [ "--boundary", 'Content-Disposition: form-data; name="name"', "", "value", "--boundary--" "", ] ) ) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=boundary", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) request.body # evaluate # Consume enough data to mess up the parsing: self.assertEqual(request.read(13), b"--boundary\r\nC") self.assertEqual(request.POST, {"name": ["value"]}) def test_POST_immutable_for_multipart(self): """ MultiPartParser.parse() leaves request.POST immutable. """ payload = FakePayload( "\r\n".join( [ "--boundary", 'Content-Disposition: form-data; name="name"', "", "value", "--boundary--", ] ) ) request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=boundary", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertFalse(request.POST._mutable) def test_multipart_without_boundary(self): request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data;", "CONTENT_LENGTH": 0, "wsgi.input": FakePayload(), } ) with self.assertRaisesMessage( MultiPartParserError, "Invalid boundary in multipart: None" ): request.POST def test_multipart_non_ascii_content_type(self): request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary = \xe0", "CONTENT_LENGTH": 0, "wsgi.input": FakePayload(), } ) msg = ( "Invalid non-ASCII Content-Type in multipart: multipart/form-data; " "boundary = à" ) with self.assertRaisesMessage(MultiPartParserError, msg): request.POST def test_POST_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the POST, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, size=-1, /): raise OSError("kaboom!") payload = b"name=value" request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": ExplodingBytesIO(payload), } ) with self.assertRaises(UnreadablePostError): request.body def test_set_encoding_clears_POST(self): payload = FakePayload("name=Hello Günter") request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, } ) self.assertEqual(request.POST, {"name": ["Hello Günter"]}) request.encoding = "iso-8859-16" self.assertEqual(request.POST, {"name": ["Hello GĂŒnter"]}) def test_set_encoding_clears_GET(self): payload = FakePayload("") request = WSGIRequest( { "REQUEST_METHOD": "GET", "wsgi.input": payload, "QUERY_STRING": "name=Hello%20G%C3%BCnter", } ) self.assertEqual(request.GET, {"name": ["Hello Günter"]}) request.encoding = "iso-8859-16" self.assertEqual(request.GET, {"name": ["Hello G\u0102\u0152nter"]}) def test_FILES_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the FILES, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, size=-1, /): raise OSError("kaboom!") payload = b"x" request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "multipart/form-data; boundary=foo_", "CONTENT_LENGTH": len(payload), "wsgi.input": ExplodingBytesIO(payload), } ) with self.assertRaises(UnreadablePostError): request.FILES def test_copy(self): request = HttpRequest() request_copy = copy.copy(request) self.assertIs(request_copy.resolver_match, request.resolver_match) def test_deepcopy(self): request = RequestFactory().get("/") request.session = {} request_copy = copy.deepcopy(request) request.session["key"] = "value" self.assertEqual(request_copy.session, {}) class HostValidationTests(SimpleTestCase): poisoned_hosts = [ "[email protected]", "example.com:[email protected]", "example.com:[email protected]:80", "example.com:80/badpath", "example.com: recovermypassword.com", ] @override_settings( USE_X_FORWARDED_HOST=False, ALLOWED_HOSTS=[ "forward.com", "example.com", "internal.com", "12.34.56.78", "[2001:19f0:feee::dead:beef:cafe]", "xn--4ca9at.com", ".multitenant.com", "INSENSITIVE.com", "[::ffff:169.254.169.254]", ], ) def test_http_get_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { "HTTP_X_FORWARDED_HOST": "forward.com", "HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } # X_FORWARDED_HOST is ignored. self.assertEqual(request.get_host(), "example.com") # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { "HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } self.assertEqual(request.get_host(), "example.com") # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } self.assertEqual(request.get_host(), "internal.com") # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { "SERVER_NAME": "internal.com", "SERVER_PORT": 8042, } self.assertEqual(request.get_host(), "internal.com:8042") legit_hosts = [ "example.com", "example.com:80", "12.34.56.78", "12.34.56.78:443", "[2001:19f0:feee::dead:beef:cafe]", "[2001:19f0:feee::dead:beef:cafe]:8080", "xn--4ca9at.com", # Punycode for öäü.com "anything.multitenant.com", "multitenant.com", "insensitive.com", "example.com.", "example.com.:80", "[::ffff:169.254.169.254]", ] for host in legit_hosts: request = HttpRequest() request.META = { "HTTP_HOST": host, } request.get_host() # Poisoned host headers are rejected as suspicious for host in chain(self.poisoned_hosts, ["other.com", "example.com.."]): with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { "HTTP_HOST": host, } request.get_host() @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=["*"]) def test_http_get_host_with_x_forwarded_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { "HTTP_X_FORWARDED_HOST": "forward.com", "HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } # X_FORWARDED_HOST is obeyed. self.assertEqual(request.get_host(), "forward.com") # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { "HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } self.assertEqual(request.get_host(), "example.com") # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } self.assertEqual(request.get_host(), "internal.com") # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { "SERVER_NAME": "internal.com", "SERVER_PORT": 8042, } self.assertEqual(request.get_host(), "internal.com:8042") # Poisoned host headers are rejected as suspicious legit_hosts = [ "example.com", "example.com:80", "12.34.56.78", "12.34.56.78:443", "[2001:19f0:feee::dead:beef:cafe]", "[2001:19f0:feee::dead:beef:cafe]:8080", "xn--4ca9at.com", # Punycode for öäü.com ] for host in legit_hosts: request = HttpRequest() request.META = { "HTTP_HOST": host, } request.get_host() for host in self.poisoned_hosts: with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { "HTTP_HOST": host, } request.get_host() @override_settings(USE_X_FORWARDED_PORT=False) def test_get_port(self): request = HttpRequest() request.META = { "SERVER_PORT": "8080", "HTTP_X_FORWARDED_PORT": "80", } # Shouldn't use the X-Forwarded-Port header self.assertEqual(request.get_port(), "8080") request = HttpRequest() request.META = { "SERVER_PORT": "8080", } self.assertEqual(request.get_port(), "8080") @override_settings(USE_X_FORWARDED_PORT=True) def test_get_port_with_x_forwarded_port(self): request = HttpRequest() request.META = { "SERVER_PORT": "8080", "HTTP_X_FORWARDED_PORT": "80", } # Should use the X-Forwarded-Port header self.assertEqual(request.get_port(), "80") request = HttpRequest() request.META = { "SERVER_PORT": "8080", } self.assertEqual(request.get_port(), "8080") @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ valid_hosts = ["localhost", "subdomain.localhost", "127.0.0.1", "[::1]"] for host in valid_hosts: request = HttpRequest() request.META = {"HTTP_HOST": host} self.assertEqual(request.get_host(), host) # Other hostnames raise a DisallowedHost. with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = {"HTTP_HOST": "example.com"} request.get_host() @override_settings(ALLOWED_HOSTS=[]) def test_get_host_suggestion_of_allowed_host(self): """ get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS. """ msg_invalid_host = "Invalid HTTP_HOST header: %r." msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS." msg_suggestion2 = ( msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035" ) for host in [ # Valid-looking hosts "example.com", "12.34.56.78", "[2001:19f0:feee::dead:beef:cafe]", "xn--4ca9at.com", # Punycode for öäü.com ]: request = HttpRequest() request.META = {"HTTP_HOST": host} with self.assertRaisesMessage( DisallowedHost, msg_suggestion % (host, host) ): request.get_host() for domain, port in [ # Valid-looking hosts with a port number ("example.com", 80), ("12.34.56.78", 443), ("[2001:19f0:feee::dead:beef:cafe]", 8080), ]: host = "%s:%s" % (domain, port) request = HttpRequest() request.META = {"HTTP_HOST": host} with self.assertRaisesMessage( DisallowedHost, msg_suggestion % (host, domain) ): request.get_host() for host in self.poisoned_hosts: request = HttpRequest() request.META = {"HTTP_HOST": host} with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host): request.get_host() request = HttpRequest() request.META = {"HTTP_HOST": "invalid_hostname.com"} with self.assertRaisesMessage( DisallowedHost, msg_suggestion2 % "invalid_hostname.com" ): request.get_host() def test_split_domain_port_removes_trailing_dot(self): domain, port = split_domain_port("example.com.:8080") self.assertEqual(domain, "example.com") self.assertEqual(port, "8080") class BuildAbsoluteURITests(SimpleTestCase): factory = RequestFactory() def test_absolute_url(self): request = HttpRequest() url = "https://www.example.com/asdf" self.assertEqual(request.build_absolute_uri(location=url), url) def test_host_retrieval(self): request = HttpRequest() request.get_host = lambda: "www.example.com" request.path = "" self.assertEqual( request.build_absolute_uri(location="/path/with:colons"), "http://www.example.com/path/with:colons", ) def test_request_path_begins_with_two_slashes(self): # //// creates a request with a path beginning with // request = self.factory.get("////absolute-uri") tests = ( # location isn't provided (None, "http://testserver//absolute-uri"), # An absolute URL ("http://example.com/?foo=bar", "http://example.com/?foo=bar"), # A schema-relative URL ("//example.com/?foo=bar", "http://example.com/?foo=bar"), # Relative URLs ("/foo/bar/", "http://testserver/foo/bar/"), ("/foo/./bar/", "http://testserver/foo/bar/"), ("/foo/../bar/", "http://testserver/bar/"), ("///foo/bar/", "http://testserver/foo/bar/"), ) for location, expected_url in tests: with self.subTest(location=location): self.assertEqual( request.build_absolute_uri(location=location), expected_url ) class RequestHeadersTests(SimpleTestCase): ENVIRON = { # Non-headers are ignored. "PATH_INFO": "/somepath/", "REQUEST_METHOD": "get", "wsgi.input": BytesIO(b""), "SERVER_NAME": "internal.com", "SERVER_PORT": 80, # These non-HTTP prefixed headers are included. "CONTENT_TYPE": "text/html", "CONTENT_LENGTH": "100", # All HTTP-prefixed headers are included. "HTTP_ACCEPT": "*", "HTTP_HOST": "example.com", "HTTP_USER_AGENT": "python-requests/1.2.0", } def test_base_request_headers(self): request = HttpRequest() request.META = self.ENVIRON self.assertEqual( dict(request.headers), { "Content-Type": "text/html", "Content-Length": "100", "Accept": "*", "Host": "example.com", "User-Agent": "python-requests/1.2.0", }, ) def test_wsgi_request_headers(self): request = WSGIRequest(self.ENVIRON) self.assertEqual( dict(request.headers), { "Content-Type": "text/html", "Content-Length": "100", "Accept": "*", "Host": "example.com", "User-Agent": "python-requests/1.2.0", }, ) def test_wsgi_request_headers_getitem(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers["User-Agent"], "python-requests/1.2.0") self.assertEqual(request.headers["user-agent"], "python-requests/1.2.0") self.assertEqual(request.headers["user_agent"], "python-requests/1.2.0") self.assertEqual(request.headers["Content-Type"], "text/html") self.assertEqual(request.headers["Content-Length"], "100") def test_wsgi_request_headers_get(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers.get("User-Agent"), "python-requests/1.2.0") self.assertEqual(request.headers.get("user-agent"), "python-requests/1.2.0") self.assertEqual(request.headers.get("Content-Type"), "text/html") self.assertEqual(request.headers.get("Content-Length"), "100") class HttpHeadersTests(SimpleTestCase): def test_basic(self): environ = { "CONTENT_TYPE": "text/html", "CONTENT_LENGTH": "100", "HTTP_HOST": "example.com", } headers = HttpHeaders(environ) self.assertEqual(sorted(headers), ["Content-Length", "Content-Type", "Host"]) self.assertEqual( headers, { "Content-Type": "text/html", "Content-Length": "100", "Host": "example.com", }, ) def test_parse_header_name(self): tests = ( ("PATH_INFO", None), ("HTTP_ACCEPT", "Accept"), ("HTTP_USER_AGENT", "User-Agent"), ("HTTP_X_FORWARDED_PROTO", "X-Forwarded-Proto"), ("CONTENT_TYPE", "Content-Type"), ("CONTENT_LENGTH", "Content-Length"), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
78e7ccde082c76eb79767d2b051e3c8f8612949291ace3103e8e97fdebae17c3
import asyncio import sys import threading from pathlib import Path from asgiref.testing import ApplicationCommunicator from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.asgi import get_asgi_application from django.core.handlers.asgi import ASGIHandler, ASGIRequest from django.core.signals import request_finished, request_started from django.db import close_old_connections from django.http import HttpResponse from django.test import ( AsyncRequestFactory, SimpleTestCase, ignore_warnings, modify_settings, override_settings, ) from django.urls import path from django.utils.http import http_date from .urls import sync_waiter, test_filename TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static" @override_settings(ROOT_URLCONF="asgi.urls") class ASGITest(SimpleTestCase): async_request_factory = AsyncRequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) async def test_get_asgi_application(self): """ get_asgi_application() returns a functioning ASGI callable. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"12"), (b"Content-Type", b"text/html; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Allow response.close() to finish. await communicator.wait() # Python's file API is not async compatible. A third-party library such # as https://github.com/Tinche/aiofiles allows passing the file to # FileResponse as an async iterator. With a sync iterator # StreamingHTTPResponse triggers a warning when iterating the file. # assertWarnsMessage is not async compatible, so ignore_warnings for the # test. @ignore_warnings(module="django.http.response") async def test_file_response(self): """ Makes sure that FileResponse works over ASGI. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/file/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. with open(test_filename, "rb") as test_file: test_file_contents = test_file.read() # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) headers = response_start["headers"] self.assertEqual(len(headers), 3) expected_headers = { b"Content-Length": str(len(test_file_contents)).encode("ascii"), b"Content-Type": b"text/x-python", b"Content-Disposition": b'inline; filename="urls.py"', } for key, value in headers: try: self.assertEqual(value, expected_headers[key]) except AssertionError: # Windows registry may not be configured with correct # mimetypes. if sys.platform == "win32" and key == b"Content-Type": self.assertEqual(value, b"text/plain") else: raise # Warning ignored here. response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() @modify_settings(INSTALLED_APPS={"append": "django.contrib.staticfiles"}) @override_settings( STATIC_URL="static/", STATIC_ROOT=TEST_STATIC_ROOT, STATICFILES_DIRS=[TEST_STATIC_ROOT], STATICFILES_FINDERS=[ "django.contrib.staticfiles.finders.FileSystemFinder", ], ) async def test_static_file_response(self): application = ASGIStaticFilesHandler(get_asgi_application()) # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/static/file.txt") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. file_path = TEST_STATIC_ROOT / "file.txt" with open(file_path, "rb") as test_file: test_file_contents = test_file.read() # Read the response. stat = file_path.stat() response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", str(len(test_file_contents)).encode("ascii")), (b"Content-Type", b"text/plain"), (b"Content-Disposition", b'inline; filename="file.txt"'), (b"Last-Modified", http_date(stat.st_mtime).encode("ascii")), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() async def test_headers(self): application = get_asgi_application() communicator = ApplicationCommunicator( application, self.async_request_factory._base_scope( path="/meta/", headers=[ [b"content-type", b"text/plain; charset=utf-8"], [b"content-length", b"77"], [b"referer", b"Scotland"], [b"referer", b"Wales"], ], ), ) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"19"), (b"Content-Type", b"text/plain; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"From Scotland,Wales") # Allow response.close() to finish await communicator.wait() async def test_post_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope( method="POST", path="/post/", query_string="echo=1", ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"Echo!"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Echo!") async def test_untouched_request_body_gets_closed(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(method="POST", path="/post/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 204) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") # Allow response.close() to finish await communicator.wait() async def test_get_query_string(self): application = get_asgi_application() for query_string in (b"name=Andrew", "name=Andrew"): with self.subTest(query_string=query_string): scope = self.async_request_factory._base_scope( path="/", query_string=query_string, ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello Andrew!") # Allow response.close() to finish await communicator.wait() async def test_disconnect(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_disconnect_with_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"some body"}) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_assert_in_listen_for_disconnect(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) await communicator.send_input({"type": "http.not_a_real_message"}) msg = "Invalid ASGI message after request body: http.not_a_real_message" with self.assertRaisesMessage(AssertionError, msg): await communicator.receive_output() async def test_delayed_disconnect_with_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/delayed_hello/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"some body"}) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_wrong_connection_type(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", type="other") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) msg = "Django can only handle ASGI/HTTP connections, not other." with self.assertRaisesMessage(ValueError, msg): await communicator.receive_output() async def test_non_unicode_query_string(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", query_string=b"\xff") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 400) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self): class SignalHandler: """Track threads handler is dispatched on.""" threads = [] def __call__(self, **kwargs): self.threads.append(threading.current_thread()) signal_handler = SignalHandler() request_started.connect(signal_handler) request_finished.connect(signal_handler) # Perform a basic request. application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # AsyncToSync should have executed the signals in the same thread. request_started_thread, request_finished_thread = signal_handler.threads self.assertEqual(request_started_thread, request_finished_thread) request_started.disconnect(signal_handler) request_finished.disconnect(signal_handler) async def test_concurrent_async_uses_multiple_thread_pools(self): sync_waiter.active_threads.clear() # Send 2 requests concurrently application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/wait/") communicators = [] for _ in range(2): communicators.append(ApplicationCommunicator(application, scope)) await communicators[-1].send_input({"type": "http.request"}) # Each request must complete with a status code of 200 # If requests aren't scheduled concurrently, the barrier in the # sync_wait view will time out, resulting in a 500 status code. for communicator in communicators: response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # The requests should have scheduled on different threads. Note # active_threads is a set (a thread can only appear once), therefore # length is a sufficient check. self.assertEqual(len(sync_waiter.active_threads), 2) sync_waiter.active_threads.clear() async def test_asyncio_cancel_error(self): # Flag to check if the view was cancelled. view_did_cancel = False # A view that will listen for the cancelled error. async def view(request): nonlocal view_did_cancel try: await asyncio.sleep(0.2) return HttpResponse("Hello World!") except asyncio.CancelledError: # Set the flag. view_did_cancel = True raise # Request class to use the view. class TestASGIRequest(ASGIRequest): urlconf = (path("cancel/", view),) # Handler to use request class. class TestASGIHandler(ASGIHandler): request_class = TestASGIRequest # Request cycle should complete since no disconnect was sent. application = TestASGIHandler() scope = self.async_request_factory._base_scope(path="/cancel/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() self.assertIs(view_did_cancel, False) # Request cycle with a disconnect before the view can respond. application = TestASGIHandler() scope = self.async_request_factory._base_scope(path="/cancel/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Let the view actually start. await asyncio.sleep(0.1) # Disconnect the client. await communicator.send_input({"type": "http.disconnect"}) # The handler should not send a response. with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() await communicator.wait() self.assertIs(view_did_cancel, True)
0aefc28e003636350f89466d79138259b1bf5a7eda01ed4193a8e002acad0259
import threading import time from django.http import FileResponse, HttpResponse from django.urls import path from django.views.decorators.csrf import csrf_exempt def hello(request): name = request.GET.get("name") or "World" return HttpResponse("Hello %s!" % name) def hello_with_delay(request): name = request.GET.get("name") or "World" time.sleep(1) return HttpResponse(f"Hello {name}!") def hello_meta(request): return HttpResponse( "From %s" % request.META.get("HTTP_REFERER") or "", content_type=request.META.get("CONTENT_TYPE"), ) def sync_waiter(request): with sync_waiter.lock: sync_waiter.active_threads.add(threading.current_thread()) sync_waiter.barrier.wait(timeout=0.5) return hello(request) @csrf_exempt def post_echo(request): if request.GET.get("echo"): return HttpResponse(request.body) else: return HttpResponse(status=204) sync_waiter.active_threads = set() sync_waiter.lock = threading.Lock() sync_waiter.barrier = threading.Barrier(2) test_filename = __file__ urlpatterns = [ path("", hello), path("file/", lambda x: FileResponse(open(test_filename, "rb"))), path("meta/", hello_meta), path("post/", post_echo), path("wait/", sync_waiter), path("delayed_hello/", hello_with_delay), ]
8b1a534bae434e00b607bacc2c84bc9c7f68212bb397492461d75f39e50f0310
from django.contrib import admin from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.contrib.contenttypes.admin import GenericTabularInline from django.contrib.contenttypes.models import ContentType from django.forms.formsets import DEFAULT_MAX_NUM from django.forms.models import ModelForm from django.test import ( RequestFactory, SimpleTestCase, TestCase, ignore_warnings, override_settings, ) from django.urls import reverse from django.utils.deprecation import RemovedInDjango60Warning from .admin import MediaInline, MediaPermanentInline from .admin import site as admin_site from .models import Category, Episode, EpisodePermanent, Media, PhoneNumber class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) @ignore_warnings(category=RemovedInDjango60Warning) @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericAdminViewTest(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) e = Episode.objects.create(name="This Week in Django") self.episode_pk = e.pk m = Media(content_object=e, url="http://example.com/podcast.mp3") m.save() self.mp3_media_pk = m.pk m = Media(content_object=e, url="http://example.com/logo.png") m.save() self.png_media_pk = m.pk def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:generic_inline_admin_episode_add")) self.assertEqual(response.status_code, 200) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get( reverse( "admin:generic_inline_admin_episode_change", args=(self.episode_pk,) ) ) self.assertEqual(response.status_code, 200) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "This Week in Django", # inline data "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": "1", "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": "0", "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0", } response = self.client.post( reverse("admin:generic_inline_admin_episode_add"), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ prefix = "generic_inline_admin-media-content_type-object_id" post_data = { "name": "This Week in Django", # inline data f"{prefix}-TOTAL_FORMS": "3", f"{prefix}-INITIAL_FORMS": "2", f"{prefix}-MAX_NUM_FORMS": "0", f"{prefix}-0-id": str(self.mp3_media_pk), f"{prefix}-0-url": "http://example.com/podcast.mp3", f"{prefix}-1-id": str(self.png_media_pk), f"{prefix}-1-url": "http://example.com/logo.png", f"{prefix}-2-id": "", f"{prefix}-2-url": "", } url = reverse( "admin:generic_inline_admin_episode_change", args=(self.episode_pk,) ) response = self.client.post(url, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere @ignore_warnings(category=RemovedInDjango60Warning) @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericInlineAdminParametersTest(TestDataMixin, TestCase): factory = RequestFactory() def setUp(self): self.client.force_login(self.superuser) def _create_object(self, model): """ Create a model with an attached Media object via GFK. We can't load content via a fixture (since the GenericForeignKey relies on content type IDs, which will vary depending on what other tests have been run), thus we do it here. """ e = model.objects.create(name="This Week in Django") Media.objects.create(content_object=e, url="http://example.com/podcast.mp3") return e def test_no_param(self): """ With one initial form, extra (default) at 3, there should be 4 forms. """ e = self._create_object(Episode) response = self.client.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) formset = response.context["inline_admin_formsets"][0].formset self.assertEqual(formset.total_form_count(), 4) self.assertEqual(formset.initial_form_count(), 1) def test_extra_param(self): """ With extra=0, there should be one form. """ class ExtraInline(GenericTabularInline): model = Media extra = 0 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [ExtraInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.total_form_count(), 1) self.assertEqual(formset.initial_form_count(), 1) def test_max_num_param(self): """ With extra=5 and max_num=2, there should be only 2 forms. """ class MaxNumInline(GenericTabularInline): model = Media extra = 5 max_num = 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [MaxNumInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.total_form_count(), 2) self.assertEqual(formset.initial_form_count(), 1) def test_min_num_param(self): """ With extra=3 and min_num=2, there should be five forms. """ class MinNumInline(GenericTabularInline): model = Media extra = 3 min_num = 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [MinNumInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.total_form_count(), 5) self.assertEqual(formset.initial_form_count(), 1) def test_get_extra(self): class GetExtraInline(GenericTabularInline): model = Media extra = 4 def get_extra(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetExtraInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.extra, 2) def test_get_min_num(self): class GetMinNumInline(GenericTabularInline): model = Media min_num = 5 def get_min_num(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetMinNumInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.min_num, 2) def test_get_max_num(self): class GetMaxNumInline(GenericTabularInline): model = Media extra = 5 def get_max_num(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetMaxNumInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.max_num, 2) @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericInlineAdminWithUniqueTogetherTest(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_add(self): category_id = Category.objects.create(name="male").pk prefix = "generic_inline_admin-phonenumber-content_type-object_id" post_data = { "name": "John Doe", # inline data f"{prefix}-TOTAL_FORMS": "1", f"{prefix}-INITIAL_FORMS": "0", f"{prefix}-MAX_NUM_FORMS": "0", f"{prefix}-0-id": "", f"{prefix}-0-phone_number": "555-555-5555", f"{prefix}-0-category": str(category_id), } response = self.client.get(reverse("admin:generic_inline_admin_contact_add")) self.assertEqual(response.status_code, 200) response = self.client.post( reverse("admin:generic_inline_admin_contact_add"), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_delete(self): from .models import Contact c = Contact.objects.create(name="foo") PhoneNumber.objects.create( object_id=c.id, content_type=ContentType.objects.get_for_model(Contact), phone_number="555-555-5555", ) response = self.client.post( reverse("admin:generic_inline_admin_contact_delete", args=[c.pk]) ) self.assertContains(response, "Are you sure you want to delete") @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class NoInlineDeletionTest(SimpleTestCase): @ignore_warnings(category=RemovedInDjango60Warning) def test_no_deletion(self): inline = MediaPermanentInline(EpisodePermanent, admin_site) fake_request = object() formset = inline.get_formset(fake_request) self.assertFalse(formset.can_delete) class MockRequest: pass class MockSuperUser: def has_perm(self, perm, obj=None): return True request = MockRequest() request.user = MockSuperUser() @override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericInlineModelAdminTest(SimpleTestCase): def setUp(self): self.site = AdminSite() @ignore_warnings(category=RemovedInDjango60Warning) def test_get_formset_kwargs(self): media_inline = MediaInline(Media, AdminSite()) # Create a formset with default arguments formset = media_inline.get_formset(request) self.assertEqual(formset.max_num, DEFAULT_MAX_NUM) self.assertIs(formset.can_order, False) # Create a formset with custom keyword arguments formset = media_inline.get_formset(request, max_num=100, can_order=True) self.assertEqual(formset.max_num, 100) self.assertIs(formset.can_order, True) def test_custom_form_meta_exclude_with_readonly(self): """ The custom ModelForm's `Meta.exclude` is respected when used in conjunction with `GenericInlineModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined. """ class MediaForm(ModelForm): class Meta: model = Media exclude = ["url"] class MediaInline(GenericTabularInline): readonly_fields = ["description"] form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = [MediaInline] ma = EpisodeAdmin(Episode, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["keywords", "id", "DELETE"], ) @ignore_warnings(category=RemovedInDjango60Warning) def test_custom_form_meta_exclude(self): """ The custom ModelForm's `Meta.exclude` is respected by `GenericInlineModelAdmin.get_formset`, and overridden if `ModelAdmin.exclude` or `GenericInlineModelAdmin.exclude` are defined. Refs #15907. """ # First with `GenericInlineModelAdmin` ----------------- class MediaForm(ModelForm): class Meta: model = Media exclude = ["url"] class MediaInline(GenericTabularInline): exclude = ["description"] form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = [MediaInline] ma = EpisodeAdmin(Episode, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["url", "keywords", "id", "DELETE"], ) # Then, only with `ModelForm` ----------------- class MediaInline(GenericTabularInline): form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = [MediaInline] ma = EpisodeAdmin(Episode, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["description", "keywords", "id", "DELETE"], ) @ignore_warnings(category=RemovedInDjango60Warning) def test_get_fieldsets(self): # get_fieldsets is called when figuring out form fields. # Refs #18681. class MediaForm(ModelForm): class Meta: model = Media fields = "__all__" class MediaInline(GenericTabularInline): form = MediaForm model = Media can_delete = False def get_fieldsets(self, request, obj=None): return [(None, {"fields": ["url", "description"]})] ma = MediaInline(Media, self.site) form = ma.get_formset(None).form self.assertEqual(form._meta.fields, ["url", "description"]) def test_get_formsets_with_inlines_returns_tuples(self): """ get_formsets_with_inlines() returns the correct tuples. """ class MediaForm(ModelForm): class Meta: model = Media exclude = ["url"] class MediaInline(GenericTabularInline): form = MediaForm model = Media class AlternateInline(GenericTabularInline): form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = [AlternateInline, MediaInline] ma = EpisodeAdmin(Episode, self.site) inlines = ma.get_inline_instances(request) for (formset, inline), other_inline in zip( ma.get_formsets_with_inlines(request), inlines ): self.assertIsInstance(formset, other_inline.get_formset(request).__class__) def test_get_inline_instances_override_get_inlines(self): class MediaInline(GenericTabularInline): model = Media class AlternateInline(GenericTabularInline): model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = (AlternateInline, MediaInline) def get_inlines(self, request, obj): if hasattr(request, "name"): if request.name == "alternate": return self.inlines[:1] elif request.name == "media": return self.inlines[1:2] return [] ma = EpisodeAdmin(Episode, self.site) self.assertEqual(ma.get_inlines(request, None), []) self.assertEqual(ma.get_inline_instances(request), []) for name, inline_class in ( ("alternate", AlternateInline), ("media", MediaInline), ): request.name = name self.assertEqual(ma.get_inlines(request, None), (inline_class,)), self.assertEqual(type(ma.get_inline_instances(request)[0]), inline_class)
8579fb078b6f1481219b13f13ae04576832d7f9a385e67557205d8a23cbd7a04
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.css") self.assertEqual(relpath, "cached/source_map_data_uri.3166be10260d.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"/*# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv*/" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.js") self.assertEqual(relpath, "cached/source_map_data_uri.a68d23cbf6dd.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"//# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_nonutf8(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(UnicodeDecodeError): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class JSModuleImportAggregationManifestStorage(storage.ManifestStaticFilesStorage): support_js_module_import_aggregation = True @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "staticfiles_tests.test_storage." "JSModuleImportAggregationManifestStorage" ), }, } ) class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage", }, }, ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
cd9f4bcac888e76676b04fae4c4fe5f5e1ae57b185aeacc97b75d439f282e383
import datetime import zoneinfo from django.test import TestCase from django.test.utils import override_settings, requires_tz_support from django.utils import timezone, translation from django.utils.timesince import timesince, timeuntil from django.utils.translation import npgettext_lazy class TimesinceTests(TestCase): def setUp(self): self.t = datetime.datetime(2007, 8, 14, 13, 46, 0) self.onemicrosecond = datetime.timedelta(microseconds=1) self.onesecond = datetime.timedelta(seconds=1) self.oneminute = datetime.timedelta(minutes=1) self.onehour = datetime.timedelta(hours=1) self.oneday = datetime.timedelta(days=1) self.oneweek = datetime.timedelta(days=7) self.onemonth = datetime.timedelta(days=31) self.oneyear = datetime.timedelta(days=366) def test_equal_datetimes(self): """equal datetimes.""" # NOTE: \xa0 avoids wrapping between value and unit self.assertEqual(timesince(self.t, self.t), "0\xa0minutes") def test_ignore_microseconds_and_seconds(self): """Microseconds and seconds are ignored.""" self.assertEqual( timesince(self.t, self.t + self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t + self.onesecond), "0\xa0minutes") def test_other_units(self): """Test other units.""" self.assertEqual(timesince(self.t, self.t + self.oneminute), "1\xa0minute") self.assertEqual(timesince(self.t, self.t + self.onehour), "1\xa0hour") self.assertEqual(timesince(self.t, self.t + self.oneday), "1\xa0day") self.assertEqual(timesince(self.t, self.t + self.oneweek), "1\xa0week") self.assertEqual(timesince(self.t, self.t + self.onemonth), "1\xa0month") self.assertEqual(timesince(self.t, self.t + self.oneyear), "1\xa0year") def test_multiple_units(self): """Test multiple units.""" self.assertEqual( timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), "2\xa0days, 6\xa0hours", ) self.assertEqual( timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), "2\xa0weeks, 2\xa0days", ) def test_display_first_unit(self): """ If the two differing units aren't adjacent, only the first unit is displayed. """ self.assertEqual( timesince( self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute, ), "2\xa0weeks", ) self.assertEqual( timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), "4\xa0days", ) def test_display_second_before_first(self): """ When the second date occurs before the first, we should always get 0 minutes. """ self.assertEqual( timesince(self.t, self.t - self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t - self.onesecond), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneminute), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onehour), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneday), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneweek), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onemonth), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneyear), "0\xa0minutes") self.assertEqual( timesince(self.t, self.t - 2 * self.oneday - 6 * self.onehour), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 2 * self.oneweek - 2 * self.oneday), "0\xa0minutes", ) self.assertEqual( timesince( self.t, self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute, ), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 4 * self.oneday - 5 * self.oneminute), "0\xa0minutes", ) def test_second_before_equal_first_humanize_time_strings(self): time_strings = { "minute": npgettext_lazy( "naturaltime-future", "%(num)d minute", "%(num)d minutes", "num", ), } with translation.override("cs"): for now in [self.t, self.t - self.onemicrosecond, self.t - self.oneday]: with self.subTest(now): self.assertEqual( timesince(self.t, now, time_strings=time_strings), "0\xa0minut", ) @requires_tz_support def test_different_timezones(self): """When using two different timezones.""" now = datetime.datetime.now() now_tz = timezone.make_aware(now, timezone.get_default_timezone()) now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195)) self.assertEqual(timesince(now), "0\xa0minutes") self.assertEqual(timesince(now_tz), "0\xa0minutes") self.assertEqual(timesince(now_tz_i), "0\xa0minutes") self.assertEqual(timesince(now_tz, now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now), "0\xa0minutes") self.assertEqual(timeuntil(now_tz), "0\xa0minutes") self.assertEqual(timeuntil(now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now_tz, now_tz_i), "0\xa0minutes") def test_date_objects(self): """Both timesince and timeuntil should work on date objects (#17937).""" today = datetime.date.today() self.assertEqual(timesince(today + self.oneday), "0\xa0minutes") self.assertEqual(timeuntil(today - self.oneday), "0\xa0minutes") def test_both_date_objects(self): """Timesince should work with both date objects (#9672)""" today = datetime.date.today() self.assertEqual(timeuntil(today + self.oneday, today), "1\xa0day") self.assertEqual(timeuntil(today - self.oneday, today), "0\xa0minutes") self.assertEqual(timeuntil(today + self.oneweek, today), "1\xa0week") def test_leap_year(self): start_date = datetime.date(2016, 12, 25) self.assertEqual(timeuntil(start_date + self.oneweek, start_date), "1\xa0week") self.assertEqual(timesince(start_date, start_date + self.oneweek), "1\xa0week") def test_leap_year_new_years_eve(self): t = datetime.date(2016, 12, 31) now = datetime.datetime(2016, 12, 31, 18, 0, 0) self.assertEqual(timesince(t + self.oneday, now), "0\xa0minutes") self.assertEqual(timeuntil(t - self.oneday, now), "0\xa0minutes") def test_naive_datetime_with_tzinfo_attribute(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None future = datetime.datetime(2080, 1, 1, tzinfo=naive()) self.assertEqual(timesince(future), "0\xa0minutes") past = datetime.datetime(1980, 1, 1, tzinfo=naive()) self.assertEqual(timeuntil(past), "0\xa0minutes") def test_thousand_years_ago(self): t = self.t.replace(year=self.t.year - 1000) self.assertEqual(timesince(t, self.t), "1000\xa0years") self.assertEqual(timeuntil(self.t, t), "1000\xa0years") def test_depth(self): t = ( self.t + self.oneyear + self.onemonth + self.oneweek + self.oneday + self.onehour ) tests = [ (t, 1, "1\xa0year"), (t, 2, "1\xa0year, 1\xa0month"), (t, 3, "1\xa0year, 1\xa0month, 1\xa0week"), (t, 4, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day"), (t, 5, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (t, 6, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (self.t + self.onehour, 5, "1\xa0hour"), (self.t + (4 * self.oneminute), 3, "4\xa0minutes"), (self.t + self.onehour + self.oneminute, 1, "1\xa0hour"), (self.t + self.oneday + self.onehour, 1, "1\xa0day"), (self.t + self.oneweek + self.oneday, 1, "1\xa0week"), (self.t + self.onemonth + self.oneweek, 1, "1\xa0month"), (self.t + self.oneyear + self.onemonth, 1, "1\xa0year"), (self.t + self.oneyear + self.oneweek + self.oneday, 3, "1\xa0year"), ] for value, depth, expected in tests: with self.subTest(): self.assertEqual(timesince(self.t, value, depth=depth), expected) self.assertEqual(timeuntil(value, self.t, depth=depth), expected) def test_months_edge(self): t = datetime.datetime(2022, 1, 1) tests = [ (datetime.datetime(2022, 1, 31), "4\xa0weeks, 2\xa0days"), (datetime.datetime(2022, 2, 1), "1\xa0month"), (datetime.datetime(2022, 2, 28), "1\xa0month, 3\xa0weeks"), (datetime.datetime(2022, 3, 1), "2\xa0months"), (datetime.datetime(2022, 3, 31), "2\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 4, 1), "3\xa0months"), (datetime.datetime(2022, 4, 30), "3\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 5, 1), "4\xa0months"), (datetime.datetime(2022, 5, 31), "4\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 6, 1), "5\xa0months"), (datetime.datetime(2022, 6, 30), "5\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 7, 1), "6\xa0months"), (datetime.datetime(2022, 7, 31), "6\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 8, 1), "7\xa0months"), (datetime.datetime(2022, 8, 31), "7\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 9, 1), "8\xa0months"), (datetime.datetime(2022, 9, 30), "8\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 10, 1), "9\xa0months"), (datetime.datetime(2022, 10, 31), "9\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 11, 1), "10\xa0months"), (datetime.datetime(2022, 11, 30), "10\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 12, 1), "11\xa0months"), (datetime.datetime(2022, 12, 31), "11\xa0months, 4\xa0weeks"), ] for value, expected in tests: with self.subTest(): self.assertEqual(timesince(t, value), expected) def test_depth_invalid(self): msg = "depth must be greater than 0." with self.assertRaisesMessage(ValueError, msg): timesince(self.t, self.t, depth=0) @requires_tz_support def test_less_than_a_day_with_zoneinfo(self): now_with_zoneinfo = timezone.now().astimezone( zoneinfo.ZoneInfo(key="Asia/Kathmandu") # UTC+05:45 ) tests = [ (now_with_zoneinfo, "0\xa0minutes"), (now_with_zoneinfo - self.onemicrosecond, "0\xa0minutes"), (now_with_zoneinfo - self.onesecond, "0\xa0minutes"), (now_with_zoneinfo - self.oneminute, "1\xa0minute"), (now_with_zoneinfo - self.onehour, "1\xa0hour"), ] for value, expected in tests: with self.subTest(value): self.assertEqual(timesince(value), expected) @requires_tz_support def test_less_than_a_day_cross_day_with_zoneinfo(self): now_with_zoneinfo = timezone.make_aware( datetime.datetime(2023, 4, 14, 1, 30, 30), zoneinfo.ZoneInfo(key="Asia/Kathmandu"), # UTC+05:45 ) now_utc = now_with_zoneinfo.astimezone(datetime.timezone.utc) tests = [ (now_with_zoneinfo, "0\xa0minutes"), (now_with_zoneinfo - self.onemicrosecond, "0\xa0minutes"), (now_with_zoneinfo - self.onesecond, "0\xa0minutes"), (now_with_zoneinfo - self.oneminute, "1\xa0minute"), (now_with_zoneinfo - self.onehour, "1\xa0hour"), ] for value, expected in tests: with self.subTest(value): self.assertEqual(timesince(value, now_utc), expected) @requires_tz_support @override_settings(USE_TZ=True) class TZAwareTimesinceTests(TimesinceTests): def setUp(self): super().setUp() self.t = timezone.make_aware(self.t, timezone.get_default_timezone())
064201de8b7dee939cec6a14e0ea4355a0b36f9127fc758407f8c544ad125222
from unittest import mock from django.test import SimpleTestCase from django.utils.functional import cached_property, classproperty, lazy class FunctionalTests(SimpleTestCase): def test_lazy(self): t = lazy(lambda: tuple(range(3)), list, tuple) for a, b in zip(t(), range(3)): self.assertEqual(a, b) def test_lazy_base_class(self): """lazy also finds base class methods in the proxy object""" class Base: def base_method(self): pass class Klazz(Base): pass t = lazy(lambda: Klazz(), Klazz)() self.assertIn("base_method", dir(t)) def test_lazy_base_class_override(self): """lazy finds the correct (overridden) method implementation""" class Base: def method(self): return "Base" class Klazz(Base): def method(self): return "Klazz" t = lazy(lambda: Klazz(), Base)() self.assertEqual(t.method(), "Klazz") def test_lazy_object_to_string(self): class Klazz: def __str__(self): return "Î am ā Ǩlâzz." def __bytes__(self): return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz." t = lazy(lambda: Klazz(), Klazz)() self.assertEqual(str(t), "Î am ā Ǩlâzz.") self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.") def assertCachedPropertyWorks(self, attr, Class): with self.subTest(attr=attr): def get(source): return getattr(source, attr) obj = Class() class SubClass(Class): pass subobj = SubClass() # Docstring is preserved. self.assertEqual(get(Class).__doc__, "Here is the docstring...") self.assertEqual(get(SubClass).__doc__, "Here is the docstring...") # It's cached. self.assertEqual(get(obj), get(obj)) self.assertEqual(get(subobj), get(subobj)) # The correct value is returned. self.assertEqual(get(obj)[0], 1) self.assertEqual(get(subobj)[0], 1) # State isn't shared between instances. obj2 = Class() subobj2 = SubClass() self.assertNotEqual(get(obj), get(obj2)) self.assertNotEqual(get(subobj), get(subobj2)) # It behaves like a property when there's no instance. self.assertIsInstance(get(Class), cached_property) self.assertIsInstance(get(SubClass), cached_property) # 'other_value' doesn't become a property. self.assertTrue(callable(obj.other_value)) self.assertTrue(callable(subobj.other_value)) def test_cached_property(self): """cached_property caches its value and behaves like a property.""" class Class: @cached_property def value(self): """Here is the docstring...""" return 1, object() @cached_property def __foo__(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["value", "other", "__foo__"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) def test_cached_property_auto_name(self): """ cached_property caches its value and behaves like a property on mangled methods or when the name kwarg isn't set. """ class Class: @cached_property def __value(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["_Class__value", "other"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) def test_cached_property_reuse_different_names(self): """Disallow this case because the decorated function wouldn't be cached.""" with self.assertRaises(RuntimeError) as ctx: class ReusedCachedProperty: @cached_property def a(self): pass b = a self.assertEqual( str(ctx.exception.__context__), str( TypeError( "Cannot assign the same cached_property to two different " "names ('a' and 'b')." ) ), ) def test_cached_property_reuse_same_name(self): """ Reusing a cached_property on different classes under the same name is allowed. """ counter = 0 @cached_property def _cp(_self): nonlocal counter counter += 1 return counter class A: cp = _cp class B: cp = _cp a = A() b = B() self.assertEqual(a.cp, 1) self.assertEqual(b.cp, 2) self.assertEqual(a.cp, 1) def test_cached_property_set_name_not_called(self): cp = cached_property(lambda s: None) class Foo: pass Foo.cp = cp msg = ( "Cannot use cached_property instance without calling __set_name__() on it." ) with self.assertRaisesMessage(TypeError, msg): Foo().cp def test_lazy_add(self): lazy_4 = lazy(lambda: 4, int) lazy_5 = lazy(lambda: 5, int) self.assertEqual(lazy_4() + lazy_5(), 9) def test_lazy_equality(self): """ == and != work correctly for Promises. """ lazy_a = lazy(lambda: 4, int) lazy_b = lazy(lambda: 4, int) lazy_c = lazy(lambda: 5, int) self.assertEqual(lazy_a(), lazy_b()) self.assertNotEqual(lazy_b(), lazy_c()) def test_lazy_repr_text(self): original_object = "Lazy translation text" lazy_obj = lazy(lambda: original_object, str) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_int(self): original_object = 15 lazy_obj = lazy(lambda: original_object, int) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_bytes(self): original_object = b"J\xc3\xbcst a str\xc3\xadng" lazy_obj = lazy(lambda: original_object, bytes) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_class_preparation_caching(self): # lazy() should prepare the proxy class only once i.e. the first time # it's used. lazified = lazy(lambda: 0, int) __proxy__ = lazified().__class__ with mock.patch.object(__proxy__, "__prepare_class__") as mocked: lazified() mocked.assert_not_called() def test_lazy_bytes_and_str_result_classes(self): lazy_obj = lazy(lambda: "test", str, bytes) msg = "Cannot call lazy() with both bytes and text return types." with self.assertRaisesMessage(ValueError, msg): lazy_obj() def test_lazy_str_cast_mixed_result_types(self): lazy_value = lazy(lambda: [1], str, list)() self.assertEqual(str(lazy_value), "[1]") def test_classproperty_getter(self): class Foo: foo_attr = 123 def __init__(self): self.foo_attr = 456 @classproperty def foo(cls): return cls.foo_attr class Bar: bar = classproperty() @bar.getter def bar(cls): return 123 self.assertEqual(Foo.foo, 123) self.assertEqual(Foo().foo, 123) self.assertEqual(Bar.bar, 123) self.assertEqual(Bar().bar, 123) def test_classproperty_override_getter(self): class Foo: @classproperty def foo(cls): return 123 @foo.getter def foo(cls): return 456 self.assertEqual(Foo.foo, 456) self.assertEqual(Foo().foo, 456)
47e088622310d46bf93f524bd813d56b705a1720258c277c17eca268cd219b13
from datetime import date from django import forms from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, TabularInline, get_content_type_for_model, ) from django.contrib.admin.sites import AdminSite from django.contrib.admin.widgets import ( AdminDateWidget, AdminRadioSelect, AutocompleteSelect, AutocompleteSelectMultiple, ) from django.contrib.auth.models import User from django.db import models from django.forms.widgets import Select from django.test import RequestFactory, SimpleTestCase, TestCase from django.test.utils import isolate_apps from django.utils.deprecation import RemovedInDjango60Warning from .models import Band, Concert, Song class MockRequest: pass class MockSuperUser: def has_perm(self, perm, obj=None): return True request = MockRequest() request.user = MockSuperUser() class ModelAdminTests(TestCase): @classmethod def setUpTestData(cls): cls.band = Band.objects.create( name="The Doors", bio="", sign_date=date(1965, 1, 1), ) def setUp(self): self.site = AdminSite() def test_modeladmin_str(self): ma = ModelAdmin(Band, self.site) self.assertEqual(str(ma), "modeladmin.ModelAdmin") def test_default_attributes(self): ma = ModelAdmin(Band, self.site) self.assertEqual(ma.actions, ()) self.assertEqual(ma.inlines, ()) # form/fields/fieldsets interaction ############################## def test_default_fields(self): ma = ModelAdmin(Band, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["name", "bio", "sign_date"] ) self.assertEqual(list(ma.get_fields(request)), ["name", "bio", "sign_date"]) self.assertEqual( list(ma.get_fields(request, self.band)), ["name", "bio", "sign_date"] ) self.assertIsNone(ma.get_exclude(request, self.band)) def test_default_fieldsets(self): # fieldsets_add and fieldsets_change should return a special data structure that # is used in the templates. They should generate the "right thing" whether we # have specified a custom form, the fields argument, or nothing at all. # # Here's the default case. There are no custom form_add/form_change methods, # no fields argument, and no fieldsets argument. ma = ModelAdmin(Band, self.site) self.assertEqual( ma.get_fieldsets(request), [(None, {"fields": ["name", "bio", "sign_date"]})], ) self.assertEqual( ma.get_fieldsets(request, self.band), [(None, {"fields": ["name", "bio", "sign_date"]})], ) def test_get_fieldsets(self): # get_fieldsets() is called when figuring out form fields (#18681). class BandAdmin(ModelAdmin): def get_fieldsets(self, request, obj=None): return [(None, {"fields": ["name", "bio"]})] ma = BandAdmin(Band, self.site) form = ma.get_form(None) self.assertEqual(form._meta.fields, ["name", "bio"]) class InlineBandAdmin(TabularInline): model = Concert fk_name = "main_band" can_delete = False def get_fieldsets(self, request, obj=None): return [(None, {"fields": ["day", "transport"]})] ma = InlineBandAdmin(Band, self.site) form = ma.get_formset(None).form self.assertEqual(form._meta.fields, ["day", "transport"]) def test_lookup_allowed_allows_nonexistent_lookup(self): """ A lookup_allowed allows a parameter whose field lookup doesn't exist. (#21129). """ class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertIs( ma.lookup_allowed("name__nonexistent", "test_value", request), True, ) @isolate_apps("modeladmin") def test_lookup_allowed_onetoone(self): class Department(models.Model): code = models.CharField(max_length=4, unique=True) class Employee(models.Model): department = models.ForeignKey(Department, models.CASCADE, to_field="code") class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) class EmployeeInfo(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) description = models.CharField(max_length=100) class EmployeeProfileAdmin(ModelAdmin): list_filter = [ "employee__employeeinfo__description", "employee__department__code", ] ma = EmployeeProfileAdmin(EmployeeProfile, self.site) # Reverse OneToOneField self.assertIs( ma.lookup_allowed( "employee__employeeinfo__description", "test_value", request ), True, ) # OneToOneField and ForeignKey self.assertIs( ma.lookup_allowed("employee__department__code", "test_value", request), True, ) @isolate_apps("modeladmin") def test_lookup_allowed_foreign_primary(self): class Country(models.Model): name = models.CharField(max_length=256) class Place(models.Model): country = models.ForeignKey(Country, models.CASCADE) class Restaurant(models.Model): place = models.OneToOneField(Place, models.CASCADE, primary_key=True) class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant, models.CASCADE) class WaiterAdmin(ModelAdmin): list_filter = [ "restaurant__place__country", "restaurant__place__country__name", ] ma = WaiterAdmin(Waiter, self.site) self.assertIs( ma.lookup_allowed("restaurant__place__country", "1", request), True, ) self.assertIs( ma.lookup_allowed("restaurant__place__country__id__exact", "1", request), True, ) self.assertIs( ma.lookup_allowed( "restaurant__place__country__name", "test_value", request ), True, ) def test_lookup_allowed_considers_dynamic_list_filter(self): class ConcertAdmin(ModelAdmin): list_filter = ["main_band__sign_date"] def get_list_filter(self, request): if getattr(request, "user", None): return self.list_filter + ["main_band__name"] return self.list_filter model_admin = ConcertAdmin(Concert, self.site) request_band_name_filter = RequestFactory().get( "/", {"main_band__name": "test"} ) self.assertIs( model_admin.lookup_allowed( "main_band__sign_date", "?", request_band_name_filter ), True, ) self.assertIs( model_admin.lookup_allowed( "main_band__name", "?", request_band_name_filter ), False, ) request_with_superuser = request self.assertIs( model_admin.lookup_allowed( "main_band__sign_date", "?", request_with_superuser ), True, ) self.assertIs( model_admin.lookup_allowed("main_band__name", "?", request_with_superuser), True, ) def test_lookup_allowed_without_request_deprecation(self): class ConcertAdmin(ModelAdmin): list_filter = ["main_band__sign_date"] def get_list_filter(self, request): return self.list_filter + ["main_band__name"] def lookup_allowed(self, lookup, value): return True model_admin = ConcertAdmin(Concert, self.site) msg = ( "`request` must be added to the signature of ModelAdminTests." "test_lookup_allowed_without_request_deprecation.<locals>." "ConcertAdmin.lookup_allowed()." ) request_band_name_filter = RequestFactory().get( "/", {"main_band__name": "test"} ) request_band_name_filter.user = User.objects.create_superuser( username="bob", email="[email protected]", password="test" ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): changelist = model_admin.get_changelist_instance(request_band_name_filter) filterspec = changelist.get_filters(request_band_name_filter)[0][0] self.assertEqual(filterspec.title, "sign date") filterspec = changelist.get_filters(request_band_name_filter)[0][1] self.assertEqual(filterspec.title, "name") self.assertSequenceEqual(filterspec.lookup_choices, [self.band.name]) def test_field_arguments(self): # If fields is specified, fieldsets_add and fieldsets_change should # just stick the fields into a formsets structure and return it. class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_fields(request)), ["name"]) self.assertEqual(list(ma.get_fields(request, self.band)), ["name"]) self.assertEqual(ma.get_fieldsets(request), [(None, {"fields": ["name"]})]) self.assertEqual( ma.get_fieldsets(request, self.band), [(None, {"fields": ["name"]})] ) def test_field_arguments_restricted_on_form(self): # If fields or fieldsets is specified, it should exclude fields on the # Form class to the fields specified. This may cause errors to be # raised in the db layer if required model fields aren't in fields/ # fieldsets, but that's preferable to ghost errors where a field in the # Form class isn't being displayed because it's not in fields/fieldsets. # Using `fields`. class BandAdmin(ModelAdmin): fields = ["name"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ["name"]) # Using `fieldsets`. class BandAdmin(ModelAdmin): fieldsets = [(None, {"fields": ["name"]})] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ["name"]) # Using `exclude`. class BandAdmin(ModelAdmin): exclude = ["bio"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) # You can also pass a tuple to `exclude`. class BandAdmin(ModelAdmin): exclude = ("bio",) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) # Using `fields` and `exclude`. class BandAdmin(ModelAdmin): fields = ["name", "bio"] exclude = ["bio"] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name"]) def test_custom_form_meta_exclude_with_readonly(self): """ The custom ModelForm's `Meta.exclude` is respected when used in conjunction with `ModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["bio"] class BandAdmin(ModelAdmin): readonly_fields = ["name"] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["sign_date"]) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): readonly_fields = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "opening_band", "id", "DELETE"], ) def test_custom_formfield_override_readonly(self): class AdminBandForm(forms.ModelForm): name = forms.CharField() class Meta: exclude = () model = Band class BandAdmin(ModelAdmin): form = AdminBandForm readonly_fields = ["name"] ma = BandAdmin(Band, self.site) # `name` shouldn't appear in base_fields because it's part of # readonly_fields. self.assertEqual(list(ma.get_form(request).base_fields), ["bio", "sign_date"]) # But it should appear in get_fields()/fieldsets() so it can be # displayed as read-only. self.assertEqual(list(ma.get_fields(request)), ["bio", "sign_date", "name"]) self.assertEqual( list(ma.get_fieldsets(request)), [(None, {"fields": ["bio", "sign_date", "name"]})], ) def test_custom_form_meta_exclude(self): """ The custom ModelForm's `Meta.exclude` is overridden if `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["bio"] class BandAdmin(ModelAdmin): exclude = ["name"] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["bio", "sign_date"]) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): exclude = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "opening_band", "day", "id", "DELETE"], ) def test_overriding_get_exclude(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ["bio", "sign_date"], ) def test_get_exclude_overrides_exclude(self): class BandAdmin(ModelAdmin): exclude = ["bio"] def get_exclude(self, request, obj=None): return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ["bio", "sign_date"], ) def test_get_exclude_takes_obj(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): if obj: return ["sign_date"] return ["name"] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request, self.band).base_fields), ["name", "bio"], ) def test_custom_form_validation(self): # If a form is specified, it should use it allowing custom validation # to work properly. This won't break any of the admin widgets or media. class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["name", "bio", "sign_date", "delete"], ) self.assertEqual( type(ma.get_form(request).base_fields["sign_date"].widget), AdminDateWidget ) def test_form_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `ModelAdmin.get_form()` overrides all other declarations (#8999). """ class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ["name"] class BandAdmin(ModelAdmin): exclude = ["sign_date"] form = AdminBandForm def get_form(self, request, obj=None, **kwargs): kwargs["exclude"] = ["bio"] return super().get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["name", "sign_date"]) def test_formset_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `InlineModelAdmin.get_formset()` overrides all other declarations (#8999). """ class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): exclude = ["transport"] form = AdminConcertForm fk_name = "main_band" model = Concert def get_formset(self, request, obj=None, **kwargs): kwargs["exclude"] = ["opening_band"] return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_formset_overriding_get_exclude_with_form_fields(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert fields = ["main_band", "opening_band", "day", "transport"] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = "main_band" model = Concert def get_exclude(self, request, obj=None): return ["opening_band"] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_formset_overriding_get_exclude_with_form_exclude(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ["day"] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = "main_band" model = Concert def get_exclude(self, request, obj=None): return ["opening_band"] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["main_band", "day", "transport", "id", "DELETE"], ) def test_raw_id_fields_widget_override(self): """ The autocomplete_fields, raw_id_fields, and radio_fields widgets may overridden by specifying a widget in get_formset(). """ class ConcertInline(TabularInline): model = Concert fk_name = "main_band" raw_id_fields = ("opening_band",) def get_formset(self, request, obj=None, **kwargs): kwargs["widgets"] = {"opening_band": Select} return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) band_widget = ( list(ma.get_formsets_with_inlines(request))[0][0]() .forms[0] .fields["opening_band"] .widget ) # Without the override this would be ForeignKeyRawIdWidget. self.assertIsInstance(band_widget, Select) def test_queryset_override(self): # If the queryset of a ModelChoiceField in a custom form is overridden, # RelatedFieldWidgetWrapper doesn't mess that up. band2 = Band.objects.create( name="The Beatles", bio="", sign_date=date(1962, 1, 1) ) ma = ModelAdmin(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper" data-model-ref="band">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Beatles</option>' '<option value="%d">The Doors</option>' "</select></div>" % (band2.id, self.band.id), ) class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["main_band"].queryset = Band.objects.filter( name="The Doors" ) class ConcertAdminWithForm(ModelAdmin): form = AdminConcertForm ma = ConcertAdminWithForm(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper" data-model-ref="band">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Doors</option>' "</select></div>" % self.band.id, ) def test_regression_for_ticket_15820(self): """ `obj` is passed from `InlineModelAdmin.get_fieldsets()` to `InlineModelAdmin.get_formset()`. """ class CustomConcertForm(forms.ModelForm): class Meta: model = Concert fields = ["day"] class ConcertInline(TabularInline): model = Concert fk_name = "main_band" def get_formset(self, request, obj=None, **kwargs): if obj: kwargs["form"] = CustomConcertForm return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] Concert.objects.create(main_band=self.band, opening_band=self.band, day=1) ma = BandAdmin(Band, self.site) inline_instances = ma.get_inline_instances(request) fieldsets = list(inline_instances[0].get_fieldsets(request)) self.assertEqual( fieldsets[0][1]["fields"], ["main_band", "opening_band", "day", "transport"] ) fieldsets = list( inline_instances[0].get_fieldsets(request, inline_instances[0].model) ) self.assertEqual(fieldsets[0][1]["fields"], ["day"]) # radio_fields behavior ########################################### def test_default_foreign_key_widget(self): # First, without any radio_fields specified, the widgets for ForeignKey # and fields with choices specified ought to be a basic Select widget. # ForeignKey widgets in the admin are wrapped with RelatedFieldWidgetWrapper so # they need to be handled properly when type checking. For Select fields, all of # the choices lists have a first entry of dashes. cma = ModelAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields["main_band"].widget.widget), Select) self.assertEqual( list(cmafa.base_fields["main_band"].widget.choices), [("", "---------"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["opening_band"].widget.widget), Select) self.assertEqual( list(cmafa.base_fields["opening_band"].widget.choices), [("", "---------"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["day"].widget), Select) self.assertEqual( list(cmafa.base_fields["day"].widget.choices), [("", "---------"), (1, "Fri"), (2, "Sat")], ) self.assertEqual(type(cmafa.base_fields["transport"].widget), Select) self.assertEqual( list(cmafa.base_fields["transport"].widget.choices), [("", "---------"), (1, "Plane"), (2, "Train"), (3, "Bus")], ) def test_foreign_key_as_radio_field(self): # Now specify all the fields as radio_fields. Widgets should now be # RadioSelect, and the choices list should have a first entry of 'None' if # blank=True for the model field. Finally, the widget should have the # 'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL. class ConcertAdmin(ModelAdmin): radio_fields = { "main_band": HORIZONTAL, "opening_band": VERTICAL, "day": VERTICAL, "transport": HORIZONTAL, } cma = ConcertAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual( type(cmafa.base_fields["main_band"].widget.widget), AdminRadioSelect ) self.assertEqual( cmafa.base_fields["main_band"].widget.attrs, {"class": "radiolist inline"} ) self.assertEqual( list(cmafa.base_fields["main_band"].widget.choices), [(self.band.id, "The Doors")], ) self.assertEqual( type(cmafa.base_fields["opening_band"].widget.widget), AdminRadioSelect ) self.assertEqual( cmafa.base_fields["opening_band"].widget.attrs, {"class": "radiolist"} ) self.assertEqual( list(cmafa.base_fields["opening_band"].widget.choices), [("", "None"), (self.band.id, "The Doors")], ) self.assertEqual(type(cmafa.base_fields["day"].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields["day"].widget.attrs, {"class": "radiolist"}) self.assertEqual( list(cmafa.base_fields["day"].widget.choices), [(1, "Fri"), (2, "Sat")] ) self.assertEqual(type(cmafa.base_fields["transport"].widget), AdminRadioSelect) self.assertEqual( cmafa.base_fields["transport"].widget.attrs, {"class": "radiolist inline"} ) self.assertEqual( list(cmafa.base_fields["transport"].widget.choices), [("", "None"), (1, "Plane"), (2, "Train"), (3, "Bus")], ) class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ("transport",) class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual( list(ma.get_form(request).base_fields), ["main_band", "opening_band", "day"] ) class AdminConcertForm(forms.ModelForm): extra = forms.CharField() class Meta: model = Concert fields = ["extra", "transport"] class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ["extra", "transport"]) class ConcertInline(TabularInline): form = AdminConcertForm model = Concert fk_name = "main_band" can_delete = True class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ["extra", "transport", "id", "DELETE", "main_band"], ) def test_log_actions(self): ma = ModelAdmin(Band, self.site) mock_request = MockRequest() mock_request.user = User.objects.create(username="bill") content_type = get_content_type_for_model(self.band) tests = ( (ma.log_addition, ADDITION, {"added": {}}), (ma.log_change, CHANGE, {"changed": {"fields": ["name", "bio"]}}), (ma.log_deletion, DELETION, str(self.band)), ) for method, flag, message in tests: with self.subTest(name=method.__name__): created = method(mock_request, self.band, message) fetched = LogEntry.objects.filter(action_flag=flag).latest("id") self.assertEqual(created, fetched) self.assertEqual(fetched.action_flag, flag) self.assertEqual(fetched.content_type, content_type) self.assertEqual(fetched.object_id, str(self.band.pk)) self.assertEqual(fetched.user, mock_request.user) if flag == DELETION: self.assertEqual(fetched.change_message, "") self.assertEqual(fetched.object_repr, message) else: self.assertEqual(fetched.change_message, str(message)) self.assertEqual(fetched.object_repr, str(self.band)) def test_get_autocomplete_fields(self): class NameAdmin(ModelAdmin): search_fields = ["name"] class SongAdmin(ModelAdmin): autocomplete_fields = ["featuring"] fields = ["featuring", "band"] class OtherSongAdmin(SongAdmin): def get_autocomplete_fields(self, request): return ["band"] self.site.register(Band, NameAdmin) try: # Uses autocomplete_fields if not overridden. model_admin = SongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance( form.fields["featuring"].widget.widget, AutocompleteSelectMultiple ) # Uses overridden get_autocomplete_fields model_admin = OtherSongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields["band"].widget.widget, AutocompleteSelect) finally: self.site.unregister(Band) def test_get_deleted_objects(self): mock_request = MockRequest() mock_request.user = User.objects.create_superuser( username="bob", email="[email protected]", password="test" ) self.site.register(Band, ModelAdmin) ma = self.site._registry[Band] ( deletable_objects, model_count, perms_needed, protected, ) = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ["Band: The Doors"]) self.assertEqual(model_count, {"bands": 1}) self.assertEqual(perms_needed, set()) self.assertEqual(protected, []) def test_get_deleted_objects_with_custom_has_delete_permission(self): """ ModelAdmin.get_deleted_objects() uses ModelAdmin.has_delete_permission() for permissions checking. """ mock_request = MockRequest() mock_request.user = User.objects.create_superuser( username="bob", email="[email protected]", password="test" ) class TestModelAdmin(ModelAdmin): def has_delete_permission(self, request, obj=None): return False self.site.register(Band, TestModelAdmin) ma = self.site._registry[Band] ( deletable_objects, model_count, perms_needed, protected, ) = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ["Band: The Doors"]) self.assertEqual(model_count, {"bands": 1}) self.assertEqual(perms_needed, {"band"}) self.assertEqual(protected, []) def test_modeladmin_repr(self): ma = ModelAdmin(Band, self.site) self.assertEqual( repr(ma), "<ModelAdmin: model=Band site=AdminSite(name='admin')>", ) class ModelAdminPermissionTests(SimpleTestCase): class MockUser: def has_module_perms(self, app_label): return app_label == "modeladmin" class MockViewUser(MockUser): def has_perm(self, perm, obj=None): return perm == "modeladmin.view_band" class MockAddUser(MockUser): def has_perm(self, perm, obj=None): return perm == "modeladmin.add_band" class MockChangeUser(MockUser): def has_perm(self, perm, obj=None): return perm == "modeladmin.change_band" class MockDeleteUser(MockUser): def has_perm(self, perm, obj=None): return perm == "modeladmin.delete_band" def test_has_view_permission(self): """ has_view_permission() returns True for users who can view objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_view_permission(request), True) request.user = self.MockAddUser() self.assertIs(ma.has_view_permission(request), False) request.user = self.MockChangeUser() self.assertIs(ma.has_view_permission(request), True) request.user = self.MockDeleteUser() self.assertIs(ma.has_view_permission(request), False) def test_has_add_permission(self): """ has_add_permission returns True for users who can add objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertFalse(ma.has_add_permission(request)) request.user = self.MockAddUser() self.assertTrue(ma.has_add_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_add_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_add_permission(request)) def test_inline_has_add_permission_uses_obj(self): class ConcertInline(TabularInline): model = Concert def has_add_permission(self, request, obj): return bool(obj) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockAddUser() self.assertEqual(ma.get_inline_instances(request), []) band = Band(name="The Doors", bio="", sign_date=date(1965, 1, 1)) inline_instances = ma.get_inline_instances(request, band) self.assertEqual(len(inline_instances), 1) self.assertIsInstance(inline_instances[0], ConcertInline) def test_has_change_permission(self): """ has_change_permission returns True for users who can edit objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_change_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_change_permission(request)) request.user = self.MockChangeUser() self.assertTrue(ma.has_change_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_change_permission(request)) def test_has_delete_permission(self): """ has_delete_permission returns True for users who can delete objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_delete_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_delete_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_delete_permission(request)) request.user = self.MockDeleteUser() self.assertTrue(ma.has_delete_permission(request)) def test_has_module_permission(self): """ as_module_permission returns True for users who have any permission for the module and False for users who don't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_module_permission(request), True) request.user = self.MockAddUser() self.assertTrue(ma.has_module_permission(request)) request.user = self.MockChangeUser() self.assertTrue(ma.has_module_permission(request)) request.user = self.MockDeleteUser() self.assertTrue(ma.has_module_permission(request)) original_app_label = ma.opts.app_label ma.opts.app_label = "anotherapp" try: request.user = self.MockViewUser() self.assertIs(ma.has_module_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_module_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_module_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_module_permission(request)) finally: ma.opts.app_label = original_app_label
361d560ebe95efdc526788fde6259289aa48045aaf1c762353faeb63dbd728ee
from django import forms from django.contrib import admin from django.contrib.admin import BooleanFieldListFilter, SimpleListFilter from django.contrib.admin.options import VERTICAL, ModelAdmin, TabularInline from django.contrib.admin.sites import AdminSite from django.core.checks import Error from django.db.models import CASCADE, F, Field, ForeignKey, Model from django.db.models.functions import Upper from django.forms.models import BaseModelFormSet from django.test import SimpleTestCase from .models import Band, Song, User, ValidationTestInlineModel, ValidationTestModel class CheckTestCase(SimpleTestCase): def assertIsInvalid( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None, admin_site=None, ): if admin_site is None: admin_site = AdminSite() invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, admin_site) self.assertEqual( admin_obj.check(), [Error(msg, hint=hint, obj=invalid_obj, id=id)] ) def assertIsInvalidRegexp( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None ): """ Same as assertIsInvalid but treats the given msg as a regexp. """ invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.hint, hint) self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.id, id) self.assertRegex(error.msg, msg) def assertIsValid(self, model_admin, model, admin_site=None): if admin_site is None: admin_site = AdminSite() admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), []) class RawIdCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): raw_id_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields' must be a list or tuple.", "admin.E001", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' must be a foreign key or a " "many-to-many field.", "admin.E003", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_field_attname(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ["band_id"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'band_id', which is " "not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) class FieldsetsCheckTests(CheckTestCase): def test_valid_case(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_not_iterable(self): class TestModelAdmin(ModelAdmin): fieldsets = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets' must be a list or tuple.", "admin.E007", ) def test_non_iterable_item(self): class TestModelAdmin(ModelAdmin): fieldsets = ({},) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be a list or tuple.", "admin.E008", ) def test_item_not_a_pair(self): class TestModelAdmin(ModelAdmin): fieldsets = ((),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be of length 2.", "admin.E009", ) def test_second_element_of_item_not_a_dict(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", ()),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must be a dictionary.", "admin.E010", ) def test_missing_fields_key(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {}),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must contain the key 'fields'.", "admin.E011", ) class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_specified_both_fields_and_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) fields = ["name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "Both 'fieldsets' and 'fields' are specified.", "admin.E005", ) def test_duplicate_fields(self): class TestModelAdmin(ModelAdmin): fieldsets = [(None, {"fields": ["name", "name"]})] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[0][1]'.", "admin.E012", ) def test_duplicate_fields_in_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = [ (None, {"fields": ["name"]}), (None, {"fields": ["name"]}), ] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[1][1]'.", "admin.E012", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) class FieldsCheckTests(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ["name", "name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", "admin.E006", ) def test_inline(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fields = 10 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' must be a list or tuple.", "admin.E004", invalid_obj=ValidationTestInline, ) class FormCheckTests(CheckTestCase): def test_invalid_type(self): class FakeForm: pass class TestModelAdmin(ModelAdmin): form = FakeForm class TestModelAdminWithNoForm(ModelAdmin): form = "not a form" for model_admin in (TestModelAdmin, TestModelAdminWithNoForm): with self.subTest(model_admin): self.assertIsInvalid( model_admin, ValidationTestModel, "The value of 'form' must inherit from 'BaseModelForm'.", "admin.E016", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) def test_valid_case(self): class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm fieldsets = (("Band", {"fields": ("name", "bio", "sign_date", "delete")}),) self.assertIsValid(BandAdmin, Band) class FilterVerticalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", "admin.E017", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' must be a many-to-many field.", "admin.E020", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FilterHorizontalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_horizontal = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal' must be a list or tuple.", "admin.E018", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' must be a many-to-many field.", "admin.E020", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class RadioFieldsCheckTests(CheckTestCase): def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): radio_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' must be a dictionary.", "admin.E021", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): radio_fields = {"non_existent_field": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E022", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): radio_fields = {"name": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'name', which is not an instance " "of ForeignKey, and does not have a 'choices' definition.", "admin.E023", ) def test_invalid_value(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": None} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or " "admin.VERTICAL.", "admin.E024", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": VERTICAL} self.assertIsValid(TestModelAdmin, ValidationTestModel) class PrepopulatedFieldsCheckTests(CheckTestCase): def test_not_list_or_tuple(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": "test"} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"]' must be a list or tuple.", "admin.E029", ) def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' must be a dictionary.", "admin.E026", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"non_existent_field": ("slug",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E027", ) def test_missing_field_again(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("non_existent_field",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"][0]' refers to " "'non_existent_field', which is not a field of " "'modeladmin.ValidationTestModel'.", "admin.E030", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"users": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'users', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", "admin.E028", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("name",)} self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_one_to_one_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"best_friend": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'best_friend', which must " "not be a DateTimeField, a ForeignKey, a OneToOneField, or a " "ManyToManyField.", "admin.E028", ) class ListDisplayTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display' must be a list or tuple.", "admin.E107", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'non_existent_field', " "which is not a callable, an attribute of 'TestModelAdmin', " "or an attribute or method on 'modeladmin.ValidationTestModel'.", "admin.E108", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): list_display = ("users",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_reverse_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ["song_set"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ["song"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_m2m_related_name(self): class TestModelAdmin(ModelAdmin): list_display = ["featured"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_field_accessible_via_instance(self): class PositionField(Field): """Custom field accessible only via instance.""" def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, self) def __get__(self, instance, owner): if instance is None: raise AttributeError() class TestModel(Model): field = PositionField() class TestModelAdmin(ModelAdmin): list_display = ("field",) self.assertIsValid(TestModelAdmin, TestModel) class ListDisplayLinksCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display_links = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display_links = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, ( "The value of 'list_display_links[0]' refers to " "'non_existent_field', which is not defined in 'list_display'." ), "admin.E111", ) def test_missing_in_list_display(self): class TestModelAdmin(ModelAdmin): list_display_links = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links[0]' refers to 'name', which is not " "defined in 'list_display'.", "admin.E111", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) list_display_links = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_None_is_valid_case(self): class TestModelAdmin(ModelAdmin): list_display_links = None self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_links_check_skipped_if_get_list_display_overridden(self): """ list_display_links check is skipped if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = ["name", "subtitle"] def get_list_display(self, request): pass self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_link_checked_for_list_tuple_if_get_list_display_overridden( self, ): """ list_display_links is checked for list/tuple/None even if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = "non-list/tuple" def get_list_display(self, request): pass self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) class ListFilterTests(CheckTestCase): def test_list_filter_validation(self): class TestModelAdmin(ModelAdmin): list_filter = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter' must be a list or tuple.", "admin.E112", ) def test_not_list_filter_class(self): class TestModelAdmin(ModelAdmin): list_filter = ["RandomClass"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'RandomClass', which " "does not refer to a Field.", "admin.E116", ) def test_callable(self): def random_callable(): pass class TestModelAdmin(ModelAdmin): list_filter = [random_callable] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_callable(self): class TestModelAdmin(ModelAdmin): list_filter = [[42, 42]] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_filter = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E116", ) def test_not_filter(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (RandomClass,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_filter_again(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (("is_active", RandomClass),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_not_filter_again_again(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = (("is_active", AwesomeFilter),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_list_filter_is_func(self): def get_filter(): pass class TestModelAdmin(ModelAdmin): list_filter = [get_filter] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_associated_with_field_name(self): class TestModelAdmin(ModelAdmin): list_filter = (BooleanFieldListFilter,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.", "admin.E114", ) def test_valid_case(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = ( "is_active", AwesomeFilter, ("is_active", BooleanFieldListFilter), "no", ) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListPerPageCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_per_page = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_per_page' must be an integer.", "admin.E118", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_per_page = 100 self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListMaxShowAllCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_max_show_all = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_max_show_all' must be an integer.", "admin.E119", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 200 self.assertIsValid(TestModelAdmin, ValidationTestModel) class SearchFieldsCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): search_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'search_fields' must be a list or tuple.", "admin.E126", ) class DateHierarchyCheckTests(CheckTestCase): def test_missing_field(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "non_existent_field" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E127", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "name" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", "admin.E128", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "pub_date" self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "band__sign_date" self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "band__name" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", "admin.E128", ) class OrderingCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): ordering = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' must be a list or tuple.", "admin.E031", ) class TestModelAdmin(ModelAdmin): ordering = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E033", ) def test_random_marker_not_alone(self): class TestModelAdmin(ModelAdmin): ordering = ("?", "name") self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' has the random ordering marker '?', but contains " "other fields as well.", "admin.E032", hint='Either remove the "?", or remove the other fields.', ) def test_valid_random_marker_case(self): class TestModelAdmin(ModelAdmin): ordering = ("?",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_complex_case(self): class TestModelAdmin(ModelAdmin): ordering = ("band__name",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_case(self): class TestModelAdmin(ModelAdmin): ordering = ("name", "pk") self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_invalid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (F("nonexistent"),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'nonexistent', which is not " "a field of 'modeladmin.ValidationTestModel'.", "admin.E033", ) def test_valid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (Upper("name"), Upper("band__name").desc()) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListSelectRelatedCheckTests(CheckTestCase): def test_invalid_type(self): class TestModelAdmin(ModelAdmin): list_select_related = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_select_related' must be a boolean, tuple or list.", "admin.E117", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_select_related = False self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveAsCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_as = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_as' must be a boolean.", "admin.E101", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_as = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveOnTopCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_on_top = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_on_top' must be a boolean.", "admin.E102", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_on_top = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class InlinesCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): inlines = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'inlines' must be a list or tuple.", "admin.E103", ) def test_not_correct_inline_field(self): class TestModelAdmin(ModelAdmin): inlines = [42] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.TestModelAdmin' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_not_model_admin(self): class ValidationTestInline: pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_missing_model_field(self): class ValidationTestInline(TabularInline): pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must have a 'model' attribute\.", "admin.E105", ) def test_invalid_model_type(self): class SomethingBad: pass class ValidationTestInline(TabularInline): model = SomethingBad class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", "admin.E106", ) def test_invalid_model(self): class ValidationTestInline(TabularInline): model = "Not a class" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", "admin.E106", ) def test_invalid_callable(self): def random_obj(): pass class TestModelAdmin(ModelAdmin): inlines = [random_obj] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.random_obj' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FkNameCheckTests(CheckTestCase): def test_missing_field(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = "non_existent_field" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "'modeladmin.ValidationTestInlineModel' has no field named " "'non_existent_field'.", "admin.E202", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = "parent" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_proxy_model_parent(self): class Parent(Model): pass class ProxyChild(Parent): class Meta: proxy = True class ProxyProxyChild(ProxyChild): class Meta: proxy = True class Related(Model): proxy_child = ForeignKey(ProxyChild, on_delete=CASCADE) class InlineFkName(admin.TabularInline): model = Related fk_name = "proxy_child" class InlineNoFkName(admin.TabularInline): model = Related class ProxyProxyChildAdminFkName(admin.ModelAdmin): inlines = [InlineFkName, InlineNoFkName] self.assertIsValid(ProxyProxyChildAdminFkName, ProxyProxyChild) class ExtraCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'extra' must be an integer.", "admin.E203", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MaxNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'max_num' must be an integer.", "admin.E204", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MinNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'min_num' must be an integer.", "admin.E205", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FormsetCheckTests(CheckTestCase): def test_invalid_type(self): class FakeFormSet: pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = FakeFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", "admin.E206", invalid_obj=ValidationTestInline, ) def test_inline_without_formset_class(self): class ValidationTestInlineWithoutFormsetClass(TabularInline): model = ValidationTestInlineModel formset = "Not a FormSet Class" class TestModelAdminWithoutFormsetClass(ModelAdmin): inlines = [ValidationTestInlineWithoutFormsetClass] self.assertIsInvalid( TestModelAdminWithoutFormsetClass, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", "admin.E206", invalid_obj=ValidationTestInlineWithoutFormsetClass, ) def test_valid_case(self): class RealModelFormSet(BaseModelFormSet): pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = RealModelFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListDisplayEditableTests(CheckTestCase): def test_list_display_links_is_none(self): """ list_display and list_editable can contain the same values when list_display_links is None """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = list_display list_display_links = None self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_first_item(self): """ The first item in list_display can be the same as the first in list_editable. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["name", "slug"] list_display_links = ["pub_date"] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_in_list_editable(self): """ The first item in list_display can be in list_editable as long as list_display_links is defined. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["slug", "name"] list_display_links = ["pub_date"] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_no_list_display_links(self): """ The first item in list_display cannot be the same as the first item in list_editable if list_display_links is not defined. """ class ProductAdmin(ModelAdmin): list_display = ["name"] list_editable = ["name"] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[0]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id="admin.E124", ) def test_list_display_first_item_in_list_editable_no_list_display_links(self): """ The first item in list_display cannot be in list_editable if list_display_links isn't defined. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["slug", "name"] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[1]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id="admin.E124", ) def test_both_list_editable_and_list_display_links(self): class ProductAdmin(ModelAdmin): list_editable = ("name",) list_display = ("name",) list_display_links = ("name",) self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'name' cannot be in both 'list_editable' and " "'list_display_links'.", id="admin.E123", ) class AutocompleteFieldsTests(CheckTestCase): def test_autocomplete_e036(self): class Admin(ModelAdmin): autocomplete_fields = "name" self.assertIsInvalid( Admin, Band, msg="The value of 'autocomplete_fields' must be a list or tuple.", id="admin.E036", invalid_obj=Admin, ) def test_autocomplete_e037(self): class Admin(ModelAdmin): autocomplete_fields = ("nonexistent",) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' refers to 'nonexistent', " "which is not a field of 'modeladmin.ValidationTestModel'." ), id="admin.E037", invalid_obj=Admin, ) def test_autocomplete_e38(self): class Admin(ModelAdmin): autocomplete_fields = ("name",) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' must be a foreign " "key or a many-to-many field." ), id="admin.E038", invalid_obj=Admin, ) def test_autocomplete_e039(self): class Admin(ModelAdmin): autocomplete_fields = ("band",) self.assertIsInvalid( Admin, Song, msg=( 'An admin for model "Band" has to be registered ' "to be referenced by Admin.autocomplete_fields." ), id="admin.E039", invalid_obj=Admin, ) def test_autocomplete_e040(self): class NoSearchFieldsAdmin(ModelAdmin): pass class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ("featuring",) site = AdminSite() site.register(Band, NoSearchFieldsAdmin) self.assertIsInvalid( AutocompleteAdmin, Song, msg=( 'NoSearchFieldsAdmin must define "search_fields", because ' "it's referenced by AutocompleteAdmin.autocomplete_fields." ), id="admin.E040", invalid_obj=AutocompleteAdmin, admin_site=site, ) def test_autocomplete_is_valid(self): class SearchFieldsAdmin(ModelAdmin): search_fields = "name" class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ("featuring",) site = AdminSite() site.register(Band, SearchFieldsAdmin) self.assertIsValid(AutocompleteAdmin, Song, admin_site=site) def test_autocomplete_is_onetoone(self): class UserAdmin(ModelAdmin): search_fields = ("name",) class Admin(ModelAdmin): autocomplete_fields = ("best_friend",) site = AdminSite() site.register(User, UserAdmin) self.assertIsValid(Admin, ValidationTestModel, admin_site=site) class ActionsCheckTests(CheckTestCase): def test_custom_permissions_require_matching_has_method(self): @admin.action(permissions=["custom"]) def custom_permission_action(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (custom_permission_action,) self.assertIsInvalid( BandAdmin, Band, "BandAdmin must define a has_custom_permission() method for the " "custom_permission_action action.", id="admin.E129", ) def test_actions_not_unique(self): @admin.action def action(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action, action) self.assertIsInvalid( BandAdmin, Band, "__name__ attributes of actions defined in BandAdmin must be " "unique. Name 'action' is not unique.", id="admin.E130", ) def test_actions_unique(self): @admin.action def action1(modeladmin, request, queryset): pass @admin.action def action2(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action1, action2) self.assertIsValid(BandAdmin, Band)
c501e7425b756eacd57c28c691099ae450a4d0545dcce21974f73863ac9f0243
from unittest import mock from django.http import HttpRequest from django.template import ( Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase, override_settings class ContextTests(SimpleTestCase): def test_context(self): c = Context({"a": 1, "b": "xyzzy"}) self.assertEqual(c["a"], 1) self.assertEqual(c.push(), {}) c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c.get("a"), 2) self.assertEqual(c.pop(), {"a": 2}) self.assertEqual(c["a"], 1) self.assertEqual(c.get("foo", 42), 42) self.assertEqual(c, mock.ANY) def test_push_context_manager(self): c = Context({"a": 1}) with c.push(): c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c["a"], 1) with c.push(a=3): self.assertEqual(c["a"], 3) self.assertEqual(c["a"], 1) def test_update_context_manager(self): c = Context({"a": 1}) with c.update({}): c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c["a"], 1) with c.update({"a": 3}): self.assertEqual(c["a"], 3) self.assertEqual(c["a"], 1) def test_push_context_manager_with_context_object(self): c = Context({"a": 1}) with c.push(Context({"a": 3})): self.assertEqual(c["a"], 3) self.assertEqual(c["a"], 1) def test_update_context_manager_with_context_object(self): c = Context({"a": 1}) with c.update(Context({"a": 3})): self.assertEqual(c["a"], 3) self.assertEqual(c["a"], 1) def test_push_proper_layering(self): c = Context({"a": 1}) c.push(Context({"b": 2})) c.push(Context({"c": 3, "d": {"z": "26"}})) self.assertEqual( c.dicts, [ {"False": False, "None": None, "True": True}, {"a": 1}, {"b": 2}, {"c": 3, "d": {"z": "26"}}, ], ) def test_update_proper_layering(self): c = Context({"a": 1}) c.update(Context({"b": 2})) c.update(Context({"c": 3, "d": {"z": "26"}})) self.assertEqual( c.dicts, [ {"False": False, "None": None, "True": True}, {"a": 1}, {"b": 2}, {"c": 3, "d": {"z": "26"}}, ], ) def test_setdefault(self): c = Context() x = c.setdefault("x", 42) self.assertEqual(x, 42) self.assertEqual(c["x"], 42) x = c.setdefault("x", 100) self.assertEqual(x, 42) self.assertEqual(c["x"], 42) def test_resolve_on_context_method(self): """ #17778 -- Variable shouldn't resolve RequestContext methods """ empty_context = Context() with self.assertRaises(VariableDoesNotExist): Variable("no_such_variable").resolve(empty_context) with self.assertRaises(VariableDoesNotExist): Variable("new").resolve(empty_context) self.assertEqual( Variable("new").resolve(Context({"new": "foo"})), "foo", ) def test_render_context(self): test_context = RenderContext({"fruit": "papaya"}) # push() limits access to the topmost dict test_context.push() test_context["vegetable"] = "artichoke" self.assertEqual(list(test_context), ["vegetable"]) self.assertNotIn("fruit", test_context) with self.assertRaises(KeyError): test_context["fruit"] self.assertIsNone(test_context.get("fruit")) def test_flatten_context(self): a = Context() a.update({"a": 2}) a.update({"b": 4}) a.update({"c": 8}) self.assertEqual( a.flatten(), {"False": False, "None": None, "True": True, "a": 2, "b": 4, "c": 8}, ) def test_flatten_context_with_context(self): """ Context.push() with a Context argument should work. """ a = Context({"a": 2}) a.push(Context({"z": "8"})) self.assertEqual( a.flatten(), { "False": False, "None": None, "True": True, "a": 2, "z": "8", }, ) def test_context_comparable(self): """ #21765 -- equality comparison should work """ test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}} self.assertEqual(Context(test_data), Context(test_data)) a = Context() b = Context() self.assertEqual(a, b) # update only a a.update({"a": 1}) self.assertNotEqual(a, b) # update both to check regression a.update({"c": 3}) b.update({"c": 3}) self.assertNotEqual(a, b) # make contexts equals again b.update({"a": 1}) self.assertEqual(a, b) def test_copy_request_context_twice(self): """ #24273 -- Copy twice shouldn't raise an exception """ RequestContext(HttpRequest()).new().new() def test_set_upward(self): c = Context({"a": 1}) c.set_upward("a", 2) self.assertEqual(c.get("a"), 2) def test_set_upward_empty_context(self): empty_context = Context() empty_context.set_upward("a", 1) self.assertEqual(empty_context.get("a"), 1) def test_set_upward_with_push(self): """ The highest context which has the given key is used. """ c = Context({"a": 1}) c.push({"a": 2}) c.set_upward("a", 3) self.assertEqual(c.get("a"), 3) c.pop() self.assertEqual(c.get("a"), 1) def test_set_upward_with_push_no_match(self): """ The highest context is used if the given key isn't found. """ c = Context({"b": 1}) c.push({"b": 2}) c.set_upward("a", 2) self.assertEqual(len(c.dicts), 3) self.assertEqual(c.dicts[-1]["a"], 2) def context_process_returning_none(request): return None class RequestContextTests(SimpleTestCase): request_factory = RequestFactory() def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine( loaders=[ ( "django.template.loaders.locmem.Loader", { "child": '{{ var|default:"none" }}', }, ), ] ) request = self.request_factory.get("/") ctx = RequestContext(request, {"var": "parent"}) self.assertEqual( engine.from_string('{% include "child" %}').render(ctx), "parent" ) self.assertEqual( engine.from_string('{% include "child" only %}').render(ctx), "none" ) def test_stack_size(self): """Optimized RequestContext construction (#7116).""" request = self.request_factory.get("/") ctx = RequestContext(request, {}) # The stack contains 4 items: # [builtins, supplied context, context processor, empty dict] self.assertEqual(len(ctx.dicts), 4) def test_context_comparable(self): # Create an engine without any context processors. test_data = {"x": "y", "v": "z", "d": {"o": object, "a": "b"}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future request = self.request_factory.get("/") self.assertEqual( RequestContext(request, dict_=test_data), RequestContext(request, dict_=test_data), ) def test_modify_context_and_render(self): template = Template("{{ foo }}") request = self.request_factory.get("/") context = RequestContext(request, {}) context["foo"] = "foo" self.assertEqual(template.render(context), "foo") @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "template_tests.test_context.context_process_returning_none", ], }, } ], ) def test_template_context_processor_returning_none(self): request_context = RequestContext(HttpRequest()) msg = ( "Context processor context_process_returning_none didn't return a " "dictionary." ) with self.assertRaisesMessage(TypeError, msg): with request_context.bind_template(Template("")): pass
bf8fd421a7ba2ad3374306fc8c8897d6d0fcd5ac9838ec47313289429a1cb8e4
import datetime from django.db import connection, models, transaction from django.db.models import Exists, OuterRef from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from .models import ( Award, AwardNote, Book, Child, Contact, Eaten, Email, File, Food, FooFile, FooFileProxy, FooImage, FooPhoto, House, Image, Item, Location, Login, OrderedPerson, OrgUnit, Person, Photo, PlayedWith, PlayedWithNote, Policy, Researcher, Toy, Version, ) # Can't run this test under SQLite, because you can't # get two connections to an in-memory database. @skipUnlessDBFeature("test_db_allows_multiple_connections") class DeleteLockingTest(TransactionTestCase): available_apps = ["delete_regress"] def setUp(self): # Create a second connection to the default database self.conn2 = connection.copy() self.conn2.set_autocommit(False) def tearDown(self): # Close down the second connection. self.conn2.rollback() self.conn2.close() def test_concurrent_delete(self): """Concurrent deletes don't collide and lock the database (#9479).""" with transaction.atomic(): Book.objects.create(id=1, pagecount=100) Book.objects.create(id=2, pagecount=200) Book.objects.create(id=3, pagecount=300) with transaction.atomic(): # Start a transaction on the main connection. self.assertEqual(3, Book.objects.count()) # Delete something using another database connection. with self.conn2.cursor() as cursor2: cursor2.execute("DELETE from delete_regress_book WHERE id = 1") self.conn2.commit() # In the same transaction on the main connection, perform a # queryset delete that covers the object deleted with the other # connection. This causes an infinite loop under MySQL InnoDB # unless we keep track of already deleted objects. Book.objects.filter(pagecount__lt=250).delete() self.assertEqual(1, Book.objects.count()) class DeleteCascadeTests(TestCase): def test_generic_relation_cascade(self): """ Django cascades deletes through generic-related objects to their reverse relations. """ person = Person.objects.create(name="Nelson Mandela") award = Award.objects.create(name="Nobel", content_object=person) AwardNote.objects.create(note="a peace prize", award=award) self.assertEqual(AwardNote.objects.count(), 1) person.delete() self.assertEqual(Award.objects.count(), 0) # first two asserts are just sanity checks, this is the kicker: self.assertEqual(AwardNote.objects.count(), 0) def test_fk_to_m2m_through(self): """ If an M2M relationship has an explicitly-specified through model, and some other model has an FK to that through model, deletion is cascaded from one of the participants in the M2M, to the through model, to its related model. """ juan = Child.objects.create(name="Juan") paints = Toy.objects.create(name="Paints") played = PlayedWith.objects.create( child=juan, toy=paints, date=datetime.date.today() ) PlayedWithNote.objects.create(played=played, note="the next Jackson Pollock") self.assertEqual(PlayedWithNote.objects.count(), 1) paints.delete() self.assertEqual(PlayedWith.objects.count(), 0) # first two asserts just sanity checks, this is the kicker: self.assertEqual(PlayedWithNote.objects.count(), 0) def test_15776(self): policy = Policy.objects.create(pk=1, policy_number="1234") version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create(version=version, location=location) policy.delete() class DeleteCascadeTransactionTests(TransactionTestCase): available_apps = ["delete_regress"] def test_inheritance(self): """ Auto-created many-to-many through tables referencing a parent model are correctly found by the delete cascade when a child of that parent is deleted. Refs #14896. """ r = Researcher.objects.create() email = Email.objects.create( label="office-email", email_address="[email protected]" ) r.contacts.add(email) email.delete() def test_to_field(self): """ Cascade deletion works with ForeignKey.to_field set to non-PK. """ apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") apple.delete() self.assertFalse(Food.objects.exists()) self.assertFalse(Eaten.objects.exists()) class LargeDeleteTests(TestCase): def test_large_deletes(self): """ If the number of objects > chunk size, deletion still occurs. """ for x in range(300): Book.objects.create(pagecount=x + 100) # attach a signal to make sure we will not fast-delete def noop(*args, **kwargs): pass models.signals.post_delete.connect(noop, sender=Book) Book.objects.all().delete() models.signals.post_delete.disconnect(noop, sender=Book) self.assertEqual(Book.objects.count(), 0) class ProxyDeleteTest(TestCase): """ Tests on_delete behavior for proxy models. See #16128. """ def create_image(self): """Return an Image referenced by both a FooImage and a FooFile.""" # Create an Image test_image = Image() test_image.save() foo_image = FooImage(my_image=test_image) foo_image.save() # Get the Image instance as a File test_file = File.objects.get(pk=test_image.pk) foo_file = FooFile(my_file=test_file) foo_file.save() return test_image def test_delete_proxy(self): """ Deleting the *proxy* instance bubbles through to its non-proxy and *all* referring objects are deleted. """ self.create_image() Image.objects.all().delete() # An Image deletion == File deletion self.assertEqual(len(Image.objects.all()), 0) self.assertEqual(len(File.objects.all()), 0) # The Image deletion cascaded and *all* references to it are deleted. self.assertEqual(len(FooImage.objects.all()), 0) self.assertEqual(len(FooFile.objects.all()), 0) def test_delete_proxy_of_proxy(self): """ Deleting a proxy-of-proxy instance should bubble through to its proxy and non-proxy parents, deleting *all* referring objects. """ test_image = self.create_image() # Get the Image as a Photo test_photo = Photo.objects.get(pk=test_image.pk) foo_photo = FooPhoto(my_photo=test_photo) foo_photo.save() Photo.objects.all().delete() # A Photo deletion == Image deletion == File deletion self.assertEqual(len(Photo.objects.all()), 0) self.assertEqual(len(Image.objects.all()), 0) self.assertEqual(len(File.objects.all()), 0) # The Photo deletion should have cascaded and deleted *all* # references to it. self.assertEqual(len(FooPhoto.objects.all()), 0) self.assertEqual(len(FooFile.objects.all()), 0) self.assertEqual(len(FooImage.objects.all()), 0) def test_delete_concrete_parent(self): """ Deleting an instance of a concrete model should also delete objects referencing its proxy subclass. """ self.create_image() File.objects.all().delete() # A File deletion == Image deletion self.assertEqual(len(File.objects.all()), 0) self.assertEqual(len(Image.objects.all()), 0) # The File deletion should have cascaded and deleted *all* references # to it. self.assertEqual(len(FooFile.objects.all()), 0) self.assertEqual(len(FooImage.objects.all()), 0) def test_delete_proxy_pair(self): """ If a pair of proxy models are linked by an FK from one concrete parent to the other, deleting one proxy model cascade-deletes the other, and the deletion happens in the right order (not triggering an IntegrityError on databases unable to defer integrity checks). Refs #17918. """ # Create an Image (proxy of File) and FooFileProxy (proxy of FooFile, # which has an FK to File) image = Image.objects.create() as_file = File.objects.get(pk=image.pk) FooFileProxy.objects.create(my_file=as_file) Image.objects.all().delete() self.assertEqual(len(FooFileProxy.objects.all()), 0) def test_19187_values(self): msg = "Cannot call delete() after .values() or .values_list()" with self.assertRaisesMessage(TypeError, msg): Image.objects.values().delete() with self.assertRaisesMessage(TypeError, msg): Image.objects.values_list().delete() class Ticket19102Tests(TestCase): """ Test different queries which alter the SELECT clause of the query. We also must be using a subquery for the deletion (that is, the original query has a join in it). The deletion should be done as "fast-path" deletion (that is, just one query for the .delete() call). Note that .values() is not tested here on purpose. .values().delete() doesn't work for non fast-path deletes at all. """ @classmethod def setUpTestData(cls): cls.o1 = OrgUnit.objects.create(name="o1") cls.o2 = OrgUnit.objects.create(name="o2") cls.l1 = Login.objects.create(description="l1", orgunit=cls.o1) cls.l2 = Login.objects.create(description="l2", orgunit=cls.o2) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_annotate(self): with self.assertNumQueries(1): Login.objects.order_by("description").filter( orgunit__name__isnull=False ).annotate(n=models.Count("description")).filter( n=1, pk=self.l1.pk ).delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_extra(self): with self.assertNumQueries(1): Login.objects.order_by("description").filter( orgunit__name__isnull=False ).extra(select={"extraf": "1"}).filter(pk=self.l1.pk).delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_select_related(self): with self.assertNumQueries(1): Login.objects.filter(pk=self.l1.pk).filter( orgunit__name__isnull=False ).order_by("description").select_related("orgunit").delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_defer(self): with self.assertNumQueries(1): Login.objects.filter(pk=self.l1.pk).filter( orgunit__name__isnull=False ).order_by("description").only("id").delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) class DeleteTests(TestCase): def test_meta_ordered_delete(self): # When a subquery is performed by deletion code, the subquery must be # cleared of all ordering. There was a but that caused _meta ordering # to be used. Refs #19720. h = House.objects.create(address="Foo") OrderedPerson.objects.create(name="Jack", lives_in=h) OrderedPerson.objects.create(name="Bob", lives_in=h) OrderedPerson.objects.filter(lives_in__address="Foo").delete() self.assertEqual(OrderedPerson.objects.count(), 0) def test_foreign_key_delete_nullifies_correct_columns(self): """ With a model (Researcher) that has two foreign keys pointing to the same model (Contact), deleting an instance of the target model (contact1) nullifies the correct fields of Researcher. """ contact1 = Contact.objects.create(label="Contact 1") contact2 = Contact.objects.create(label="Contact 2") researcher1 = Researcher.objects.create( primary_contact=contact1, secondary_contact=contact2, ) researcher2 = Researcher.objects.create( primary_contact=contact2, secondary_contact=contact1, ) contact1.delete() researcher1.refresh_from_db() researcher2.refresh_from_db() self.assertIsNone(researcher1.primary_contact) self.assertEqual(researcher1.secondary_contact, contact2) self.assertEqual(researcher2.primary_contact, contact2) self.assertIsNone(researcher2.secondary_contact) def test_self_reference_with_through_m2m_at_second_level(self): toy = Toy.objects.create(name="Paints") child = Child.objects.create(name="Juan") Book.objects.create(pagecount=500, owner=child) PlayedWith.objects.create(child=child, toy=toy, date=datetime.date.today()) with self.assertNumQueries(1) as ctx: Book.objects.filter( Exists( Book.objects.filter( pk=OuterRef("pk"), owner__toys=toy.pk, ), ) ).delete() self.assertIs(Book.objects.exists(), False) sql = ctx.captured_queries[0]["sql"].lower() if connection.features.delete_can_self_reference_subquery: self.assertEqual(sql.count("select"), 1) class DeleteDistinct(SimpleTestCase): def test_disallowed_delete_distinct(self): msg = "Cannot call delete() after .distinct()." with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct().delete() with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct("id").delete() class SetQueryCountTests(TestCase): def test_set_querycount(self): policy = Policy.objects.create() version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create( version=version, location=location, location_default=location, location_value=location, ) # 3 UPDATEs for SET of item values and one for DELETE locations. with self.assertNumQueries(4): location.delete()
78dc2061aac8653b718970d9c9d4de7f2afd9082eac8aaa195d6dd22482dc330
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ import copy import itertools import tempfile from unittest import mock from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse, HttpResponseNotAllowed from django.test import ( AsyncRequestFactory, Client, RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.urls import reverse_lazy from django.utils.decorators import async_only_middleware from django.views.generic import RedirectView from .views import TwoArgException, get_view, post_view, trace_view def middleware_urlconf(get_response): def middleware(request): request.urlconf = "test_client.urls_middleware_urlconf" return get_response(request) return middleware @async_only_middleware def async_middleware_urlconf(get_response): async def middleware(request): request.urlconf = "test_client.urls_middleware_urlconf" return await get_response(request) return middleware @override_settings(ROOT_URLCONF="test_client.urls") class ClientTest(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username="testclient", password="password") cls.u2 = User.objects.create_user( username="inactive", password="password", is_active=False ) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {"var": "\xf2"} response = self.client.get("/get_view/", data) # Check some response details self.assertContains(response, "This is a test") self.assertEqual(response.context["var"], "\xf2") self.assertEqual(response.templates[0].name, "GET Template") def test_copy_response(self): tests = ["/cbv_view/", "/get_view/"] for url in tests: with self.subTest(url=url): response = self.client.get(url) response_copy = copy.copy(response) self.assertEqual(repr(response), repr(response_copy)) self.assertIs(response_copy.client, response.client) self.assertIs(response_copy.resolver_match, response.resolver_match) self.assertIs(response_copy.wsgi_request, response.wsgi_request) async def test_copy_response_async(self): response = await self.async_client.get("/async_get_view/") response_copy = copy.copy(response) self.assertEqual(repr(response), repr(response_copy)) self.assertIs(response_copy.client, response.client) self.assertIs(response_copy.resolver_match, response.resolver_match) self.assertIs(response_copy.asgi_request, response.asgi_request) def test_query_string_encoding(self): # WSGI requires latin-1 encoded strings. response = self.client.get("/get_view/?var=1\ufffd") self.assertEqual(response.context["var"], "1\ufffd") def test_get_data_none(self): msg = ( "Cannot encode None for key 'value' in a query string. Did you " "mean to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.get("/get_view/", {"value": None}) def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty GET Template") self.assertTemplateUsed(response, "Empty GET Template") self.assertTemplateNotUsed(response, "Empty POST Template") def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty POST Template") self.assertTemplateNotUsed(response, "Empty GET Template") self.assertTemplateUsed(response, "Empty POST Template") def test_post(self): "POST some data to a view" post_data = {"value": 37} response = self.client.post("/post_view/", post_data) # Check some response details self.assertContains(response, "Data received") self.assertEqual(response.context["data"], "37") self.assertEqual(response.templates[0].name, "POST Template") def test_post_data_none(self): msg = ( "Cannot encode None for key 'value' as POST data. Did you mean " "to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.post("/post_view/", {"value": None}) def test_json_serialization(self): """The test client serializes JSON data.""" methods = ("post", "put", "patch", "delete") tests = ( ({"value": 37}, {"value": 37}), ([37, True], [37, True]), ((37, False), [37, False]), ) for method in methods: with self.subTest(method=method): for data, expected in tests: with self.subTest(data): client_method = getattr(self.client, method) method_name = method.upper() response = client_method( "/json_view/", data, content_type="application/json" ) self.assertContains(response, "Viewing %s page." % method_name) self.assertEqual(response.context["data"], expected) def test_json_encoder_argument(self): """The test Client accepts a json_encoder.""" mock_encoder = mock.MagicMock() mock_encoding = mock.MagicMock() mock_encoder.return_value = mock_encoding mock_encoding.encode.return_value = '{"value": 37}' client = self.client_class(json_encoder=mock_encoder) # Vendored tree JSON content types are accepted. client.post( "/json_view/", {"value": 37}, content_type="application/vnd.api+json" ) self.assertTrue(mock_encoder.called) self.assertTrue(mock_encoding.encode.called) def test_put(self): response = self.client.put("/put_view/", {"foo": "bar"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "PUT Template") self.assertEqual(response.context["data"], "{'foo': 'bar'}") self.assertEqual(response.context["Content-Length"], "14") def test_trace(self): """TRACE a view""" response = self.client.trace("/trace_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["method"], "TRACE") self.assertEqual(response.templates[0].name, "TRACE Template") def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/header_view/") self.assertEqual(response.headers["X-DJANGO-TEST"], "Slartibartfast") def test_response_attached_request(self): """ The returned response has a ``request`` attribute with the originating environ dict and a ``wsgi_request`` with the originating WSGIRequest. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "request")) self.assertTrue(hasattr(response, "wsgi_request")) for key, value in response.request.items(): self.assertIn(key, response.wsgi_request.environ) self.assertEqual(response.wsgi_request.environ[key], value) def test_response_resolver_match(self): """ The response contains a ResolverMatch instance. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "resolver_match")) def test_response_resolver_match_redirect_follow(self): """ The response ResolverMatch instance contains the correct information when following redirects. """ response = self.client.get("/redirect_view/", follow=True) self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_regular_view(self): """ The response ResolverMatch instance contains the correct information when accessing a regular view. """ response = self.client.get("/get_view/") self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_class_based_view(self): """ The response ResolverMatch instance can be used to access the CBV view class. """ response = self.client.get("/accounts/") self.assertIs(response.resolver_match.func.view_class, RedirectView) @modify_settings(MIDDLEWARE={"prepend": "test_client.tests.middleware_urlconf"}) def test_response_resolver_match_middleware_urlconf(self): response = self.client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?> <library><book><title>Blink</title><author>Malcolm Gladwell</author></book> </library> """ response = self.client.post( "/raw_post_view/", test_doc, content_type="text/xml" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_insecure(self): "GET a URL through http" response = self.client.get("/secure_view/", secure=False) self.assertFalse(response.test_was_secure_request) self.assertEqual(response.test_server_port, "80") def test_secure(self): "GET a URL through https" response = self.client.get("/secure_view/", secure=True) self.assertTrue(response.test_was_secure_request) self.assertEqual(response.test_server_port, "443") def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get("/redirect_view/") self.assertRedirects(response, "/get_view/") def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get("/redirect_view/", {"var": "value"}) self.assertRedirects(response, "/get_view/?var=value") def test_redirect_with_query_ordering(self): """assertRedirects() ignores the order of query string parameters.""" response = self.client.get("/redirect_view/", {"var": "value", "foo": "bar"}) self.assertRedirects(response, "/get_view/?var=value&foo=bar") self.assertRedirects(response, "/get_view/?foo=bar&var=value") def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get("/permanent_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get("/temporary_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get("/double_redirect_view/") # The response was a 302, and that the attempt to get the redirection # location returned 301 when retrieved self.assertRedirects( response, "/permanent_redirect_view/", target_status_code=301 ) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get("/double_redirect_view/", follow=True) self.assertRedirects( response, "/get_view/", status_code=302, target_status_code=200 ) self.assertEqual(len(response.redirect_chain), 2) def test_follow_relative_redirect(self): "A URL with a relative redirect can be followed." response = self.client.get("/accounts/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_follow_relative_redirect_no_trailing_slash(self): "A URL with a relative redirect with no trailing slash can be followed." response = self.client.get("/accounts/no_trailing_slash", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_redirect_to_querystring_only(self): """A URL that consists of a querystring only can be followed""" response = self.client.post("/post_then_get_view/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_then_get_view/") self.assertEqual(response.content, b"The value of success is true.") def test_follow_307_and_308_redirect(self): """ A 307 or 308 redirect preserves the request method after the redirect. """ methods = ("get", "post", "head", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_view/") self.assertEqual(response.request["REQUEST_METHOD"], method.upper()) def test_follow_307_and_308_preserves_query_string(self): methods = ("post", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "hello=world") def test_follow_307_and_308_get_head_query_string(self): methods = ("get", "head") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "value=test") def test_follow_307_and_308_preserves_post_data(self): for code in (307, 308): with self.subTest(code=code): response = self.client.post( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertContains(response, "test is the value") def test_follow_307_and_308_preserves_put_body(self): for code in (307, 308): with self.subTest(code=code): response = self.client.put( "/redirect_view_%s/?to=/put_view/" % code, data="a=b", follow=True ) self.assertContains(response, "a=b is the body") def test_follow_307_and_308_preserves_get_params(self): data = {"var": 30, "to": "/get_view/"} for code in (307, 308): with self.subTest(code=code): response = self.client.get( "/redirect_view_%s/" % code, data=data, follow=True ) self.assertContains(response, "30 is the value") def test_redirect_http(self): """GET a URL that redirects to an HTTP URI.""" response = self.client.get("/http_redirect_view/", follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): """GET a URL that redirects to an HTTPS URI.""" response = self.client.get("/https_redirect_view/", follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get("/bad_view/") self.assertContains(response, "MAGIC", status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = {"text": "Hello World", "multi": ("b", "c", "e")} response = self.client.get("/form_view/", data=hints) # The multi-value data has been rolled out ok self.assertContains(response, "Select a valid choice.", 0) self.assertTemplateUsed(response, "Form GET Template") def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view/", post_data) self.assertContains(response, "This field is required.", 3) self.assertTemplateUsed(response, "Invalid POST Template") form = response.context["form"] self.assertFormError(form, "email", "This field is required.") self.assertFormError(form, "single", "This field is required.") self.assertFormError(form, "multi", "This field is required.") def test_form_error(self): "POST erroneous data to a form" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError( response.context["form"], "email", "Enter a valid email address." ) def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data OK") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") form = response.context["form"] self.assertFormError(form, "email", "This field is required.") self.assertFormError(form, "single", "This field is required.") self.assertFormError(form, "multi", "This field is required.") def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError( response.context["form"], "email", "Enter a valid email address." ) def test_unknown_page(self): "GET an invalid URL" response = self.client.get("/unknown_view/") # The response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get("/unknown_view/;some-parameter") # The path in the response includes it (ignore that it's a 404) self.assertEqual(response.request["PATH_INFO"], "/unknown_view/;some-parameter") def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( INSTALLED_APPS=["django.contrib.auth"], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_view_with_login_when_sessions_app_is_not_installed(self): self.test_view_with_login() def test_view_with_force_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_force_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_force_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username="otheruser", password="nopassword") self.assertFalse(login) def test_view_with_inactive_login(self): """ An inactive user may login if the authenticate backend allows it. """ credentials = {"username": "inactive", "password": "password"} self.assertFalse(self.client.login(**credentials)) with self.settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.AllowAllUsersModelBackend" ] ): self.assertTrue(self.client.login(**credentials)) @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "django.contrib.auth.backends.AllowAllUsersModelBackend", ] ) def test_view_with_inactive_force_login(self): "Request a page that is protected with @login, but use an inactive login" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u2, backend="django.contrib.auth.backends.AllowAllUsersModelBackend" ) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "inactive") def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username="testclient", password="password") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") def test_logout_with_force_login(self): "Request a logout after logging in" # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_with_backend(self): """ Request a page that is protected with @login_required when using force_login() and passing a backend. """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u1, backend="test_client.auth_backends.TestClientBackend" ) self.assertEqual(self.u1.backend, "test_client.auth_backends.TestClientBackend") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_without_backend(self): """ force_login() without passing a backend and with multiple backends configured should automatically use the first backend. """ self.client.force_login(self.u1) response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings( AUTHENTICATION_BACKENDS=[ "test_client.auth_backends.BackendWithoutGetUserMethod", "django.contrib.auth.backends.ModelBackend", ] ) def test_force_login_with_backend_missing_get_user(self): """ force_login() skips auth backends without a get_user() method. """ self.client.force_login(self.u1) self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout() def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): """ Request a page that is protected with @permission_required but raises an exception. """ # Get the page without logging in. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # TODO: Log in with right permissions and request the page again def test_external_redirect(self): response = self.client.get("/django_project_redirect/") self.assertRedirects( response, "https://www.djangoproject.com/", fetch_redirect_response=False ) def test_external_redirect_without_trailing_slash(self): """ Client._handle_redirects() with an empty path. """ response = self.client.get("/no_trailing_slash_external_redirect/", follow=True) self.assertRedirects(response, "https://testserver") def test_external_redirect_with_fetch_error_msg(self): """ assertRedirects without fetch_redirect_response=False raises a relevant ValueError rather than a non-descript AssertionError. """ response = self.client.get("/django_project_redirect/") msg = ( "The test client is unable to fetch remote URLs (got " "https://www.djangoproject.com/). If the host is served by Django, " "add 'www.djangoproject.com' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." ) with self.assertRaisesMessage(ValueError, msg): self.assertRedirects(response, "https://www.djangoproject.com/") def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially with self.assertRaises(KeyError): self.client.session["tobacconist"] self.client.post("/session_view/") # The session was modified self.assertEqual(self.client.session["tobacconist"], "hovercraft") @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_sessions_app_is_not_installed(self): self.test_session_modifying_view() @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.nonexistent", ) def test_session_engine_is_invalid(self): with self.assertRaisesMessage(ImportError, "nonexistent"): self.test_session_modifying_view() def test_view_with_exception(self): "Request a page that is known to throw an error" with self.assertRaises(KeyError): self.client.get("/broken_view/") def test_exc_info(self): client = Client(raise_request_exception=False) response = client.get("/broken_view/") self.assertEqual(response.status_code, 500) exc_type, exc_value, exc_traceback = response.exc_info self.assertIs(exc_type, KeyError) self.assertIsInstance(exc_value, KeyError) self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") self.assertIsNotNone(exc_traceback) def test_exc_info_none(self): response = self.client.get("/get_view/") self.assertIsNone(response.exc_info) def test_mail_sending(self): "Mail is redirected to a dummy outbox during test setup" response = self.client.get("/mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test message") self.assertEqual(mail.outbox[0].body, "This is a test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") def test_reverse_lazy_decodes(self): "reverse_lazy() works in the test client" data = {"var": "data"} response = self.client.get(reverse_lazy("get_view"), data) # Check some response details self.assertContains(response, "This is a test") def test_relative_redirect(self): response = self.client.get("/accounts/") self.assertRedirects(response, "/accounts/login/") def test_relative_redirect_no_trailing_slash(self): response = self.client.get("/accounts/no_trailing_slash") self.assertRedirects(response, "/accounts/login/") def test_mass_mail_sending(self): "Mass mail is redirected to a dummy outbox during test setup" response = self.client.get("/mass_mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "First Test message") self.assertEqual(mail.outbox[0].body, "This is the first test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") self.assertEqual(mail.outbox[1].subject, "Second Test message") self.assertEqual(mail.outbox[1].body, "This is the second test email") self.assertEqual(mail.outbox[1].from_email, "[email protected]") self.assertEqual(mail.outbox[1].to[0], "[email protected]") self.assertEqual(mail.outbox[1].to[1], "[email protected]") def test_exception_following_nested_client_request(self): """ A nested test client request shouldn't clobber exception signals from the outer client request. """ with self.assertRaisesMessage(Exception, "exception message"): self.client.get("/nesting_exception_view/") def test_response_raises_multi_arg_exception(self): """A request may raise an exception with more than one required arg.""" with self.assertRaises(TwoArgException) as cm: self.client.get("/two_arg_exception/") self.assertEqual(cm.exception.args, ("one", "two")) def test_uploading_temp_file(self): with tempfile.TemporaryFile() as test_file: response = self.client.post("/upload_view/", data={"temp_file": test_file}) self.assertEqual(response.content, b"temp_file") def test_uploading_named_temp_file(self): with tempfile.NamedTemporaryFile() as test_file: response = self.client.post( "/upload_view/", data={"named_temp_file": test_file}, ) self.assertEqual(response.content, b"named_temp_file") @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], ROOT_URLCONF="test_client.urls", ) class CSRFEnabledClientTests(SimpleTestCase): def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post("/post_view/", {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post("/post_view/", {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(SimpleTestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertIs(hasattr(self.client, "i_am_customized"), True) def _generic_view(request): return HttpResponse(status=200) @override_settings(ROOT_URLCONF="test_client.urls") class RequestFactoryTest(SimpleTestCase): """Tests for the request factory.""" # A mapping between names of HTTP/1.1 methods and their test views. http_methods_and_views = ( ("get", get_view), ("post", post_view), ("put", _generic_view), ("patch", _generic_view), ("delete", _generic_view), ("head", _generic_view), ("options", _generic_view), ("trace", trace_view), ) request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = view(request) self.assertEqual(response.status_code, 200) def test_get_request_from_factory(self): """ The request factory returns a templated response for a GET request. """ request = self.request_factory.get("/somewhere/") response = get_view(request) self.assertContains(response, "This is a test") def test_trace_request_from_factory(self): """The request factory returns an echo response for a TRACE request.""" url_path = "/somewhere/" request = self.request_factory.trace(url_path) response = trace_view(request) protocol = request.META["SERVER_PROTOCOL"] echoed_request_line = "TRACE {} {}".format(url_path, protocol) self.assertContains(response, echoed_request_line) def test_request_factory_default_headers(self): request = RequestFactory( headers={ "authorization": "Bearer faketoken", "x-another-header": "some other value", } ).get("/somewhere/") self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) request = RequestFactory( headers={ "Authorization": "Bearer faketoken", "X-Another-Header": "some other value", } ).get("/somewhere/") self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) def test_request_factory_sets_headers(self): for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method( "/somewhere/", headers={ "authorization": "Bearer faketoken", "x-another-header": "some other value", }, ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) request = method( "/somewhere/", headers={ "Authorization": "Bearer faketoken", "X-Another-Header": "some other value", }, ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) @override_settings(ROOT_URLCONF="test_client.urls") class AsyncClientTest(TestCase): async def test_response_resolver_match(self): response = await self.async_client.get("/async_get_view/") self.assertTrue(hasattr(response, "resolver_match")) self.assertEqual(response.resolver_match.url_name, "async_get_view") @modify_settings( MIDDLEWARE={"prepend": "test_client.tests.async_middleware_urlconf"}, ) async def test_response_resolver_match_middleware_urlconf(self): response = await self.async_client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") async def test_follow_parameter_not_implemented(self): msg = "AsyncClient request methods do not accept the follow parameter." tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): method = getattr(self.async_client, method_name) with self.assertRaisesMessage(NotImplementedError, msg): await method("/redirect_view/", follow=True) async def test_get_data(self): response = await self.async_client.get("/get_view/", {"var": "val"}) self.assertContains(response, "This is a test. val is the value.") async def test_post_data(self): response = await self.async_client.post("/post_view/", {"value": 37}) self.assertContains(response, "Data received: 37 is the value.") async def test_body_read_on_get_data(self): response = await self.async_client.get("/post_view/") self.assertContains(response, "Viewing GET page.") @override_settings(ROOT_URLCONF="test_client.urls") class AsyncRequestFactoryTest(SimpleTestCase): request_factory = AsyncRequestFactory() async def test_request_factory(self): tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): async def async_generic_view(request): if request.method.lower() != method_name: return HttpResponseNotAllowed(method_name) return HttpResponse(status=200) method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) async def test_request_factory_data(self): async def async_generic_view(request): return HttpResponse(status=200, content=request.body) request = self.request_factory.post( "/somewhere/", data={"example": "data"}, content_type="application/json", ) self.assertEqual(request.headers["content-length"], "19") self.assertEqual(request.headers["content-type"], "application/json") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'{"example": "data"}') async def test_request_limited_read(self): tests = ["GET", "POST"] for method in tests: with self.subTest(method=method): request = self.request_factory.generic( method, "/somewhere", ) self.assertEqual(request.read(200), b"") def test_request_factory_sets_headers(self): request = self.request_factory.get( "/somewhere/", AUTHORIZATION="Bearer faketoken", X_ANOTHER_HEADER="some other value", ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) request = self.request_factory.get( "/somewhere/", headers={ "Authorization": "Bearer faketoken", "X-Another-Header": "some other value", }, ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) def test_request_factory_query_string(self): request = self.request_factory.get("/somewhere/", {"example": "data"}) self.assertNotIn("Query-String", request.headers) self.assertEqual(request.GET["example"], "data")
b8de9da89ba97ce74c42dc19ed24bfef4a35e448f32bd34258f240b23b3ff341
from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name from django.core.signals import request_finished, request_started from django.db import close_old_connections, connection from django.test import ( AsyncRequestFactory, RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) class HandlerTests(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_middleware_initialized(self): handler = WSGIHandler() self.assertIsNotNone(handler._middleware_chain) def test_bad_path_info(self): """ A non-UTF-8 path populates PATH_INFO with an URL-encoded path and produces a 404. """ environ = self.request_factory.get("/").environ environ["PATH_INFO"] = "\xed" handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # The path of the request will be encoded to '/%ED'. self.assertEqual(response.status_code, 404) def test_non_ascii_query_string(self): """ Non-ASCII query strings are properly decoded (#20530, #22996). """ environ = self.request_factory.get("/").environ raw_query_strings = [ b"want=caf%C3%A9", # This is the proper way to encode 'café' b"want=caf\xc3\xa9", # UA forgot to quote bytes b"want=caf%E9", # UA quoted, but not in UTF-8 # UA forgot to convert Latin-1 to UTF-8 and to quote (typical of # MSIE). b"want=caf\xe9", ] got = [] for raw_query_string in raw_query_strings: # Simulate http.server.BaseHTTPRequestHandler.parse_request # handling of raw request. environ["QUERY_STRING"] = str(raw_query_string, "iso-8859-1") request = WSGIRequest(environ) got.append(request.GET["want"]) # %E9 is converted to the Unicode replacement character by parse_qsl self.assertEqual(got, ["café", "café", "caf\ufffd", "café"]) def test_non_ascii_cookie(self): """Non-ASCII cookies set in JavaScript are properly decoded (#20557).""" environ = self.request_factory.get("/").environ raw_cookie = 'want="café"'.encode("utf-8").decode("iso-8859-1") environ["HTTP_COOKIE"] = raw_cookie request = WSGIRequest(environ) self.assertEqual(request.COOKIES["want"], "café") def test_invalid_unicode_cookie(self): """ Invalid cookie content should result in an absent cookie, but not in a crash while trying to decode it (#23638). """ environ = self.request_factory.get("/").environ environ["HTTP_COOKIE"] = "x=W\x03c(h]\x8e" request = WSGIRequest(environ) # We don't test COOKIES content, as the result might differ between # Python version because parsing invalid content became stricter in # latest versions. self.assertIsInstance(request.COOKIES, dict) @override_settings(ROOT_URLCONF="handlers.urls") def test_invalid_multipart_boundary(self): """ Invalid boundary string should produce a "Bad Request" response, not a server error (#23887). """ environ = self.request_factory.post("/malformed_post/").environ environ["CONTENT_TYPE"] = "multipart/form-data; boundary=WRONG\x07" handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # Expect "bad request" response self.assertEqual(response.status_code, 400) @override_settings(ROOT_URLCONF="handlers.urls", MIDDLEWARE=[]) class TransactionsPerRequestTests(TransactionTestCase): available_apps = [] def test_no_transaction(self): response = self.client.get("/in_transaction/") self.assertContains(response, "False") def test_auto_transaction(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/in_transaction/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests self.assertContains(response, "True") async def test_auto_transaction_async_view(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True msg = "You cannot use ATOMIC_REQUESTS with async views." with self.assertRaisesMessage(RuntimeError, msg): await self.async_client.get("/async_regular/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests def test_no_auto_transaction(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/not_in_transaction/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests self.assertContains(response, "False") try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/not_in_transaction_using_none/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests self.assertContains(response, "False") try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/not_in_transaction_using_text/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests # The non_atomic_requests decorator is used for an incorrect table. self.assertContains(response, "True") @override_settings(ROOT_URLCONF="handlers.urls") class SignalsTests(SimpleTestCase): def setUp(self): self.signals = [] self.signaled_environ = None request_started.connect(self.register_started) request_finished.connect(self.register_finished) def tearDown(self): request_started.disconnect(self.register_started) request_finished.disconnect(self.register_finished) def register_started(self, **kwargs): self.signals.append("started") self.signaled_environ = kwargs.get("environ") def register_finished(self, **kwargs): self.signals.append("finished") def test_request_signals(self): response = self.client.get("/regular/") self.assertEqual(self.signals, ["started", "finished"]) self.assertEqual(response.content, b"regular content") self.assertEqual(self.signaled_environ, response.wsgi_request.environ) def test_request_signals_streaming_response(self): response = self.client.get("/streaming/") self.assertEqual(self.signals, ["started"]) self.assertEqual(b"".join(list(response)), b"streaming content") self.assertEqual(self.signals, ["started", "finished"]) def empty_middleware(get_response): pass @override_settings(ROOT_URLCONF="handlers.urls") class HandlerRequestTests(SimpleTestCase): request_factory = RequestFactory() def test_async_view(self): """Calling an async view down the normal synchronous path.""" response = self.client.get("/async_regular/") self.assertEqual(response.status_code, 200) def test_suspiciousop_in_view_returns_400(self): response = self.client.get("/suspicious/") self.assertEqual(response.status_code, 400) def test_bad_request_in_view_returns_400(self): response = self.client.get("/bad_request/") self.assertEqual(response.status_code, 400) def test_invalid_urls(self): response = self.client.get("~%A9helloworld") self.assertEqual(response.status_code, 404) self.assertEqual(response.context["request_path"], "/~%25A9helloworld") response = self.client.get("d%aao%aaw%aan%aal%aao%aaa%aad%aa/") self.assertEqual( response.context["request_path"], "/d%25AAo%25AAw%25AAn%25AAl%25AAo%25AAa%25AAd%25AA", ) response = self.client.get("/%E2%99%E2%99%A5/") self.assertEqual(response.context["request_path"], "/%25E2%2599%E2%99%A5/") response = self.client.get("/%E2%98%8E%E2%A9%E2%99%A5/") self.assertEqual( response.context["request_path"], "/%E2%98%8E%25E2%25A9%E2%99%A5/" ) def test_environ_path_info_type(self): environ = self.request_factory.get("/%E2%A8%87%87%A5%E2%A8%A0").environ self.assertIsInstance(environ["PATH_INFO"], str) def test_handle_accepts_httpstatus_enum_value(self): def start_response(status, headers): start_response.status = status environ = self.request_factory.get("/httpstatus_enum/").environ WSGIHandler()(environ, start_response) self.assertEqual(start_response.status, "200 OK") @override_settings(MIDDLEWARE=["handlers.tests.empty_middleware"]) def test_middleware_returns_none(self): msg = "Middleware factory handlers.tests.empty_middleware returned None." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/") def test_no_response(self): msg = ( "The view %s didn't return an HttpResponse object. It returned None " "instead." ) tests = ( ("/no_response_fbv/", "handlers.views.no_response"), ("/no_response_cbv/", "handlers.views.NoResponse.__call__"), ) for url, view in tests: with self.subTest(url=url), self.assertRaisesMessage( ValueError, msg % view ): self.client.get(url) def test_streaming(self): response = self.client.get("/streaming/") self.assertEqual(response.status_code, 200) self.assertEqual(b"".join(list(response)), b"streaming content") def test_async_streaming(self): response = self.client.get("/async_streaming/") self.assertEqual(response.status_code, 200) msg = ( "StreamingHttpResponse must consume asynchronous iterators in order to " "serve them synchronously. Use a synchronous iterator instead." ) with self.assertWarnsMessage(Warning, msg): self.assertEqual(b"".join(list(response)), b"streaming content") class ScriptNameTests(SimpleTestCase): def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({"SCRIPT_URL": "/foobar/"}) self.assertEqual(script_name, "/foobar/") script_name = get_script_name({"SCRIPT_URL": "/foobar/", "PATH_INFO": "/"}) self.assertEqual(script_name, "/foobar") def test_get_script_name_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, get_script_name should take that into account when forming SCRIPT_NAME (#17133). """ script_name = get_script_name( { "SCRIPT_URL": "/mst/milestones//accounts/login//help", "PATH_INFO": "/milestones/accounts/login/help", } ) self.assertEqual(script_name, "/mst") @override_settings(ROOT_URLCONF="handlers.urls") class AsyncHandlerRequestTests(SimpleTestCase): """Async variants of the normal handler request tests.""" async def test_sync_view(self): """Calling a sync view down the asynchronous path.""" response = await self.async_client.get("/regular/") self.assertEqual(response.status_code, 200) async def test_async_view(self): """Calling an async view down the asynchronous path.""" response = await self.async_client.get("/async_regular/") self.assertEqual(response.status_code, 200) async def test_suspiciousop_in_view_returns_400(self): response = await self.async_client.get("/suspicious/") self.assertEqual(response.status_code, 400) async def test_bad_request_in_view_returns_400(self): response = await self.async_client.get("/bad_request/") self.assertEqual(response.status_code, 400) async def test_no_response(self): msg = ( "The view handlers.views.no_response didn't return an " "HttpResponse object. It returned None instead." ) with self.assertRaisesMessage(ValueError, msg): await self.async_client.get("/no_response_fbv/") async def test_unawaited_response(self): msg = ( "The view handlers.views.CoroutineClearingView.__call__ didn't" " return an HttpResponse object. It returned an unawaited" " coroutine instead. You may need to add an 'await'" " into your view." ) with self.assertRaisesMessage(ValueError, msg): await self.async_client.get("/unawaited/") @override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/") def test_force_script_name(self): async_request_factory = AsyncRequestFactory() request = async_request_factory.request(**{"path": "/somepath/"}) self.assertEqual(request.path, "/FORCED_PREFIX/somepath/") async def test_sync_streaming(self): response = await self.async_client.get("/streaming/") self.assertEqual(response.status_code, 200) msg = ( "StreamingHttpResponse must consume synchronous iterators in order to " "serve them asynchronously. Use an asynchronous iterator instead." ) with self.assertWarnsMessage(Warning, msg): self.assertEqual( b"".join([chunk async for chunk in response]), b"streaming content" ) async def test_async_streaming(self): response = await self.async_client.get("/async_streaming/") self.assertEqual(response.status_code, 200) self.assertEqual( b"".join([chunk async for chunk in response]), b"streaming content" )
85a97861fb18c0695c00d091654f1a14e61b19f93b5f41c7790abbff47949caa
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.exceptions import FieldError from django.core.management.color import no_style from django.db import ( DatabaseError, DataError, IntegrityError, OperationalError, connection, ) from django.db.backends.utils import truncate_name from django.db.models import ( CASCADE, PROTECT, AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, CheckConstraint, DateField, DateTimeField, DecimalField, DurationField, F, FloatField, ForeignKey, ForeignObject, Index, IntegerField, JSONField, ManyToManyField, Model, OneToOneField, OrderBy, PositiveIntegerField, Q, SlugField, SmallAutoField, SmallIntegerField, TextField, TimeField, UniqueConstraint, UUIDField, Value, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Upper from django.db.models.indexes import IndexExpression from django.db.transaction import TransactionManagementError, atomic from django.test import ( TransactionTestCase, ignore_warnings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup from django.utils.deprecation import RemovedInDjango51Warning from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField from .models import ( Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName, AuthorWithUniqueName, AuthorWithUniqueNameAndBirthday, Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps, ) class SchemaTests(TransactionTestCase): """ Tests for the schema-alteration code. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note, Tag, TagM2MTest, TagUniqueRename, Thing, UniqueTest, ] # Utility functions def setUp(self): # local_models should contain test dependent model classes that will be # automatically removed from the app cache on test tear down. self.local_models = [] # isolated_local_models contains models that are in test methods # decorated with @isolate_apps. self.isolated_local_models = [] def tearDown(self): # Delete any tables made for our models self.delete_tables() new_apps.clear_cache() for model in new_apps.get_models(): model._meta._expire_cache() if "schema" in new_apps.all_models: for model in self.local_models: for many_to_many in model._meta.many_to_many: through = many_to_many.remote_field.through if through and through._meta.auto_created: del new_apps.all_models["schema"][through._meta.model_name] del new_apps.all_models["schema"][model._meta.model_name] if self.isolated_local_models: with connection.schema_editor() as editor: for model in self.isolated_local_models: editor.delete_model(model) def delete_tables(self): "Deletes all model tables for our models for a clean test environment" converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: connection.disable_constraint_checking() table_names = connection.introspection.table_names() if connection.features.ignores_table_name_case: table_names = [table_name.lower() for table_name in table_names] for model in itertools.chain(SchemaTests.models, self.local_models): tbl = converter(model._meta.db_table) if connection.features.ignores_table_name_case: tbl = tbl.lower() if tbl in table_names: editor.delete_model(model) table_names.remove(tbl) connection.enable_constraint_checking() def column_classes(self, model): with connection.cursor() as cursor: columns = { d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple): columns[name] = (type[0], desc) return columns def get_primary_key(self, table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_column(cursor, table) def get_indexes(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["index"] and len(c["columns"]) == 1 ] def get_uniques(self, table): with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["unique"] and len(c["columns"]) == 1 ] def get_constraints(self, table): """ Get the constraints on a table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def get_constraints_for_column(self, model, column_name): constraints = self.get_constraints(model._meta.db_table) constraints_for_column = [] for name, details in constraints.items(): if details["columns"] == [column_name]: constraints_for_column.append(name) return sorted(constraints_for_column) def check_added_field_default( self, schema_editor, model, field, field_name, expected_default, cast_function=None, ): with connection.cursor() as cursor: schema_editor.add_field(model, field) cursor.execute( "SELECT {} FROM {};".format(field_name, model._meta.db_table) ) database_default = cursor.fetchall()[0][0] if cast_function and type(database_default) != type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) def get_constraints_count(self, table, column, fk_to): """ Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the number of foreign keys, unique constraints, and indexes on `table`.`column`. The `fk_to` argument is a 2-tuple specifying the expected foreign key relationship's (table, column). """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) counts = {"fks": 0, "uniques": 0, "indexes": 0} for c in constraints.values(): if c["columns"] == [column]: if c["foreign_key"] == fk_to: counts["fks"] += 1 if c["unique"]: counts["uniques"] += 1 elif c["index"]: counts["indexes"] += 1 return counts def get_column_collation(self, table, column): with connection.cursor() as cursor: return next( f.collation for f in connection.introspection.get_table_description(cursor, table) if f.name == column ) def get_column_comment(self, table, column): with connection.cursor() as cursor: return next( f.comment for f in connection.introspection.get_table_description(cursor, table) if f.name == column ) def get_table_comment(self, table): with connection.cursor() as cursor: return next( t.comment for t in connection.introspection.get_table_list(cursor) if t.name == table ) def assert_column_comment_not_exists(self, table, column): with connection.cursor() as cursor: columns = connection.introspection.get_table_description(cursor, table) self.assertFalse(any([c.name == column and c.comment for c in columns])) def assertIndexOrder(self, table, index, order): constraints = self.get_constraints(table) self.assertIn(index, constraints) index_orders = constraints[index]["orders"] self.assertTrue( all(val == expected for val, expected in zip(index_orders, order)) ) def assertForeignKeyExists(self, model, column, expected_fk_table, field="id"): """ Fail if the FK constraint on `model.Meta.db_table`.`column` to `expected_fk_table`.id doesn't exist. """ if not connection.features.can_introspect_foreign_keys: return constraints = self.get_constraints(model._meta.db_table) constraint_fk = None for details in constraints.values(): if details["columns"] == [column] and details["foreign_key"]: constraint_fk = details["foreign_key"] break self.assertEqual(constraint_fk, (expected_fk_table, field)) def assertForeignKeyNotExists(self, model, column, expected_fk_table): if not connection.features.can_introspect_foreign_keys: return with self.assertRaises(AssertionError): self.assertForeignKeyExists(model, column, expected_fk_table) # Tests def test_creation_deletion(self): """ Tries creating a model's table, and then deleting it. """ with connection.schema_editor() as editor: # Create the table editor.create_model(Author) # The table is there list(Author.objects.all()) # Clean up that table editor.delete_model(Author) # No deferred SQL should be left over. self.assertEqual(editor.deferred_sql, []) # The table is gone with self.assertRaises(DatabaseError): list(Author.objects.all()) @skipUnlessDBFeature("supports_foreign_keys") def test_fk(self): "Creating tables out of FK order, then repointing, works" # Create the table with connection.schema_editor() as editor: editor.create_model(Book) editor.create_model(Author) editor.create_model(Tag) # Initial tables are there list(Author.objects.all()) list(Book.objects.all()) # Make sure the FK constraint is present with self.assertRaises(IntegrityError): Book.objects.create( author_id=1, title="Much Ado About Foreign Keys", pub_date=datetime.datetime.now(), ) # Repoint the FK constraint old_field = Book._meta.get_field("author") new_field = ForeignKey(Tag, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertForeignKeyExists(Book, "author_id", "schema_tag") @skipUnlessDBFeature("can_create_inline_fk") def test_inline_fk(self): # Create some tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.create_model(Note) self.assertForeignKeyNotExists(Note, "book_id", "schema_book") # Add a foreign key from one to the other. with connection.schema_editor() as editor: new_field = ForeignKey(Book, CASCADE) new_field.set_attributes_from_name("book") editor.add_field(Note, new_field) self.assertForeignKeyExists(Note, "book_id", "schema_book") # Creating a FK field with a constraint uses a single statement without # a deferred ALTER TABLE. self.assertFalse( [ sql for sql in (str(statement) for statement in editor.deferred_sql) if sql.startswith("ALTER TABLE") and "ADD CONSTRAINT" in sql ] ) @skipUnlessDBFeature("can_create_inline_fk") def test_add_inline_fk_update_data(self): with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key and update data in the same transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) assertIndex = ( self.assertIn if connection.features.indexes_foreign_keys else self.assertNotIn ) assertIndex("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature( "can_create_inline_fk", "allows_multiple_constraints_on_same_fields", ) @isolate_apps("schema") def test_add_inline_fk_index_update_data(self): class Node(Model): class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key, update data, and an index in the same # transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) Node._meta.add_field(new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) editor.add_index( Node, Index(fields=["new_parent_fk"], name="new_parent_inline_fk_idx") ) self.assertIn("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature("supports_foreign_keys") def test_char_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorCharFieldWithIndex) # Change CharField to FK old_field = AuthorCharFieldWithIndex._meta.get_field("char_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("char_field") with connection.schema_editor() as editor: editor.alter_field( AuthorCharFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorCharFieldWithIndex, "char_field_id", "schema_author" ) @skipUnlessDBFeature("supports_foreign_keys") @skipUnlessDBFeature("supports_index_on_text_field") def test_text_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorTextFieldWithIndex) # Change TextField to FK old_field = AuthorTextFieldWithIndex._meta.get_field("text_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("text_field") with connection.schema_editor() as editor: editor.alter_field( AuthorTextFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorTextFieldWithIndex, "text_field_id", "schema_author" ) @isolate_apps("schema") def test_char_field_pk_to_auto_field(self): class Foo(Model): id = CharField(max_length=255, primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @skipUnlessDBFeature("supports_foreign_keys") def test_fk_to_proxy(self): "Creating a FK to a proxy model creates database constraints." class AuthorProxy(Author): class Meta: app_label = "schema" apps = new_apps proxy = True class AuthorRef(Model): author = ForeignKey(AuthorProxy, on_delete=CASCADE) class Meta: app_label = "schema" apps = new_apps self.local_models = [AuthorProxy, AuthorRef] # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorRef) self.assertForeignKeyExists(AuthorRef, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_fk_db_constraint(self): "The db_constraint parameter is respected" # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) editor.create_model(BookWeak) # Initial tables are there list(Author.objects.all()) list(Tag.objects.all()) list(BookWeak.objects.all()) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") # Make a db_constraint=False FK new_field = ForeignKey(Tag, CASCADE, db_constraint=False) new_field.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.add_field(Author, new_field) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") # Alter to one with a constraint new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) self.assertForeignKeyExists(Author, "tag_id", "schema_tag") # Alter to one without a constraint again new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field2, new_field, strict=True) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") @isolate_apps("schema") def test_no_db_constraint_added_during_primary_key_change(self): """ When a primary key that's pointed to by a ForeignKey with db_constraint=False is altered, a foreign key constraint isn't added. """ class Author(Model): class Meta: app_label = "schema" class BookWeak(Model): author = ForeignKey(Author, CASCADE, db_constraint=False) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWeak) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Author new_field.set_attributes_from_name("id") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") def _test_m2m_db_constraint(self, M2MFieldClass): class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(LocalAuthorWithM2M) # Initial tables are there list(LocalAuthorWithM2M.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False) new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) self.assertForeignKeyNotExists( new_field.remote_field.through, "tag_id", "schema_tag" ) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint(self): self._test_m2m_db_constraint(ManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_custom(self): self._test_m2m_db_constraint(CustomManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_inherited(self): self._test_m2m_db_constraint(InheritedManyToManyField) def test_add_field(self): """ Tests adding fields to models """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") with CaptureQueriesContext( connection ) as ctx, connection.schema_editor() as editor: editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { "column": editor.quote_name(new_field.name), } self.assertFalse( any(drop_default_sql in query["sql"] for query in ctx.captured_queries) ) # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False ) columns = self.column_classes(Author) self.assertEqual( columns["age"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertTrue(columns["age"][1][6]) def test_add_field_remove_field(self): """ Adding a field and removing it removes all deferred sql referring to it. """ with connection.schema_editor() as editor: # Create a table with a unique constraint on the slug field. editor.create_model(Tag) # Remove the slug column. editor.remove_field(Tag, Tag._meta.get_field("slug")) self.assertEqual(editor.deferred_sql, []) def test_add_field_temp_default(self): """ Tests adding fields to models with a temporary default """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = CharField(max_length=30, default="Godwin") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["surname"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( columns["surname"][1][6], connection.features.interprets_empty_strings_as_nulls, ) def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns["awesome"][0] self.assertEqual( field_type, connection.features.introspected_field_types["BooleanField"] ) def test_add_field_default_transform(self): """ Tests adding fields to models with a default that is not directly valid in the database (#22581) """ class TestTransformField(IntegerField): # Weird field that saves the count of items in its value def get_default(self): return self.default def get_prep_value(self, value): if value is None: return 0 return len(value) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add the field with a default it needs to cast (to string in this case) new_field = TestTransformField(default={1: 2}) new_field.set_attributes_from_name("thing") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is there columns = self.column_classes(Author) field_type, field_info = columns["thing"] self.assertEqual( field_type, connection.features.introspected_field_types["IntegerField"] ) # Make sure the values were transformed correctly self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2) def test_add_field_o2o_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Note) new_field = OneToOneField(Note, CASCADE, null=True) new_field.set_attributes_from_name("note") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertIn("note_id", columns) self.assertTrue(columns["note_id"][1][6]) def test_add_field_binary(self): """ Tests binary fields get a sane default (#22851) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field new_field = BinaryField(blank=True) new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # MySQL annoyingly uses the same backend, so it'll come back as one of # these two types. self.assertIn(columns["bits"][0], ("BinaryField", "TextField")) def test_add_field_durationfield_with_default(self): with connection.schema_editor() as editor: editor.create_model(Author) new_field = DurationField(default=datetime.timedelta(minutes=10)) new_field.set_attributes_from_name("duration") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["duration"][0], connection.features.introspected_field_types["DurationField"], ) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_add_binaryfield_mediumblob(self): """ Test adding a custom-sized binary field on MySQL (#24846). """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field with default new_field = MediumBlobField(blank=True, default=b"123") new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # Introspection treats BLOBs as TextFields self.assertEqual(columns["bits"][0], "TextField") @isolate_apps("schema") def test_add_auto_field(self): class AddAutoFieldModel(Model): name = CharField(max_length=255, primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(AddAutoFieldModel) self.isolated_local_models = [AddAutoFieldModel] old_field = AddAutoFieldModel._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") new_field.model = AddAutoFieldModel with connection.schema_editor() as editor: editor.alter_field(AddAutoFieldModel, old_field, new_field) new_auto_field = AutoField(primary_key=True) new_auto_field.set_attributes_from_name("id") new_auto_field.model = AddAutoFieldModel() with connection.schema_editor() as editor: editor.add_field(AddAutoFieldModel, new_auto_field) # Crashes on PostgreSQL when the GENERATED BY suffix is missing. AddAutoFieldModel.objects.create(name="test") def test_remove_field(self): with connection.schema_editor() as editor: editor.create_model(Author) with CaptureQueriesContext(connection) as ctx: editor.remove_field(Author, Author._meta.get_field("name")) columns = self.column_classes(Author) self.assertNotIn("name", columns) if getattr(connection.features, "can_alter_table_drop_column", True): # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False, ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False, ) def test_remove_indexed_field(self): with connection.schema_editor() as editor: editor.create_model(AuthorCharFieldWithIndex) with connection.schema_editor() as editor: editor.remove_field( AuthorCharFieldWithIndex, AuthorCharFieldWithIndex._meta.get_field("char_field"), ) columns = self.column_classes(AuthorCharFieldWithIndex) self.assertNotIn("char_field", columns) def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) # Alter the name field to a TextField old_field = Author._meta.get_field("name") new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertTrue(columns["name"][1][6]) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) def test_alter_auto_field_to_integer_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to IntegerField old_field = Author._meta.get_field("id") new_field = IntegerField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Now that ID is an IntegerField, the database raises an error if it # isn't provided. if not connection.features.supports_unspecified_pk: with self.assertRaises(DatabaseError): Author.objects.create() def test_alter_auto_field_to_char_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to CharField old_field = Author._meta.get_field("id") new_field = CharField(primary_key=True, max_length=50) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @isolate_apps("schema") def test_alter_auto_field_quoted_db_column(self): class Foo(Model): id = AutoField(primary_key=True, db_column='"quoted_id"') class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.db_column = '"quoted_id"' new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_not_unique_field_to_primary_key(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Change UUIDField to primary key. old_field = Author._meta.get_field("uuid") new_field = UUIDField(primary_key=True) new_field.set_attributes_from_name("uuid") new_field.model = Author with connection.schema_editor() as editor: editor.remove_field(Author, Author._meta.get_field("id")) editor.alter_field(Author, old_field, new_field, strict=True) # Redundant unique constraint is not added. count = self.get_constraints_count( Author._meta.db_table, Author._meta.get_field("uuid").column, None, ) self.assertLessEqual(count["uniques"], 1) @isolate_apps("schema") def test_alter_primary_key_quoted_db_table(self): class Foo(Model): class Meta: app_label = "schema" db_table = '"foo"' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. # Create the table with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_text_field_to_not_null_with_default_value(self): with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("address") new_field = TextField(blank=True, default="", null=False) new_field.set_attributes_from_name("address") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature("can_defer_constraint_checks", "can_rollback_ddl") def test_alter_fk_checks_deferred_constraints(self): """ #25492 - Altering a foreign key's structure and data in the same transaction. """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("parent") new_field = ForeignKey(Node, CASCADE) new_field.set_attributes_from_name("parent") parent = Node.objects.create() with connection.schema_editor() as editor: # Update the parent FK to create a deferred constraint check. Node.objects.update(parent=parent) editor.alter_field(Node, old_field, new_field, strict=True) @isolate_apps("schema") def test_alter_null_with_default_value_deferred_constraints(self): class Publisher(Model): class Meta: app_label = "schema" class Article(Model): publisher = ForeignKey(Publisher, CASCADE) title = CharField(max_length=50, null=True) description = CharField(max_length=100, null=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Publisher) editor.create_model(Article) self.isolated_local_models = [Article, Publisher] publisher = Publisher.objects.create() Article.objects.create(publisher=publisher) old_title = Article._meta.get_field("title") new_title = CharField(max_length=50, null=False, default="") new_title.set_attributes_from_name("title") old_description = Article._meta.get_field("description") new_description = CharField(max_length=100, null=False, default="") new_description.set_attributes_from_name("description") with connection.schema_editor() as editor: editor.alter_field(Article, old_title, new_title, strict=True) editor.alter_field(Article, old_description, new_description, strict=True) def test_alter_text_field_to_date_field(self): """ #25002 - Test conversion of text field to date field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05") old_field = Note._meta.get_field("info") new_field = DateField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_datetime_field(self): """ #25002 - Test conversion of text field to datetime field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05 3:16:17.4567") old_field = Note._meta.get_field("info") new_field = DateTimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_time_field(self): """ #25002 - Test conversion of text field to time field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="3:16:17.4567") old_field = Note._meta.get_field("info") new_field = TimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = CharField(max_length=50) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): Note.objects.create(info=None) @skipUnlessDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_not_null_to_null(self): """ Nullability for textual fields is preserved on databases that interpret empty strings as NULLs. """ with connection.schema_editor() as editor: editor.create_model(Author) columns = self.column_classes(Author) # Field is nullable. self.assertTrue(columns["uuid"][1][6]) # Change to NOT NULL. old_field = Author._meta.get_field("uuid") new_field = SlugField(null=False, blank=True) new_field.set_attributes_from_name("uuid") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) # Nullability is preserved. self.assertTrue(columns["uuid"][1][6]) def test_alter_numeric_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(UniqueTest) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="aaa") old_field = UniqueTest._meta.get_field("year") new_field = BigIntegerField() new_field.set_attributes_from_name("year") with connection.schema_editor() as editor: editor.alter_field(UniqueTest, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="bbb") def test_alter_null_to_not_null(self): """ #23609 - Tests handling of default values when altering from NULL to NOT NULL. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertTrue(columns["height"][1][6]) # Create some test data Author.objects.create(name="Not null author", height=12) Author.objects.create(name="Null author") # Verify null value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertIsNone(Author.objects.get(name="Null author").height) # Alter the height field to NOT NULL with default old_field = Author._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertFalse(columns["height"][1][6]) # Verify default value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertEqual(Author.objects.get(name="Null author").height, 42) def test_alter_charfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a CharField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change the CharField to null old_field = Author._meta.get_field("name") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_char_field_decrease_length(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name="x" * 255) # Change max_length of CharField. old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: msg = "value too long for type character varying(254)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_with_custom_db_type(self): from django.contrib.postgres.fields import ArrayField class Foo(Model): field = ArrayField(CharField(max_length=255)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("field") new_field = ArrayField(CharField(max_length=16)) new_field.set_attributes_from_name("field") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(CharField(max_length=16)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=["x" * 16]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(CharField(max_length=15)) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_nested_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(ArrayField(CharField(max_length=16))) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=[["x" * 16]]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(ArrayField(CharField(max_length=15))) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) def _add_ci_collation(self): ci_collation = "case_insensitive" def drop_collation(): with connection.cursor() as cursor: cursor.execute(f"DROP COLLATION IF EXISTS {ci_collation}") with connection.cursor() as cursor: cursor.execute( f"CREATE COLLATION IF NOT EXISTS {ci_collation} (provider=icu, " f"locale='und-u-ks-level2', deterministic=false)" ) self.addCleanup(drop_collation) return ci_collation @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_db_collation_arrayfield(self): from django.contrib.postgres.fields import ArrayField ci_collation = self._add_ci_collation() cs_collation = "en-x-icu" class ArrayModel(Model): field = ArrayField(CharField(max_length=16, db_collation=ci_collation)) class Meta: app_label = "schema" # Create the table. with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] self.assertEqual( self.get_column_collation(ArrayModel._meta.db_table, "field"), ci_collation, ) # Alter collation. old_field = ArrayModel._meta.get_field("field") new_field_cs = ArrayField(CharField(max_length=16, db_collation=cs_collation)) new_field_cs.set_attributes_from_name("field") new_field_cs.model = ArrayField with connection.schema_editor() as editor: editor.alter_field(ArrayModel, old_field, new_field_cs, strict=True) self.assertEqual( self.get_column_collation(ArrayModel._meta.db_table, "field"), cs_collation, ) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_unique_with_collation_charfield(self): ci_collation = self._add_ci_collation() class CiCharModel(Model): field = CharField(max_length=16, db_collation=ci_collation, unique=True) class Meta: app_label = "schema" # Create the table. with connection.schema_editor() as editor: editor.create_model(CiCharModel) self.isolated_local_models = [CiCharModel] self.assertEqual( self.get_column_collation(CiCharModel._meta.db_table, "field"), ci_collation, ) self.assertIn("field", self.get_uniques(CiCharModel._meta.db_table)) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_relation_to_collation_charfield(self): ci_collation = self._add_ci_collation() class CiCharModel(Model): field = CharField(max_length=16, db_collation=ci_collation, unique=True) class Meta: app_label = "schema" class RelationModel(Model): field = OneToOneField(CiCharModel, CASCADE, to_field="field") class Meta: app_label = "schema" # Create the table. with connection.schema_editor() as editor: editor.create_model(CiCharModel) editor.create_model(RelationModel) self.isolated_local_models = [CiCharModel, RelationModel] self.assertEqual( self.get_column_collation(RelationModel._meta.db_table, "field_id"), ci_collation, ) self.assertEqual( self.get_column_collation(CiCharModel._meta.db_table, "field"), ci_collation, ) self.assertIn("field_id", self.get_uniques(RelationModel._meta.db_table)) def test_alter_textfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a TextField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Note) # Change the TextField to null old_field = Note._meta.get_field("info") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_null_to_not_null_keeping_default(self): """ #23738 - Can change a nullable field with default to non-nullable with the same default. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) # Ensure the field is right to begin with columns = self.column_classes(AuthorWithDefaultHeight) self.assertTrue(columns["height"][1][6]) # Alter the height field to NOT NULL keeping the previous default old_field = AuthorWithDefaultHeight._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) columns = self.column_classes(AuthorWithDefaultHeight) self.assertFalse(columns["height"][1][6]) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_fk(self): """ Tests altering of FKs """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the FK old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, editable=False) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_alter_to_fk(self): """ #24447 - Tests adding a FK constraint for an existing column """ class LocalBook(Model): author = IntegerField() title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBook] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBook) # Ensure no FK constraint exists constraints = self.get_constraints(LocalBook._meta.db_table) for details in constraints.values(): if details["foreign_key"]: self.fail( "Found an unexpected FK constraint to %s" % details["columns"] ) old_field = LocalBook._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(LocalBook, old_field, new_field, strict=True) self.assertForeignKeyExists(LocalBook, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_alter_o2o_to_fk(self): """ #24163 - Tests altering of OneToOneField to ForeignKey """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) # Ensure the field is right to begin with columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique author = Author.objects.create(name="Joe") BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) BookWithO2O.objects.all().delete() self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") # Alter the OneToOneField to ForeignKey old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique anymore Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_alter_fk_to_o2o(self): """ #24163 - Tests altering of ForeignKey to OneToOneField """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique author = Author.objects.create(name="Joe") Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) Book.objects.all().delete() self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the ForeignKey to OneToOneField old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique now BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") def test_alter_field_fk_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index on ForeignKey is replaced with a unique constraint for # OneToOneField. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) def test_autofield_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Note) # Rename the field. old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("note_ptr") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Alter AutoField to OneToOneField. new_field_o2o = OneToOneField(Note, CASCADE) new_field_o2o.set_attributes_from_name("note_ptr") new_field_o2o.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field_o2o, strict=True) columns = self.column_classes(Author) field_type, _ = columns["note_ptr_id"] self.assertEqual( field_type, connection.features.introspected_field_types["IntegerField"] ) def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") # on_delete changed from CASCADE. new_field = ForeignKey(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index remains. self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) def test_alter_field_o2o_to_fk(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint on OneToOneField is replaced with an index for # ForeignKey. self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1}) def test_alter_field_o2o_keeps_unique(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") # on_delete changed from CASCADE. new_field = OneToOneField(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint remains. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) @skipUnlessDBFeature("ignores_table_name_case") def test_alter_db_table_case(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Alter the case of the table old_table_name = Author._meta.db_table with connection.schema_editor() as editor: editor.alter_db_table(Author, old_table_name, old_table_name.upper()) def test_alter_implicit_id_to_explicit(self): """ Should be able to convert an implicit "id" field to an explicit "id" primary key field. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # This will fail if DROP DEFAULT is inadvertently executed on this # field which drops the id sequence, at least on PostgreSQL. Author.objects.create(name="Foo") Author.objects.create(name="Bar") def test_alter_autofield_pk_to_bigautofield_pk(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_autofield_pk_to_smallautofield_pk(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = SmallAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_int_pk_to_autofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to AutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = AutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToAutoField(Model): i = AutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) def test_alter_int_pk_to_bigautofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to BigAutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = BigAutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToBigAutoField(Model): i = BigAutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToBigAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) @isolate_apps("schema") def test_alter_smallint_pk_to_smallautofield_pk(self): """ Should be able to rename an SmallIntegerField(primary_key=True) to SmallAutoField(primary_key=True). """ class SmallIntegerPK(Model): i = SmallIntegerField(primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(SmallIntegerPK) self.isolated_local_models = [SmallIntegerPK] old_field = SmallIntegerPK._meta.get_field("i") new_field = SmallAutoField(primary_key=True) new_field.model = SmallIntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_serial_auto_field_to_bigautofield(self): class SerialAutoField(Model): id = SmallAutoField(primary_key=True) class Meta: app_label = "schema" table = SerialAutoField._meta.db_table column = SerialAutoField._meta.get_field("id").column with connection.cursor() as cursor: cursor.execute( f'CREATE TABLE "{table}" ' f'("{column}" smallserial NOT NULL PRIMARY KEY)' ) try: old_field = SerialAutoField._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = SerialAutoField new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(SerialAutoField, old_field, new_field, strict=True) sequence_name = f"{table}_{column}_seq" with connection.cursor() as cursor: cursor.execute( "SELECT data_type FROM pg_sequences WHERE sequencename = %s", [sequence_name], ) row = cursor.fetchone() sequence_data_type = row[0] if row and row[0] else None self.assertEqual(sequence_data_type, "bigint") # Rename the column. old_field = new_field new_field = AutoField(primary_key=True) new_field.model = SerialAutoField new_field.set_attributes_from_name("renamed_id") with connection.schema_editor() as editor: editor.alter_field(SerialAutoField, old_field, new_field, strict=True) with connection.cursor() as cursor: cursor.execute( "SELECT data_type FROM pg_sequences WHERE sequencename = %s", [sequence_name], ) row = cursor.fetchone() sequence_data_type = row[0] if row and row[0] else None self.assertEqual(sequence_data_type, "integer") finally: with connection.cursor() as cursor: cursor.execute(f'DROP TABLE "{table}"') def test_alter_int_pk_to_int_unique(self): """ Should be able to rename an IntegerField(primary_key=True) to IntegerField(unique=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) # Delete the old PK old_field = IntegerPK._meta.get_field("i") new_field = IntegerField(unique=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # The primary key constraint is gone. Result depends on database: # 'id' for SQLite, None for others (must not be 'i'). self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ("id", None)) # Set up a model class as it currently stands. The original IntegerPK # class is now out of date and some backends make use of the whole # model class when modifying a field (such as sqlite3 when remaking a # table) so an outdated model class leads to incorrect results. class Transitional(Model): i = IntegerField(unique=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # model requires a new PK old_field = Transitional._meta.get_field("j") new_field = IntegerField(primary_key=True) new_field.model = Transitional new_field.set_attributes_from_name("j") with connection.schema_editor() as editor: editor.alter_field(Transitional, old_field, new_field, strict=True) # Create a model class representing the updated model. class IntegerUnique(Model): i = IntegerField(unique=True) j = IntegerField(primary_key=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # Ensure unique constraint works. IntegerUnique.objects.create(i=1, j=1) with self.assertRaises(IntegrityError): IntegerUnique.objects.create(i=1, j=2) def test_rename(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("display_name", columns) # Alter the name field's name old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("display_name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual( columns["display_name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("name", columns) @isolate_apps("schema") def test_rename_referenced_field(self): class Author(Model): name = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE, to_field="name") class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # Ensure the foreign key reference was updated. self.assertForeignKeyExists(Book, "author_id", "schema_author", "renamed") @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_rename_keep_null_status(self): """ Renaming a field shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = TextField() new_field.set_attributes_from_name("detail_info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["detail_info"][0], "TextField") self.assertNotIn("info", columns) with self.assertRaises(IntegrityError): NoteRename.objects.create(detail_info=None) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) @isolate_apps("schema") def test_rename_field_with_check_to_truncated_name(self): class AuthorWithLongColumn(Model): field_with_very_looooooong_name = PositiveIntegerField(null=True) class Meta: app_label = "schema" self.isolated_local_models = [AuthorWithLongColumn] with connection.schema_editor() as editor: editor.create_model(AuthorWithLongColumn) old_field = AuthorWithLongColumn._meta.get_field( "field_with_very_looooooong_name" ) new_field = PositiveIntegerField(null=True) new_field.set_attributes_from_name("renamed_field_with_very_long_name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithLongColumn, old_field, new_field, strict=True) new_field_name = truncate_name( new_field.column, connection.ops.max_name_length() ) constraints = self.get_constraints(AuthorWithLongColumn._meta.db_table) check_constraints = [ name for name, details in constraints.items() if details["columns"] == [new_field_name] and details["check"] ] self.assertEqual(len(check_constraints), 1) def _test_m2m_create(self, M2MFieldClass): """ Tests M2M fields on models during creation """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2M) # Ensure there is now an m2m table there columns = self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create(self): self._test_m2m_create(ManyToManyField) def test_m2m_create_custom(self): self._test_m2m_create(CustomManyToManyField) def test_m2m_create_inherited(self): self._test_m2m_create(InheritedManyToManyField) def _test_m2m_create_through(self, M2MFieldClass): """ Tests M2M fields on models during creation with through models """ class LocalTagThrough(Model): book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalBookWithM2MThrough(Model): tags = M2MFieldClass( "TagM2MTest", related_name="books", through=LocalTagThrough ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalTagThrough, LocalBookWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalTagThrough) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2MThrough) # Ensure there is now an m2m table there columns = self.column_classes(LocalTagThrough) self.assertEqual( columns["book_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertEqual( columns["tag_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create_through(self): self._test_m2m_create_through(ManyToManyField) def test_m2m_create_through_custom(self): self._test_m2m_create_through(CustomManyToManyField) def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) def test_m2m_through_remove(self): class LocalAuthorNoteThrough(Model): book = ForeignKey("schema.Author", CASCADE) tag = ForeignKey("self", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalNoteWithM2MThrough(Model): authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough] # Create the tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalAuthorNoteThrough) editor.create_model(LocalNoteWithM2MThrough) # Remove the through parameter. old_field = LocalNoteWithM2MThrough._meta.get_field("authors") new_field = ManyToManyField("Author") new_field.set_attributes_from_name("authors") msg = ( f"Cannot alter field {old_field} into {new_field} - they are not " f"compatible types (you cannot alter to or from M2M fields, or add or " f"remove through= on M2M fields)" ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field) def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models """ class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field with CaptureQueriesContext( connection ) as ctx, connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) # Table is not rebuilt. self.assertEqual( len( [ query["sql"] for query in ctx.captured_queries if "CREATE TABLE" in query["sql"] ] ), 1, ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False, ) # Ensure there is now an m2m table there columns = self.column_classes(new_field.remote_field.through) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) # "Alter" the field. This should not rename the DB table to itself. with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True) # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field(LocalAuthorWithM2M, new_field) # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Make sure the model state is coherent with the table one now that # we've removed the tags field. opts = LocalAuthorWithM2M._meta opts.local_many_to_many.remove(new_field) del new_apps.all_models["schema"][ new_field.remote_field.through._meta.model_name ] opts._expire_cache() def test_m2m(self): self._test_m2m(ManyToManyField) def test_m2m_custom(self): self._test_m2m(CustomManyToManyField) def test_m2m_inherited(self): self._test_m2m(InheritedManyToManyField) def _test_m2m_through_alter(self, M2MFieldClass): """ Tests altering M2Ms with explicit through models (should no-op) """ class LocalAuthorTag(Model): author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalAuthorWithM2MThrough(Model): name = CharField(max_length=255) tags = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorTag) editor.create_model(LocalAuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags") new_field = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags") with connection.schema_editor() as editor: editor.alter_field( LocalAuthorWithM2MThrough, old_field, new_field, strict=True ) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) def test_m2m_through_alter(self): self._test_m2m_through_alter(ManyToManyField) def test_m2m_through_alter_custom(self): self._test_m2m_through_alter(CustomManyToManyField) def test_m2m_through_alter_inherited(self): self._test_m2m_through_alter(InheritedManyToManyField) def _test_m2m_repoint(self, M2MFieldClass): """ Tests repointing M2M fields """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( LocalBookWithM2M._meta.get_field("tags").remote_field.through, "tagm2mtest_id", "schema_tagm2mtest", ) # Repoint the M2M old_field = LocalBookWithM2M._meta.get_field("tags") new_field = M2MFieldClass(UniqueTest) new_field.contribute_to_class(LocalBookWithM2M, "uniques") with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True) # Ensure old M2M is gone with self.assertRaises(DatabaseError): self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) # This model looks like the new model and is used for teardown. opts = LocalBookWithM2M._meta opts.local_many_to_many.remove(old_field) # Ensure the new M2M exists and points to UniqueTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( new_field.remote_field.through, "uniquetest_id", "schema_uniquetest" ) def test_m2m_repoint(self): self._test_m2m_repoint(ManyToManyField) def test_m2m_repoint_custom(self): self._test_m2m_repoint(CustomManyToManyField) def test_m2m_repoint_inherited(self): self._test_m2m_repoint(InheritedManyToManyField) @isolate_apps("schema") def test_m2m_rename_field_in_target_model(self): class LocalTagM2MTest(Model): title = CharField(max_length=255) class Meta: app_label = "schema" class LocalM2M(Model): tags = ManyToManyField(LocalTagM2MTest) class Meta: app_label = "schema" # Create the tables. with connection.schema_editor() as editor: editor.create_model(LocalM2M) editor.create_model(LocalTagM2MTest) self.isolated_local_models = [LocalM2M, LocalTagM2MTest] # Ensure the m2m table is there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) # Alter a field in LocalTagM2MTest. old_field = LocalTagM2MTest._meta.get_field("title") new_field = CharField(max_length=254) new_field.contribute_to_class(LocalTagM2MTest, "title1") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True) # Ensure the m2m table is still there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_check_constraints(self): """ Tests creating/deleting CHECK constraints """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the constraint exists constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") # Alter the column to remove it old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) for details in constraints.values(): if details["columns"] == ["height"] and details["check"]: self.fail("Check constraint for height found") # Alter the column to re-add it new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) @isolate_apps("schema") def test_check_constraint_timedelta_param(self): class DurationModel(Model): duration = DurationField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(DurationModel) self.isolated_local_models = [DurationModel] constraint_name = "duration_gte_5_minutes" constraint = CheckConstraint( check=Q(duration__gt=datetime.timedelta(minutes=5)), name=constraint_name, ) DurationModel._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(DurationModel, constraint) constraints = self.get_constraints(DurationModel._meta.db_table) self.assertIn(constraint_name, constraints) with self.assertRaises(IntegrityError), atomic(): DurationModel.objects.create(duration=datetime.timedelta(minutes=4)) DurationModel.objects.create(duration=datetime.timedelta(minutes=10)) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_remove_field_check_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add the custom check constraint constraint = CheckConstraint( check=Q(height__gte=0), name="author_height_gte_0_check" ) custom_constraint_name = constraint.name Author._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) # Ensure the constraints exist constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field check old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field check new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the check constraint with connection.schema_editor() as editor: Author._meta.constraints = [] editor.remove_constraint(Author, constraint) def test_unique(self): """ Tests removing and adding unique constraints to a single column. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the field is unique to begin with Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be non-unique old_field = Tag._meta.get_field("slug") new_field = SlugField(unique=False) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) # Ensure the field is no longer unique Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be unique new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) # Ensure the field is unique again Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Rename the field new_field3 = SlugField(unique=True) new_field3.set_attributes_from_name("slug2") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field2, new_field3, strict=True) # Ensure the field is still unique TagUniqueRename.objects.create(title="foo", slug2="foo") with self.assertRaises(IntegrityError): TagUniqueRename.objects.create(title="bar", slug2="foo") Tag.objects.all().delete() def test_unique_name_quoting(self): old_table_name = TagUniqueRename._meta.db_table try: with connection.schema_editor() as editor: editor.create_model(TagUniqueRename) editor.alter_db_table(TagUniqueRename, old_table_name, "unique-table") TagUniqueRename._meta.db_table = "unique-table" # This fails if the unique index name isn't quoted. editor.alter_unique_together(TagUniqueRename, [], (("title", "slug2"),)) finally: with connection.schema_editor() as editor: editor.delete_model(TagUniqueRename) TagUniqueRename._meta.db_table = old_table_name @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_unique_no_unnecessary_fk_drops(self): """ If AlterField isn't selective about dropping foreign key constraints when modifying a field with a unique constraint, the AlterField incorrectly drops and recreates the Book.author foreign key even though it doesn't restrict the field being changed (#29193). """ class Author(Model): name = CharField(max_length=254, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.model = Author new_field.set_attributes_from_name("name") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) @isolate_apps("schema") def test_unique_and_reverse_m2m(self): """ AlterField can modify a unique field when there's a reverse M2M relation on the model. """ class Tag(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = "schema" class Book(Model): tags = ManyToManyField(Tag, related_name="books") class Meta: app_label = "schema" self.isolated_local_models = [Book._meta.get_field("tags").remote_field.through] with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Book) new_field = SlugField(max_length=75, unique=True) new_field.model = Tag new_field.set_attributes_from_name("slug") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Tag, Tag._meta.get_field("slug"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) # Ensure that the field is still unique. Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") def test_remove_ignored_unique_constraint_not_create_fk_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) constraint = UniqueConstraint( "author", condition=Q(title__in=["tHGttG", "tRatEotU"]), name="book_author_condition_uniq", ) # Add unique constraint. with connection.schema_editor() as editor: editor.add_constraint(Book, constraint) old_constraints = self.get_constraints_for_column( Book, Book._meta.get_field("author").column, ) # Remove unique constraint. with connection.schema_editor() as editor: editor.remove_constraint(Book, constraint) new_constraints = self.get_constraints_for_column( Book, Book._meta.get_field("author").column, ) # Redundant foreign key index is not added. self.assertEqual( len(old_constraints) - 1 if connection.features.supports_partial_indexes else len(old_constraints), len(new_constraints), ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_field_unique_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueName) self.local_models = [AuthorWithUniqueName] # Add the custom unique constraint constraint = UniqueConstraint(fields=["name"], name="author_name_uniq") custom_constraint_name = constraint.name AuthorWithUniqueName._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueName, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field uniqueness old_field = AuthorWithUniqueName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field uniqueness new_field2 = AuthorWithUniqueName._meta.get_field("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueName._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueName, constraint) def test_unique_together(self): """ Tests removing and adding unique_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(UniqueTest) # Ensure the fields are unique to begin with UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="bar") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter the model to its non-unique-together companion with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, UniqueTest._meta.unique_together, [] ) # Ensure the fields are no longer unique UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, [], UniqueTest._meta.unique_together ) # Ensure the fields are unique again UniqueTest.objects.create(year=2012, slug="foo") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() def test_unique_together_with_fk(self): """ Tests removing and adding unique_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) def test_unique_together_with_fk_with_existing_index(self): """ Tests removing and adding unique_together constraints that include a foreign key, where the foreign key is added after the model is created. """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithoutAuthor) new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") editor.add_field(BookWithoutAuthor, new_field) # Ensure the fields aren't unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) def _test_composed_index_with_fk(self, index): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) table = Book._meta.db_table self.assertEqual(Book._meta.indexes, []) Book._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(Book, index) self.assertIn(index.name, self.get_constraints(table)) Book._meta.indexes = [] with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) def test_composed_index_with_fk(self): index = Index(fields=["author", "title"], name="book_author_title_idx") self._test_composed_index_with_fk(index) def test_composed_desc_index_with_fk(self): index = Index(fields=["-author", "title"], name="book_author_title_idx") self._test_composed_index_with_fk(index) @skipUnlessDBFeature("supports_expression_indexes") def test_composed_func_index_with_fk(self): index = Index(F("author"), F("title"), name="book_author_title_idx") self._test_composed_index_with_fk(index) @skipUnlessDBFeature("supports_expression_indexes") def test_composed_desc_func_index_with_fk(self): index = Index(F("author").desc(), F("title"), name="book_author_title_idx") self._test_composed_index_with_fk(index) @skipUnlessDBFeature("supports_expression_indexes") def test_composed_func_transform_index_with_fk(self): index = Index(F("title__lower"), name="book_title_lower_idx") with register_lookup(CharField, Lower): self._test_composed_index_with_fk(index) def _test_composed_constraint_with_fk(self, constraint): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) table = Book._meta.db_table self.assertEqual(Book._meta.constraints, []) Book._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Book, constraint) self.assertIn(constraint.name, self.get_constraints(table)) Book._meta.constraints = [] with connection.schema_editor() as editor: editor.remove_constraint(Book, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) def test_composed_constraint_with_fk(self): constraint = UniqueConstraint( fields=["author", "title"], name="book_author_title_uniq", ) self._test_composed_constraint_with_fk(constraint) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_composed_check_constraint_with_fk(self): constraint = CheckConstraint(check=Q(author__gt=0), name="book_author_check") self._test_composed_constraint_with_fk(constraint) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueNameAndBirthday) self.local_models = [AuthorWithUniqueNameAndBirthday] # Add the custom unique constraint constraint = UniqueConstraint( fields=["name", "birthday"], name="author_name_birthday_uniq" ) custom_constraint_name = constraint.name AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint) # Ensure the constraints exist constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Remove unique together unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, unique_together, [] ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Re-add unique together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, [], unique_together ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueNameAndBirthday._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint) def test_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(fields=["name"], name="name_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table self.assertIs(sql.references_table(table), True) self.assertIs(sql.references_column(table, "name"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Upper("name").desc(), name="func_upper_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC"]) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Upper("title"), Lower("slug"), name="func_upper_lower_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains database functions. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) sql = str(sql) self.assertIn("UPPER(%s)" % editor.quote_name("title"), sql) self.assertIn("LOWER(%s)" % editor.quote_name("slug"), sql) self.assertLess(sql.index("UPPER"), sql.index("LOWER")) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_unique_constraint_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( F("height").desc(), "uuid", Lower("name").asc(), name="func_f_lower_field_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC", "ASC"]) constraints = self.get_constraints(table) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual(len(constraints[constraint.name]["columns"]), 3) self.assertEqual(constraints[constraint.name]["columns"][1], "uuid") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "uuid"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_partial_indexes") def test_func_unique_constraint_partial(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_cond_weight_uq", condition=Q(weight__isnull=False), ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "WHERE %s IS NOT NULL" % editor.quote_name("weight"), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_covering_indexes") def test_func_unique_constraint_covering(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_covering_uq", include=["weight", "height"], ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual( constraints[constraint.name]["columns"], [None, "weight", "height"], ) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) self.assertIs(sql.references_column(table, "height"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "INCLUDE (%s, %s)" % ( editor.quote_name("weight"), editor.quote_name("height"), ), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): constraint = UniqueConstraint( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_unique_constraint_unsupported(self): # UniqueConstraint is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(F("name"), name="func_name_uq") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_constraint(Author, constraint)) self.assertIsNone(editor.remove_constraint(Author, constraint)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nonexistent_field(self): constraint = UniqueConstraint(Lower("nonexistent"), name="func_nonexistent_uq") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Random(), name="func_random_uq") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_constraint(Author, constraint) @ignore_warnings(category=RemovedInDjango51Warning) def test_index_together(self): """ Tests removing and adding index_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure there's no index on the year/slug columns first self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) # Alter the model to add an index with connection.schema_editor() as editor: editor.alter_index_together(Tag, [], [("slug", "title")]) # Ensure there is now an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), True, ) # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_index_together(Tag, [("slug", "title")], []) # Ensure there's no index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) @ignore_warnings(category=RemovedInDjango51Warning) def test_index_together_with_fk(self): """ Tests removing and adding index_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.index_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_index_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_index_together(Book, [["author", "title"]], []) @ignore_warnings(category=RemovedInDjango51Warning) @isolate_apps("schema") def test_create_index_together(self): """ Tests creating models with index_together already defined """ class TagIndexed(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = "schema" index_together = [["slug", "title"]] # Create the table with connection.schema_editor() as editor: editor.create_model(TagIndexed) self.isolated_local_models = [TagIndexed] # Ensure there is an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tagindexed").values() if c["columns"] == ["slug", "title"] ), True, ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") @ignore_warnings(category=RemovedInDjango51Warning) @isolate_apps("schema") def test_remove_index_together_does_not_remove_meta_indexes(self): class AuthorWithIndexedNameAndBirthday(Model): name = CharField(max_length=255) birthday = DateField() class Meta: app_label = "schema" index_together = [["name", "birthday"]] with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedNameAndBirthday) self.isolated_local_models = [AuthorWithIndexedNameAndBirthday] # Add the custom index index = Index(fields=["name", "birthday"], name="author_name_birthday_idx") custom_index_name = index.name AuthorWithIndexedNameAndBirthday._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedNameAndBirthday, index) # Ensure the indexes exist constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Remove index together index_together = AuthorWithIndexedNameAndBirthday._meta.index_together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, index_together, [] ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 0) # Re-add index together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, [], index_together ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Drop the index with connection.schema_editor() as editor: AuthorWithIndexedNameAndBirthday._meta.indexes = [] editor.remove_index(AuthorWithIndexedNameAndBirthday, index) @isolate_apps("schema") def test_db_table(self): """ Tests renaming of the table """ class Author(Model): name = CharField(max_length=255) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" # Create the table and one referring it. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Alter the table with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_author", "schema_otherauthor") Author._meta.db_table = "schema_otherauthor" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Ensure the foreign key reference was updated self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor") # Alter the table again with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_otherauthor", "schema_author") # Ensure the table is still there Author._meta.db_table = "schema_author" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) def test_add_remove_index(self): """ Tests index addition and removal """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the table is there and has no index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) # Add the index index = Index(fields=["name"], name="author_title_idx") with connection.schema_editor() as editor: editor.add_index(Author, index) self.assertIn("name", self.get_indexes(Author._meta.db_table)) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn("name", self.get_indexes(Author._meta.db_table)) def test_remove_db_index_doesnt_remove_custom_indexes(self): """ Changing db_index to False doesn't remove indexes from Meta.indexes. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedName) self.local_models = [AuthorWithIndexedName] # Ensure the table has its index self.assertIn("name", self.get_indexes(AuthorWithIndexedName._meta.db_table)) # Add the custom index index = Index(fields=["-name"], name="author_name_idx") author_index_name = index.name with connection.schema_editor() as editor: db_index_name = editor._create_index_name( table_name=AuthorWithIndexedName._meta.db_table, column_names=("name",), ) try: AuthorWithIndexedName._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedName, index) old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertIn(author_index_name, old_constraints) self.assertIn(db_index_name, old_constraints) # Change name field to db_index=False old_field = AuthorWithIndexedName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field( AuthorWithIndexedName, old_field, new_field, strict=True ) new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertNotIn(db_index_name, new_constraints) # The index from Meta.indexes is still in the database. self.assertIn(author_index_name, new_constraints) # Drop the index with connection.schema_editor() as editor: editor.remove_index(AuthorWithIndexedName, index) finally: AuthorWithIndexedName._meta.indexes = [] def test_order_index(self): """ Indexes defined with ordering (ASC/DESC) defined on column """ with connection.schema_editor() as editor: editor.create_model(Author) # The table doesn't have an index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) index_name = "author_name_idx" # Add the index index = Index(fields=["name", "-weight"], name=index_name) with connection.schema_editor() as editor: editor.add_index(Author, index) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Author._meta.db_table, index_name, ["ASC", "DESC"]) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) def test_indexes(self): """ Tests creation/altering of indexes """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there and has the right index self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to remove the index old_field = Book._meta.get_field("title") new_field = CharField(max_length=100, db_index=False) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the table is there and has no index self.assertNotIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to re-add the index new_field2 = Book._meta.get_field("title") with connection.schema_editor() as editor: editor.alter_field(Book, new_field, new_field2, strict=True) # Ensure the table is there and has the index again self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Add a unique column, verify that creates an implicit index new_field3 = BookWithSlug._meta.get_field("slug") with connection.schema_editor() as editor: editor.add_field(Book, new_field3) self.assertIn( "slug", self.get_uniques(Book._meta.db_table), ) # Remove the unique, check the index goes with it new_field4 = CharField(max_length=20, unique=False) new_field4.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True) self.assertNotIn( "slug", self.get_uniques(Book._meta.db_table), ) def test_text_field_with_db_index(self): with connection.schema_editor() as editor: editor.create_model(AuthorTextFieldWithIndex) # The text_field index is present if the database supports it. assertion = ( self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn ) assertion( "text_field", self.get_indexes(AuthorTextFieldWithIndex._meta.db_table) ) def _index_expressions_wrappers(self): index_expression = IndexExpression() index_expression.set_wrapper_classes(connection) return ", ".join( [ wrapper_cls.__qualname__ for wrapper_cls in index_expression.wrapper_classes ] ) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_multiple_wrapper_references(self): index = Index(OrderBy(F("name").desc(), descending=True), name="name") msg = ( "Multiple references to %s can't be used in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_invalid_topmost_expressions(self): index = Index(Upper(F("name").desc()), name="name") msg = ( "%s must be topmost expressions in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name").desc(), name="func_lower_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_f(self): with connection.schema_editor() as editor: editor.create_model(Tag) index = Index("slug", F("title").desc(), name="func_f_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Tag, index) sql = index.create_sql(Tag, editor) table = Tag._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Tag._meta.db_table, index.name, ["ASC", "DESC"]) # SQL contains columns. self.assertIs(sql.references_column(table, "slug"), True) self.assertIs(sql.references_column(table, "title"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Tag, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): index = Index( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name"), Upper("name"), name="func_lower_upper_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains database functions. self.assertIs(sql.references_column(table, "name"), True) sql = str(sql) self.assertIn("LOWER(%s)" % editor.quote_name("name"), sql) self.assertIn("UPPER(%s)" % editor.quote_name("name"), sql) self.assertLess(sql.index("LOWER"), sql.index("UPPER")) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) index = Index( F("author").desc(), Lower("title").asc(), "pub_date", name="func_f_lower_field_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Book, index) sql = index.create_sql(Book, editor) table = Book._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC", "ASC"]) self.assertEqual(len(constraints[index.name]["columns"]), 3) self.assertEqual(constraints[index.name]["columns"][2], "pub_date") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "author_id"), True) self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "pub_date"), True) self.assertIn("LOWER(%s)" % editor.quote_name("title"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @isolate_apps("schema") def test_func_index_f_decimalfield(self): class Node(Model): value = DecimalField(max_digits=5, decimal_places=2) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) index = Index(F("value"), name="func_f_decimalfield_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Node, index) sql = index.create_sql(Node, editor) table = Node._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "value"), True) # SQL doesn't contain casting. self.assertNotIn("CAST", str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Node, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_cast(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Cast("weight", FloatField()), name="func_cast_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) index = Index( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(BookWithSlug, index) sql = index.create_sql(BookWithSlug, editor) table = Book._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @skipIfDBFeature("collate_as_index_expression") def test_func_index_collate_f_ordered(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) index = Index( Collate(F("name").desc(), collation=collation), name="func_collate_f_desc_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_calc(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("height") / (F("weight") + Value(5)), name="func_calc_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns and expressions. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "weight"), True) sql = str(sql) self.assertIs( sql.index(editor.quote_name("height")) < sql.index("/") < sql.index(editor.quote_name("weight")) < sql.index("+") < sql.index("5"), True, ) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index("field__some_key", name="func_json_key_idx") with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform_cast(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index( Cast(KeyTextTransform("some_key", "field"), IntegerField()), name="func_json_key_cast_idx", ) with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_index_unsupported(self): # Index is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("name"), name="random_idx") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_index(Author, index)) self.assertIsNone(editor.remove_index(Author, index)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nonexistent_field(self): index = Index(Lower("nonexistent"), name="func_nonexistent_idx") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Random(), name="func_random_idx") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_index(Author, index) def test_primary_key(self): """ Tests altering of the primary key """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the table is there and has the right PK self.assertEqual(self.get_primary_key(Tag._meta.db_table), "id") # Alter to change the PK id_field = Tag._meta.get_field("id") old_field = Tag._meta.get_field("slug") new_field = SlugField(primary_key=True) new_field.set_attributes_from_name("slug") new_field.model = Tag with connection.schema_editor() as editor: editor.remove_field(Tag, id_field) editor.alter_field(Tag, old_field, new_field) # Ensure the PK changed self.assertNotIn( "id", self.get_indexes(Tag._meta.db_table), ) self.assertEqual(self.get_primary_key(Tag._meta.db_table), "slug") def test_alter_primary_key_the_same_name(self): with connection.schema_editor() as editor: editor.create_model(Thing) old_field = Thing._meta.get_field("when") new_field = CharField(max_length=2, primary_key=True) new_field.set_attributes_from_name("when") new_field.model = Thing with connection.schema_editor() as editor: editor.alter_field(Thing, old_field, new_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") with connection.schema_editor() as editor: editor.alter_field(Thing, new_field, old_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") def test_context_manager_exit(self): """ Ensures transaction is correctly closed when an error occurs inside a SchemaEditor context. """ class SomeError(Exception): pass try: with connection.schema_editor(): raise SomeError except SomeError: self.assertFalse(connection.in_atomic_block) @skipIfDBFeature("can_rollback_ddl") def test_unsupported_transactional_ddl_disallowed(self): message = ( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) with atomic(), connection.schema_editor() as editor: with self.assertRaisesMessage(TransactionManagementError, message): editor.execute( editor.sql_create_table % {"table": "foo", "definition": ""} ) @skipUnlessDBFeature("supports_foreign_keys", "indexes_foreign_keys") def test_foreign_key_index_long_names_regression(self): """ Regression test for #21497. Only affects databases that supports foreign keys. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Find the properly shortened column name column_name = connection.ops.quote_name( "author_foreign_key_with_really_long_field_name_id" ) column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase # Ensure the table is there and has an index on the column self.assertIn( column_name, self.get_indexes(BookWithLongName._meta.db_table), ) @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_long_names(self): """ Regression test for #23009. Only affects databases that supports foreign keys. """ # Create the initial tables with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Add a second FK, this would fail due to long ref name before the fix new_field = ForeignKey( AuthorWithEvenLongerName, CASCADE, related_name="something" ) new_field.set_attributes_from_name( "author_other_really_long_named_i_mean_so_long_fk" ) with connection.schema_editor() as editor: editor.add_field(BookWithLongName, new_field) @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_quoted_db_table(self): class Author(Model): class Meta: db_table = '"table_author_double_quoted"' app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) self.isolated_local_models = [Author] if connection.vendor == "mysql": self.assertForeignKeyExists( Book, "author_id", '"table_author_double_quoted"' ) else: self.assertForeignKeyExists(Book, "author_id", "table_author_double_quoted") def test_add_foreign_object(self): with connection.schema_editor() as editor: editor.create_model(BookForeignObj) self.local_models = [BookForeignObj] new_field = ForeignObject( Author, on_delete=CASCADE, from_fields=["author_id"], to_fields=["id"] ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.add_field(BookForeignObj, new_field) def test_creation_deletion_reserved_names(self): """ Tries creating a model's table, and then deleting it when it has a SQL reserved name. """ # Create the table with connection.schema_editor() as editor: try: editor.create_model(Thing) except OperationalError as e: self.fail( "Errors when applying initial migration for a model " "with a table named after an SQL reserved word: %s" % e ) # The table is there list(Thing.objects.all()) # Clean up that table with connection.schema_editor() as editor: editor.delete_model(Thing) # The table is gone with self.assertRaises(DatabaseError): list(Thing.objects.all()) def test_remove_constraints_capital_letters(self): """ #23065 - Constraint names must be quoted if they contain capital letters. """ def get_field(*args, field_class=IntegerField, **kwargs): kwargs["db_column"] = "CamelCase" field = field_class(*args, **kwargs) field.set_attributes_from_name("CamelCase") return field model = Author field = get_field() table = model._meta.db_table column = field.column identifier_converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: editor.create_model(model) editor.add_field(model, field) constraint_name = "CamelCaseIndex" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_index % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "using": "", "columns": editor.quote_name(column), "extra": "", "condition": "", "include": "", } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(db_index=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) constraint_name = "CamelCaseUniqConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute(editor._create_unique_sql(model, [field], constraint_name)) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(unique=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) if editor.sql_create_fk and connection.features.can_introspect_foreign_keys: constraint_name = "CamelCaseFKConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_fk % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "column": editor.quote_name(column), "to_table": editor.quote_name(table), "to_column": editor.quote_name(model._meta.auto_field.column), "deferrable": connection.ops.deferrable_sql(), } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field( model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True, ) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) def test_add_field_use_effective_default(self): """ #23987 - effective_default() should be used as the field default when adding a new field. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField to ensure default will be used from effective_default new_field = CharField(max_length=15, blank=True) new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual( item[0], None if connection.features.interprets_empty_strings_as_nulls else "", ) def test_add_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField with a default new_field = CharField(max_length=15, blank=True, default="surname default") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], "surname default") # And that the default is no longer set in the database. field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "surname" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_add_field_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable CharField with a default. new_field = CharField(max_length=15, blank=True, null=True, default="surname") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "surname" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_add_textfield_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable TextField with a default. new_field = TextField(blank=True, null=True, default="text") new_field.set_attributes_from_name("description") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT description FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "description" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_alter_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") self.assertIsNone(Author.objects.get().height) old_field = Author._meta.get_field("height") # The default from the new field is used in updating existing rows. new_field = IntegerField(blank=True, default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(Author.objects.get().height, 42) # The database default should be removed. with connection.cursor() as cursor: field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "height" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_alter_field_default_doesnt_perform_queries(self): """ No queries are performed if a field default changes and the field's not changing from null to non-null. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) old_field = AuthorWithDefaultHeight._meta.get_field("height") new_default = old_field.default * 2 new_field = PositiveIntegerField(null=True, blank=True, default=new_default) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_fk_attributes_noop(self): """ No queries are performed when changing field attributes that don't affect the schema. """ with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_field = Book._meta.get_field("author") new_field = ForeignKey( Author, blank=True, editable=False, error_messages={"invalid": "error message"}, help_text="help text", limit_choices_to={"limit": "choice"}, on_delete=PROTECT, related_name="related_name", related_query_name="related_query_name", validators=[lambda x: x], verbose_name="verbose name", ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, old_field, new_field, strict=True) with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, new_field, old_field, strict=True) def test_alter_field_choices_noop(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField( choices=(("Jane", "Jane"), ("Joe", "Joe")), max_length=255, ) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Author, old_field, new_field, strict=True) with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Author, new_field, old_field, strict=True) def test_add_textfield_unhashable_default(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") # Create a field that has an unhashable default new_field = TextField(default={}) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.add_field(Author, new_field) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_indexed_charfield(self): field = CharField(max_length=255, db_index=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851", "schema_author_nom_de_plume_7570a851_like", ], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_unique_charfield(self): field = CharField(max_length=255, unique=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851_like", "schema_author_nom_de_plume_key", ], ) @skipUnlessDBFeature("supports_comments") def test_add_db_comment_charfield(self): comment = "Custom comment" field = CharField(max_length=255, db_comment=comment) field.set_attributes_from_name("name_with_comment") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) self.assertEqual( self.get_column_comment(Author._meta.db_table, "name_with_comment"), comment, ) @skipUnlessDBFeature("supports_comments") def test_add_db_comment_and_default_charfield(self): comment = "Custom comment with default" field = CharField(max_length=255, default="Joe Doe", db_comment=comment) field.set_attributes_from_name("name_with_comment_default") with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name="Before adding a new field") editor.add_field(Author, field) self.assertEqual( self.get_column_comment(Author._meta.db_table, "name_with_comment_default"), comment, ) with connection.cursor() as cursor: cursor.execute( f"SELECT name_with_comment_default FROM {Author._meta.db_table};" ) for row in cursor.fetchall(): self.assertEqual(row[0], "Joe Doe") @skipUnlessDBFeature("supports_comments") def test_alter_db_comment(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add comment. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_comment="Custom comment") new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_comment(Author._meta.db_table, "name"), "Custom comment", ) # Alter comment. old_field = new_field new_field = CharField(max_length=255, db_comment="New custom comment") new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_comment(Author._meta.db_table, "name"), "New custom comment", ) # Remove comment. old_field = new_field new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertIn( self.get_column_comment(Author._meta.db_table, "name"), [None, ""], ) @skipUnlessDBFeature("supports_comments", "supports_foreign_keys") def test_alter_db_comment_foreign_key(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) comment = "FK custom comment" old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, db_comment=comment) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertEqual( self.get_column_comment(Book._meta.db_table, "author_id"), comment, ) @skipUnlessDBFeature("supports_comments") def test_alter_field_type_preserve_comment(self): with connection.schema_editor() as editor: editor.create_model(Author) comment = "This is the name." old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_comment=comment) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_comment(Author._meta.db_table, "name"), comment, ) # Changing a field type should preserve the comment. old_field = new_field new_field = CharField(max_length=511, db_comment=comment) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) # Comment is preserved. self.assertEqual( self.get_column_comment(Author._meta.db_table, "name"), comment, ) @isolate_apps("schema") @skipUnlessDBFeature("supports_comments") def test_db_comment_table(self): class ModelWithDbTableComment(Model): class Meta: app_label = "schema" db_table_comment = "Custom table comment" with connection.schema_editor() as editor: editor.create_model(ModelWithDbTableComment) self.isolated_local_models = [ModelWithDbTableComment] self.assertEqual( self.get_table_comment(ModelWithDbTableComment._meta.db_table), "Custom table comment", ) # Alter table comment. old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment with connection.schema_editor() as editor: editor.alter_db_table_comment( ModelWithDbTableComment, old_db_table_comment, "New table comment" ) self.assertEqual( self.get_table_comment(ModelWithDbTableComment._meta.db_table), "New table comment", ) # Remove table comment. old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment with connection.schema_editor() as editor: editor.alter_db_table_comment( ModelWithDbTableComment, old_db_table_comment, None ) self.assertIn( self.get_table_comment(ModelWithDbTableComment._meta.db_table), [None, ""], ) @isolate_apps("schema") @skipUnlessDBFeature("supports_comments", "supports_foreign_keys") def test_db_comments_from_abstract_model(self): class AbstractModelWithDbComments(Model): name = CharField( max_length=255, db_comment="Custom comment", null=True, blank=True ) class Meta: app_label = "schema" abstract = True db_table_comment = "Custom table comment" class ModelWithDbComments(AbstractModelWithDbComments): pass with connection.schema_editor() as editor: editor.create_model(ModelWithDbComments) self.isolated_local_models = [ModelWithDbComments] self.assertEqual( self.get_column_comment(ModelWithDbComments._meta.db_table, "name"), "Custom comment", ) self.assertEqual( self.get_table_comment(ModelWithDbComments._meta.db_table), "Custom table comment", ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add db_index=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_index=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617", "schema_author_name_1fbc5617_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add unique=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617_like", "schema_author_name_1fbc5617_uniq"], ) # Remove unique=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_textfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Note) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) # Alter to add db_index=True and create 2 indexes. old_field = Note._meta.get_field("info") new_field = TextField(db_index=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Note, "info"), ["schema_note_info_4b0ea695", "schema_note_info_4b0ea695_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield_with_db_index(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove unique=True (should drop unique index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_remove_unique_and_db_index_from_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove both unique=True and db_index=True (should drop all indexes) new_field2 = CharField(max_length=100) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), [] ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_swap_unique_and_db_index_with_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to set unique=True and remove db_index=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to set db_index=True and remove unique=True (should restore index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_db_index_to_charfield_with_unique(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(Tag) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to add db_index=True old_field = Tag._meta.get_field("slug") new_field = SlugField(db_index=True, unique=True) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to remove db_index=True new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) def test_alter_field_add_index_to_integerfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) # Alter to add db_index=True and create index. old_field = Author._meta.get_field("weight") new_field = IntegerField(null=True, db_index=True) new_field.set_attributes_from_name("weight") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "weight"), ["schema_author_weight_587740f9"], ) # Remove db_index=True to drop index. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) def test_alter_pk_with_self_referential_field(self): """ Changing the primary key field name of a model with a self-referential foreign key (#26384). """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("node_id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Node, old_field, new_field, strict=True) self.assertForeignKeyExists(Node, "parent_id", Node._meta.db_table) @mock.patch("django.db.backends.base.schema.datetime") @mock.patch("django.db.backends.base.schema.timezone") def test_add_datefield_and_datetimefield_use_effective_default( self, mocked_datetime, mocked_tz ): """ effective_default() should be used for DateField, DateTimeField, and TimeField if auto_now or auto_now_add is set (#25005). """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime( month=1, day=1, year=2000, hour=1, minute=1, tzinfo=datetime.timezone.utc ) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Check auto_now/auto_now_add attributes are not defined columns = self.column_classes(Author) self.assertNotIn("dob_auto_now", columns) self.assertNotIn("dob_auto_now_add", columns) self.assertNotIn("dtob_auto_now", columns) self.assertNotIn("dtob_auto_now_add", columns) self.assertNotIn("tob_auto_now", columns) self.assertNotIn("tob_auto_now_add", columns) # Create a row Author.objects.create(name="Anonymous1") # Ensure fields were added with the correct defaults dob_auto_now = DateField(auto_now=True) dob_auto_now.set_attributes_from_name("dob_auto_now") self.check_added_field_default( editor, Author, dob_auto_now, "dob_auto_now", now.date(), cast_function=lambda x: x.date(), ) dob_auto_now_add = DateField(auto_now_add=True) dob_auto_now_add.set_attributes_from_name("dob_auto_now_add") self.check_added_field_default( editor, Author, dob_auto_now_add, "dob_auto_now_add", now.date(), cast_function=lambda x: x.date(), ) dtob_auto_now = DateTimeField(auto_now=True) dtob_auto_now.set_attributes_from_name("dtob_auto_now") self.check_added_field_default( editor, Author, dtob_auto_now, "dtob_auto_now", now, ) dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True) dt_tm_of_birth_auto_now_add.set_attributes_from_name("dtob_auto_now_add") self.check_added_field_default( editor, Author, dt_tm_of_birth_auto_now_add, "dtob_auto_now_add", now, ) tob_auto_now = TimeField(auto_now=True) tob_auto_now.set_attributes_from_name("tob_auto_now") self.check_added_field_default( editor, Author, tob_auto_now, "tob_auto_now", now.time(), cast_function=lambda x: x.time(), ) tob_auto_now_add = TimeField(auto_now_add=True) tob_auto_now_add.set_attributes_from_name("tob_auto_now_add") self.check_added_field_default( editor, Author, tob_auto_now_add, "tob_auto_now_add", now.time(), cast_function=lambda x: x.time(), ) def test_namespaced_db_table_create_index_name(self): """ Table names are stripped of their namespace/schema before being used to generate index names. """ with connection.schema_editor() as editor: max_name_length = connection.ops.max_name_length() or 200 namespace = "n" * max_name_length table_name = "t" * max_name_length namespaced_table_name = '"%s"."%s"' % (namespace, table_name) self.assertEqual( editor._create_index_name(table_name, []), editor._create_index_name(namespaced_table_name, []), ) @unittest.skipUnless( connection.vendor == "oracle", "Oracle specific db_table syntax" ) def test_creation_with_db_table_double_quotes(self): oracle_user = connection.creation._test_database_user() class Student(Model): name = CharField(max_length=30) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user class Document(Model): name = CharField(max_length=30) students = ManyToManyField(Student) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user self.isolated_local_models = [Student, Document] with connection.schema_editor() as editor: editor.create_model(Student) editor.create_model(Document) doc = Document.objects.create(name="Test Name") student = Student.objects.create(name="Some man") doc.students.add(student) @isolate_apps("schema") @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific db_table syntax." ) def test_namespaced_db_table_foreign_key_reference(self): with connection.cursor() as cursor: cursor.execute("CREATE SCHEMA django_schema_tests") def delete_schema(): with connection.cursor() as cursor: cursor.execute("DROP SCHEMA django_schema_tests CASCADE") self.addCleanup(delete_schema) class Author(Model): class Meta: app_label = "schema" class Book(Model): class Meta: app_label = "schema" db_table = '"django_schema_tests"."schema_book"' author = ForeignKey(Author, CASCADE) author.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.add_field(Book, author) def test_rename_table_renames_deferred_sql_references(self): atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: editor.create_model(Author) editor.create_model(Book) editor.alter_db_table(Author, "schema_author", "schema_renamed_author") editor.alter_db_table(Author, "schema_book", "schema_renamed_book") try: self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_table("schema_author"), False) self.assertIs(statement.references_table("schema_book"), False) finally: editor.alter_db_table(Author, "schema_renamed_author", "schema_author") editor.alter_db_table(Author, "schema_renamed_book", "schema_book") def test_rename_column_renames_deferred_sql_references(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_title = Book._meta.get_field("title") new_title = CharField(max_length=100, db_index=True) new_title.set_attributes_from_name("renamed_title") editor.alter_field(Book, old_title, new_title) old_author = Book._meta.get_field("author") new_author = ForeignKey(Author, CASCADE) new_author.set_attributes_from_name("renamed_author") editor.alter_field(Book, old_author, new_author) self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_column("book", "title"), False) self.assertIs(statement.references_column("book", "author_id"), False) @isolate_apps("schema") def test_referenced_field_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the field they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_field(Foo, Foo._meta.get_field("field"), new_field) @isolate_apps("schema") def test_referenced_table_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the table they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Foo, Foo._meta.db_table, "renamed_table") Foo._meta.db_table = "renamed_table" @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_charfield") def test_db_collation_charfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = CharField(max_length=255, db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_textfield") def test_db_collation_textfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = TextField(db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @skipUnlessDBFeature("supports_collation_on_charfield") def test_add_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("alias") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["alias"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["alias"][1][8], collation) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_collation(Author._meta.db_table, "name"), collation, ) with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertIsNone(self.get_column_collation(Author._meta.db_table, "name")) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_field_type_preserve_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_collation(Author._meta.db_table, "name"), collation, ) # Changing a field type should preserve the collation. old_field = new_field new_field = CharField(max_length=511, db_collation=collation) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) # Collation is preserved. self.assertEqual( self.get_column_collation(Author._meta.db_table, "name"), collation, ) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_primary_key_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Thing) old_field = Thing._meta.get_field("when") new_field = CharField(max_length=1, db_collation=collation, primary_key=True) new_field.set_attributes_from_name("when") new_field.model = Thing with connection.schema_editor() as editor: editor.alter_field(Thing, old_field, new_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") self.assertEqual( self.get_column_collation(Thing._meta.db_table, "when"), collation, ) with connection.schema_editor() as editor: editor.alter_field(Thing, new_field, old_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") self.assertIsNone(self.get_column_collation(Thing._meta.db_table, "when")) @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_collation_on_textfield" ) def test_alter_field_type_and_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("info") new_field.model = Note with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual( columns["info"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["info"][1][8], collation) with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["info"][0], "TextField") self.assertIsNone(columns["info"][1][8]) @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_ci_cs_db_collation(self): cs_collation = connection.features.test_collations.get("cs") ci_collation = connection.features.test_collations.get("ci") try: if connection.vendor == "mysql": cs_collation = "latin1_general_cs" elif connection.vendor == "postgresql": cs_collation = "en-x-icu" with connection.cursor() as cursor: cursor.execute( "CREATE COLLATION IF NOT EXISTS case_insensitive " "(provider = icu, locale = 'und-u-ks-level2', " "deterministic = false)" ) ci_collation = "case_insensitive" # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Case-insensitive collation. old_field = Author._meta.get_field("name") new_field_ci = CharField(max_length=255, db_collation=ci_collation) new_field_ci.set_attributes_from_name("name") new_field_ci.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field_ci, strict=True) Author.objects.create(name="ANDREW") self.assertIs(Author.objects.filter(name="Andrew").exists(), True) # Case-sensitive collation. new_field_cs = CharField(max_length=255, db_collation=cs_collation) new_field_cs.set_attributes_from_name("name") new_field_cs.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field_ci, new_field_cs, strict=True) self.assertIs(Author.objects.filter(name="Andrew").exists(), False) finally: if connection.vendor == "postgresql": with connection.cursor() as cursor: cursor.execute("DROP COLLATION IF EXISTS case_insensitive")
0031d038e490ad9b21db032b8a3094505a6f0c7a03672416f8aa2004c3f8f178
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import cache_control, cache_page, never_cache from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse("<html><body>dummy</body></html>") fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers("Accept-language"), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required("change_world"), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, "fully_decorated") self.assertEqual(fully_decorated.__doc__, "Expected __doc__") self.assertEqual(fully_decorated.__dict__["anything"], "Expected __dict__") def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append("test1") return True def test2(user): user.decorators_applied.append("test2") return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ["test2", "test1"]) def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = "GET" self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = "HEAD" self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = "POST" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = "PUT" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = "DELETE" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): @wraps(func) def wrapper(arg): return func("test:" + arg) return wrapper simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapper(): return f() and self.myattr return update_wrapper(wrapper, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, "myattr", False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, "myattr2", False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, "myattr", False), True) self.assertIs(getattr(func, "myattr2", False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), "method") class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = ( TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable, ) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, "myattr", False), True) self.assertIs(getattr(Test().method, "myattr2", False), True) self.assertIs(getattr(Test.method, "myattr", False), True) self.assertIs(getattr(Test.method, "myattr2", False), True) self.assertEqual(Test.method.__doc__, "A method") self.assertEqual(Test.method.__name__, "method") def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name="nonexistent_method") class Test: @classmethod def __module__(cls): return "tests" def test_wrapper_assignments(self): """@method_decorator preserves wrapper assignments.""" func_name = None func_module = None def decorator(func): @wraps(func) def inner(*args, **kwargs): nonlocal func_name, func_module func_name = getattr(func, "__name__", None) func_module = getattr(func, "__module__", None) return func(*args, **kwargs) return inner class Test: @method_decorator(decorator) def method(self): return "tests" Test().method() self.assertEqual(func_name, "method") self.assertIsNotNone(func_module) class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get("X-Frame-Options", None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware(a_view)(req) self.assertIsNone(r.get("X-Frame-Options", None))
949f5dc92f71a96b55f3d13288dfc351401ea1dc6aeffe581de7ff97403b2104
from unittest import mock from asgiref.sync import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control, cache_page, never_cache class HttpRequestProxy: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr) class CacheControlDecoratorTest(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = cache_control()(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = cache_control()(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a="b") def a_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) request = HttpRequest() with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) async def test_cache_control_decorator_http_request_async_view(self): class MyClass: @cache_control(a="b") async def async_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are decorating a " "classmethod, be sure to use @method_decorator." ) request = HttpRequest() with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(request) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(HttpRequestProxy(request)) def test_cache_control_decorator_http_request_proxy(self): class MyClass: @method_decorator(cache_control(a="b")) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertEqual(response.headers["Cache-Control"], "a=b") def test_cache_control_empty_decorator(self): @cache_control() def a_view(request): return HttpResponse() response = a_view(HttpRequest()) self.assertEqual(response.get("Cache-Control"), "") async def test_cache_control_empty_decorator_async_view(self): @cache_control() async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) self.assertEqual(response.get("Cache-Control"), "") def test_cache_control_full_decorator(self): @cache_control(max_age=123, private=True, public=True, custom=456) def a_view(request): return HttpResponse() response = a_view(HttpRequest()) cache_control_items = response.get("Cache-Control").split(", ") self.assertEqual( set(cache_control_items), {"max-age=123", "private", "public", "custom=456"} ) async def test_cache_control_full_decorator_async_view(self): @cache_control(max_age=123, private=True, public=True, custom=456) async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) cache_control_items = response.get("Cache-Control").split(", ") self.assertEqual( set(cache_control_items), {"max-age=123", "private", "public", "custom=456"} ) class CachePageDecoratorTest(SimpleTestCase): def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") class NeverCacheDecoratorTest(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = never_cache(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = never_cache(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) @mock.patch("time.time") def test_never_cache_decorator_headers(self, mocked_time): @never_cache def a_view(request): return HttpResponse() mocked_time.return_value = 1167616461.0 response = a_view(HttpRequest()) self.assertEqual( response.headers["Expires"], "Mon, 01 Jan 2007 01:54:21 GMT", ) self.assertEqual( response.headers["Cache-Control"], "max-age=0, no-cache, no-store, must-revalidate, private", ) @mock.patch("time.time") async def test_never_cache_decorator_headers_async_view(self, mocked_time): @never_cache async def async_view(request): return HttpResponse() mocked_time.return_value = 1167616461.0 response = await async_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "Mon, 01 Jan 2007 01:54:21 GMT") self.assertEqual( response.headers["Cache-Control"], "max-age=0, no-cache, no-store, must-revalidate, private", ) def test_never_cache_decorator_expires_not_overridden(self): @never_cache def a_view(request): return HttpResponse(headers={"Expires": "tomorrow"}) response = a_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "tomorrow") async def test_never_cache_decorator_expires_not_overridden_async_view(self): @never_cache async def async_view(request): return HttpResponse(headers={"Expires": "tomorrow"}) response = await async_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "tomorrow") def test_never_cache_decorator_http_request(self): class MyClass: @never_cache def a_view(self, request): return HttpResponse() request = HttpRequest() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) async def test_never_cache_decorator_http_request_async_view(self): class MyClass: @never_cache async def async_view(self, request): return HttpResponse() request = HttpRequest() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(request) with self.assertRaisesMessage(TypeError, msg): await MyClass().async_view(HttpRequestProxy(request)) def test_never_cache_decorator_http_request_proxy(self): class MyClass: @method_decorator(never_cache) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertIn("Cache-Control", response.headers) self.assertIn("Expires", response.headers)
af703b9fa6ae761db44a8d54767494b8b292d6ac4fd39a860b0356521e20b8b3
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.db import connection, models from django.db.models.query import EmptyQuerySet from django.forms.models import ( ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict, modelform_factory, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, ignore_warnings, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils.deprecation import RemovedInDjango60Warning from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, Category, Character, Colour, ColourfulItem, CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost, DerivedBook, DerivedPost, Dice, Document, ExplicitPK, FilePathModel, FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink, Inventory, NullableUniqueCharFieldModel, Number, Person, Photo, Post, Price, Product, Publication, PublicationDefaults, StrictAssignmentAll, StrictAssignmentFieldSpecific, Student, StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images, ) if test_images: from .models import ImageFile, NoExtensionImageFile, OptionalImageFile class ImageFileForm(forms.ModelForm): class Meta: model = ImageFile fields = "__all__" class OptionalImageFileForm(forms.ModelForm): class Meta: model = OptionalImageFile fields = "__all__" class NoExtensionImageFileForm(forms.ModelForm): class Meta: model = NoExtensionImageFile fields = "__all__" class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" class PriceForm(forms.ModelForm): class Meta: model = Price fields = "__all__" class BookForm(forms.ModelForm): class Meta: model = Book fields = "__all__" class DerivedBookForm(forms.ModelForm): class Meta: model = DerivedBook fields = "__all__" class ExplicitPKForm(forms.ModelForm): class Meta: model = ExplicitPK fields = ( "key", "desc", ) class PostForm(forms.ModelForm): class Meta: model = Post fields = "__all__" class DerivedPostForm(forms.ModelForm): class Meta: model = DerivedPost fields = "__all__" class CustomWriterForm(forms.ModelForm): name = forms.CharField(required=False) class Meta: model = Writer fields = "__all__" class BaseCategoryForm(forms.ModelForm): class Meta: model = Category fields = "__all__" class ArticleForm(forms.ModelForm): class Meta: model = Article fields = "__all__" class RoykoForm(forms.ModelForm): class Meta: model = Writer fields = "__all__" class ArticleStatusForm(forms.ModelForm): class Meta: model = ArticleStatus fields = "__all__" class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = "__all__" class SelectInventoryForm(forms.Form): items = forms.ModelMultipleChoiceField( Inventory.objects.all(), to_field_name="barcode" ) class CustomFieldForExclusionForm(forms.ModelForm): class Meta: model = CustomFieldForExclusionModel fields = ["name", "markup"] class TextFileForm(forms.ModelForm): class Meta: model = TextFile fields = "__all__" class BigIntForm(forms.ModelForm): class Meta: model = BigInt fields = "__all__" class ModelFormWithMedia(forms.ModelForm): class Media: js = ("/some/form/javascript",) css = {"all": ("/some/form/css",)} class Meta: model = TextFile fields = "__all__" class CustomErrorMessageForm(forms.ModelForm): name1 = forms.CharField(error_messages={"invalid": "Form custom error message."}) class Meta: fields = "__all__" model = CustomErrorMessage class ModelFormBaseTest(TestCase): def test_base_form(self): self.assertEqual(list(BaseCategoryForm.base_fields), ["name", "slug", "url"]) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass with self.assertRaisesMessage( ValueError, "ModelForm has no model class specified." ): NoModelModelForm() def test_empty_fields_to_fields_for_model(self): """ An argument of fields=() to fields_for_model should return an empty dictionary """ field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_fields_for_model_form_fields(self): form_declared_fields = CustomWriterForm.declared_fields field_dict = fields_for_model( Writer, fields=["name"], form_declared_fields=form_declared_fields, ) self.assertIs(field_dict["name"], form_declared_fields["name"]) def test_empty_fields_on_modelform(self): """ No fields on a ModelForm should actually result in no fields. """ class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () form = EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): """ No fields should be set on a model instance if construct_instance receives fields=(). """ form = modelform_factory(Person, fields="__all__")({"name": "John Doe"}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, "") def test_blank_with_null_foreign_key_field(self): """ #13776 -- ModelForm's with models having a FK set to null=False and required=False should be valid. """ class FormForTestingIsValid(forms.ModelForm): class Meta: model = Student fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["character"].required = False char = Character.objects.create( username="user", last_action=datetime.datetime.today() ) data = {"study": "Engineering"} data2 = {"study": "Engineering", "character": char.pk} # form is valid because required=False for field 'character' f1 = FormForTestingIsValid(data) self.assertTrue(f1.is_valid()) f2 = FormForTestingIsValid(data2) self.assertTrue(f2.is_valid()) obj = f2.save() self.assertEqual(obj.character, char) def test_blank_false_with_null_true_foreign_key_field(self): """ A ModelForm with a model having ForeignKey(blank=False, null=True) and the form field set to required=False should allow the field to be unset. """ class AwardForm(forms.ModelForm): class Meta: model = Award fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["character"].required = False character = Character.objects.create( username="user", last_action=datetime.datetime.today() ) award = Award.objects.create(name="Best sprinter", character=character) data = {"name": "Best tester", "character": ""} # remove character form = AwardForm(data=data, instance=award) self.assertTrue(form.is_valid()) award = form.save() self.assertIsNone(award.character) def test_blank_foreign_key_with_radio(self): class BookForm(forms.ModelForm): class Meta: model = Book fields = ["author"] widgets = {"author": forms.RadioSelect()} writer = Writer.objects.create(name="Joe Doe") form = BookForm() self.assertEqual( list(form.fields["author"].choices), [ ("", "---------"), (writer.pk, "Joe Doe"), ], ) def test_non_blank_foreign_key_with_radio(self): class AwardForm(forms.ModelForm): class Meta: model = Award fields = ["character"] widgets = {"character": forms.RadioSelect()} character = Character.objects.create( username="user", last_action=datetime.datetime.today(), ) form = AwardForm() self.assertEqual( list(form.fields["character"].choices), [(character.pk, "user")], ) def test_save_blank_false_with_required_false(self): """ A ModelForm with a model with a field set to blank=False and the form field set to required=False should allow the field to be unset. """ obj = Writer.objects.create(name="test") form = CustomWriterForm(data={"name": ""}, instance=obj) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.name, "") @ignore_warnings(category=RemovedInDjango60Warning) def test_save_blank_null_unique_charfield_saves_null(self): form_class = modelform_factory( model=NullableUniqueCharFieldModel, fields="__all__" ) empty_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) data = { "codename": "", "email": "", "slug": "", "url": "", } form = form_class(data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) self.assertEqual(form.instance.email, empty_value) self.assertEqual(form.instance.slug, empty_value) self.assertEqual(form.instance.url, empty_value) # Save a second form to verify there isn't a unique constraint violation. form = form_class(data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) self.assertEqual(form.instance.email, empty_value) self.assertEqual(form.instance.slug, empty_value) self.assertEqual(form.instance.url, empty_value) def test_missing_fields_attribute(self): message = ( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form " "MissingFieldsForm needs updating." ) with self.assertRaisesMessage(ImproperlyConfigured, message): class MissingFieldsForm(forms.ModelForm): class Meta: model = Category def test_extra_fields(self): class ExtraFields(BaseCategoryForm): some_extra_field = forms.BooleanField() self.assertEqual( list(ExtraFields.base_fields), ["name", "slug", "url", "some_extra_field"] ) def test_extra_field_model_form(self): with self.assertRaisesMessage(FieldError, "no-field"): class ExtraPersonForm(forms.ModelForm): """ModelForm with an extra field""" age = forms.IntegerField() class Meta: model = Person fields = ("name", "no-field") def test_extra_declared_field_model_form(self): class ExtraPersonForm(forms.ModelForm): """ModelForm with an extra field""" age = forms.IntegerField() class Meta: model = Person fields = ("name", "age") def test_extra_field_modelform_factory(self): with self.assertRaisesMessage( FieldError, "Unknown field(s) (no-field) specified for Person" ): modelform_factory(Person, fields=["no-field", "name"]) def test_replace_field(self): class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = "__all__" self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_replace_field_variant_2(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = ["url"] self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_replace_field_variant_3(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = [] # url will still appear, since it is explicit above self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_override_field(self): class WriterForm(forms.ModelForm): book = forms.CharField(required=False) class Meta: model = Writer fields = "__all__" wf = WriterForm({"name": "Richard Lockridge"}) self.assertTrue(wf.is_valid()) def test_limit_nonexistent_field(self): expected_msg = "Unknown field(s) (nonexistent) specified for Category" with self.assertRaisesMessage(FieldError, expected_msg): class InvalidCategoryForm(forms.ModelForm): class Meta: model = Category fields = ["nonexistent"] def test_limit_fields_with_string(self): msg = ( "CategoryForm.Meta.fields cannot be a string. Did you mean to type: " "('url',)?" ) with self.assertRaisesMessage(TypeError, msg): class CategoryForm(forms.ModelForm): class Meta: model = Category fields = "url" # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ["url"] self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug"]) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ["nonexistent"] self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug", "url"]) def test_exclude_fields_with_string(self): msg = ( "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: " "('url',)?" ) with self.assertRaisesMessage(TypeError, msg): class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = "url" # note the missing comma def test_exclude_and_validation(self): # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from # the form. This is for backwards compatibility. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price exclude = ("quantity",) form = PriceFormWithoutQuantity({"price": "6.00"}) self.assertTrue(form.is_valid()) price = form.save(commit=False) msg = "{'quantity': ['This field cannot be null.']}" with self.assertRaisesMessage(ValidationError, msg): price.full_clean() # The form should not validate fields that it doesn't contain even if they are # specified using 'fields', not 'exclude'. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price fields = ("price",) form = PriceFormWithoutQuantity({"price": "6.00"}) self.assertTrue(form.is_valid()) # The form should still have an instance of a model that is not complete and # not saved into a DB yet. self.assertEqual(form.instance.price, Decimal("6.00")) self.assertIsNone(form.instance.quantity) self.assertIsNone(form.instance.pk) def test_confused_form(self): class ConfusedForm(forms.ModelForm): """Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. """ class Meta: model = Category fields = ["name", "url"] exclude = ["url"] self.assertEqual(list(ConfusedForm.base_fields), ["name"]) def test_mixmodel_form(self): class MixModelForm(BaseCategoryForm): """Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. """ class Meta: model = Article fields = "__all__" # MixModelForm is now an Article-related thing, because MixModelForm.Meta # overrides BaseCategoryForm.Meta. self.assertEqual( list(MixModelForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_article_form(self): self.assertEqual( list(ArticleForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_bad_form(self): # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass self.assertEqual( list(BadForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_invalid_meta_model(self): class InvalidModelForm(forms.ModelForm): class Meta: pass # no model # Can't create new form msg = "ModelForm has no model class specified." with self.assertRaisesMessage(ValueError, msg): InvalidModelForm() # Even if you provide a model instance with self.assertRaisesMessage(ValueError, msg): InvalidModelForm(instance=Category) def test_subcategory_form(self): class SubCategoryForm(BaseCategoryForm): """Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). """ pass self.assertEqual(list(SubCategoryForm.base_fields), ["name", "slug", "url"]) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): checkbox = forms.BooleanField() class Meta: model = Category fields = "__all__" class SubclassMeta(SomeCategoryForm): """We can also subclass the Meta inner class to change the fields list. """ class Meta(SomeCategoryForm.Meta): exclude = ["url"] self.assertHTMLEqual( str(SubclassMeta()), '<div><label for="id_name">Name:</label>' '<input type="text" name="name" maxlength="20" required id="id_name">' '</div><div><label for="id_slug">Slug:</label><input type="text" ' 'name="slug" maxlength="20" required id="id_slug"></div><div>' '<label for="id_checkbox">Checkbox:</label>' '<input type="checkbox" name="checkbox" required id="id_checkbox"></div>', ) def test_orderfields_form(self): class OrderFields(forms.ModelForm): class Meta: model = Category fields = ["url", "name"] self.assertEqual(list(OrderFields.base_fields), ["url", "name"]) self.assertHTMLEqual( str(OrderFields()), '<div><label for="id_url">The URL:</label>' '<input type="text" name="url" maxlength="40" required id="id_url">' '</div><div><label for="id_name">Name:</label><input type="text" ' 'name="name" maxlength="20" required id="id_name"></div>', ) def test_orderfields2_form(self): class OrderFields2(forms.ModelForm): class Meta: model = Category fields = ["slug", "url", "name"] exclude = ["url"] self.assertEqual(list(OrderFields2.base_fields), ["slug", "name"]) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data uses the model field default. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "di") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") # Blank data doesn't use the model field default. mf2 = PubForm({"mode": ""}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.mode, "") def test_default_not_populated_on_non_empty_value_in_cleaned_data(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) mocked_mode = None def clean(self): self.cleaned_data["mode"] = self.mocked_mode return self.cleaned_data class Meta: model = PublicationDefaults fields = ("mode",) pub_form = PubForm({}) pub_form.mocked_mode = "de" pub = pub_form.save(commit=False) self.assertEqual(pub.mode, "de") # Default should be populated on an empty value in cleaned_data. default_mode = "di" for empty_value in pub_form.fields["mode"].empty_values: with self.subTest(empty_value=empty_value): pub_form = PubForm({}) pub_form.mocked_mode = empty_value pub = pub_form.save(commit=False) self.assertEqual(pub.mode, default_mode) def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("active",) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields["active"].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field("active").get_default(), True) def test_default_not_populated_on_checkboxselectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data doesn't use the model default because an unchecked # CheckboxSelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") def test_default_not_populated_on_selectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.SelectMultiple) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data doesn't use the model default because an unselected # SelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") def test_prefixed_form_with_default_field(self): class PubForm(forms.ModelForm): prefix = "form-prefix" class Meta: model = PublicationDefaults fields = ("mode",) mode = "de" self.assertNotEqual( mode, PublicationDefaults._meta.get_field("mode").get_default() ) mf1 = PubForm({"form-prefix-mode": mode}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, mode) def test_renderer_kwarg(self): custom = object() self.assertIs(ProductForm(renderer=custom).renderer, custom) def test_default_splitdatetime_field(self): class PubForm(forms.ModelForm): datetime_published = forms.SplitDateTimeField(required=False) class Meta: model = PublicationDefaults fields = ("datetime_published",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1)) mf2 = PubForm( {"datetime_published_0": "2010-01-01", "datetime_published_1": "0:00:00"} ) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1)) def test_default_filefield(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("file",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.file.name, "default.txt") mf2 = PubForm({}, {"file": SimpleUploadedFile("name", b"foo")}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.file.name, "name") def test_default_selectdatewidget(self): class PubForm(forms.ModelForm): date_published = forms.DateField( required=False, widget=forms.SelectDateWidget ) class Meta: model = PublicationDefaults fields = ("date_published",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.date_published, datetime.date.today()) mf2 = PubForm( { "date_published_year": "2010", "date_published_month": "1", "date_published_day": "1", } ) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) # RemovedInDjango60Warning. # It's a temporary workaround for the deprecation period. class HttpsURLField(forms.URLField): def __init__(self, **kwargs): super().__init__(assume_scheme="https", **kwargs) class FieldOverridesByFormMetaForm(forms.ModelForm): class Meta: model = Category fields = ["name", "url", "slug"] widgets = { "name": forms.Textarea, "url": forms.TextInput(attrs={"class": "url"}), } labels = { "name": "Title", } help_texts = { "slug": "Watch out! Letters, numbers, underscores and hyphens only.", } error_messages = { "slug": { "invalid": ( "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!" ) } } field_classes = { "url": HttpsURLField, } class TestFieldOverridesByFormMeta(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form["name"]), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" ' "required></textarea>", ) self.assertHTMLEqual( str(form["url"]), '<input id="id_url" type="text" class="url" name="url" maxlength="40" ' "required>", ) self.assertHTMLEqual( str(form["slug"]), '<input id="id_slug" type="text" name="slug" maxlength="20" required>', ) def test_label_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form["name"].label_tag()), '<label for="id_name">Title:</label>', ) self.assertHTMLEqual( str(form["url"].label_tag()), '<label for="id_url">The URL:</label>', ) self.assertHTMLEqual( str(form["slug"].label_tag()), '<label for="id_slug">Slug:</label>', ) self.assertHTMLEqual( form["name"].legend_tag(), '<legend for="id_name">Title:</legend>', ) self.assertHTMLEqual( form["url"].legend_tag(), '<legend for="id_url">The URL:</legend>', ) self.assertHTMLEqual( form["slug"].legend_tag(), '<legend for="id_slug">Slug:</legend>', ) def test_help_text_overrides(self): form = FieldOverridesByFormMetaForm() self.assertEqual( form["slug"].help_text, "Watch out! Letters, numbers, underscores and hyphens only.", ) def test_error_messages_overrides(self): form = FieldOverridesByFormMetaForm( data={ "name": "Category", "url": "http://www.example.com/category/", "slug": "!%#*@", } ) form.full_clean() error = [ "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!", ] self.assertEqual(form.errors, {"slug": error}) def test_field_type_overrides(self): form = FieldOverridesByFormMetaForm() self.assertIs(Category._meta.get_field("url").__class__, models.CharField) self.assertIsInstance(form.fields["url"], forms.URLField) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ("name", "slug") model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ["url"] model = Category class ValidationTest(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) self.assertIs(form.is_valid(), True) class UniqueTest(TestCase): """ unique/unique_together validation. """ @classmethod def setUpTestData(cls): cls.writer = Writer.objects.create(name="Mike Royko") def test_simple_unique(self): form = ProductForm({"slug": "teddy-bear-blue"}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({"slug": "teddy-bear-blue"}) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["slug"], ["Product with this Slug already exists."] ) form = ProductForm({"slug": "teddy-bear-blue"}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({"price": "6.00", "quantity": "1"}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({"price": "6.00", "quantity": "1"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Price with this Price and Quantity already exists."], ) def test_unique_together_exclusion(self): """ Forms don't validate unique_together constraints when only part of the constraint is included in the form's fields. This allows using form.save(commit=False) and then assigning the missing field(s) to the model instance. """ class BookForm(forms.ModelForm): class Meta: model = DerivedBook fields = ("isbn", "suffix1") # The unique_together is on suffix1/suffix2 but only suffix1 is part # of the form. The fields must have defaults, otherwise they'll be # skipped by other logic. self.assertEqual(DerivedBook._meta.unique_together, (("suffix1", "suffix2"),)) for name in ("suffix1", "suffix2"): with self.subTest(name=name): field = DerivedBook._meta.get_field(name) self.assertEqual(field.default, 0) # The form fails validation with "Derived book with this Suffix1 and # Suffix2 already exists." if the unique_together validation isn't # skipped. DerivedBook.objects.create(isbn="12345") form = BookForm({"isbn": "56789", "suffix1": "0"}) self.assertTrue(form.is_valid(), form.errors) def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ class TripleForm(forms.ModelForm): class Meta: model = Triple fields = "__all__" Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({"left": "1", "middle": "2", "right": "3"}) self.assertFalse(form.is_valid()) form = TripleForm({"left": "1", "middle": "3", "right": "1"}) self.assertTrue(form.is_valid()) @skipUnlessDBFeature("supports_nullable_unique_constraints") def test_unique_null(self): title = "I May Be Wrong But I Doubt It" form = BookForm({"title": title, "author": self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({"title": title, "author": self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Book with this Title and Author already exists."] ) form = BookForm({"title": title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({"title": title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = "Boss" Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "special_id": "1", "isbn": "12345", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["special_id"], ["Book with this Special id already exists."] ) def test_inherited_unique_together(self): title = "Boss" form = BookForm({"title": title, "author": self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm( {"title": title, "author": self.writer.pk, "isbn": "12345"} ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Book with this Title and Author already exists."] ) def test_abstract_inherited_unique(self): title = "Boss" isbn = "12345" DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "isbn": isbn, "suffix1": "1", "suffix2": "2", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["isbn"], ["Derived book with this Isbn already exists."] ) def test_abstract_inherited_unique_together(self): title = "Boss" isbn = "12345" DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "isbn": "9876", "suffix1": "0", "suffix2": "0", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Derived book with this Suffix1 and Suffix2 already exists."], ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({"key": "", "desc": ""}) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({"key": "key1", "desc": ""}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({"key": "key1", "desc": ""}) self.assertFalse(form.is_valid()) if connection.features.interprets_empty_strings_as_nulls: self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["key"], ["Explicit pk with this Key already exists."] ) else: self.assertEqual(len(form.errors), 3) self.assertEqual( form.errors["__all__"], ["Explicit pk with this Key and Desc already exists."], ) self.assertEqual( form.errors["desc"], ["Explicit pk with this Desc already exists."] ) self.assertEqual( form.errors["key"], ["Explicit pk with this Key already exists."] ) def test_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-03"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Title must be unique for Posted date."] ) form = PostForm({"title": "Work on Django 1.1 begins", "posted": "2008-09-03"}) self.assertTrue(form.is_valid()) form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-04"}) self.assertTrue(form.is_valid()) form = PostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."]) form = PostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["subtitle"], ["Subtitle must be unique for Posted month."] ) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", "posted": "2008-09-03", } form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({"title": "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["posted"], ["This field is required."]) def test_unique_for_date_in_exclude(self): """ If the date for unique_for_* constraints is excluded from the ModelForm (in this case 'posted' has editable=False, then the constraint should be ignored. """ class DateTimePostForm(forms.ModelForm): class Meta: model = DateTimePost fields = "__all__" DateTimePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), ) # 'title' has unique_for_date='posted' form = DateTimePostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertTrue(form.is_valid()) # 'slug' has unique_for_year='posted' form = DateTimePostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertTrue(form.is_valid()) # 'subtitle' has unique_for_month='posted' form = DateTimePostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = DerivedPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Title must be unique for Posted date."] ) form = DerivedPostForm( {"title": "Work on Django 1.1 begins", "posted": "2008-09-03"} ) self.assertTrue(form.is_valid()) form = DerivedPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-04"} ) self.assertTrue(form.is_valid()) form = DerivedPostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."]) form = DerivedPostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["subtitle"], ["Subtitle must be unique for Posted month."] ) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", "posted": "2008-09-03", } form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): class FlexDatePostForm(forms.ModelForm): class Meta: model = FlexibleDatePost fields = "__all__" p = FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = FlexDatePostForm({"title": "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({"slug": "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({"subtitle": "Finally"}) self.assertTrue(form.is_valid()) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", } form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): class CustomProductForm(ProductForm): class Meta(ProductForm.Meta): error_messages = { "slug": { "unique": "%(model_name)s's %(field_label)s not unique.", } } Product.objects.create(slug="teddy-bear-blue") form = CustomProductForm({"slug": "teddy-bear-blue"}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Product's Slug not unique."]) def test_override_unique_together_message(self): class CustomPriceForm(PriceForm): class Meta(PriceForm.Meta): error_messages = { NON_FIELD_ERRORS: { "unique_together": ( "%(model_name)s's %(field_labels)s not unique." ), } } Price.objects.create(price=6.00, quantity=1) form = CustomPriceForm({"price": "6.00", "quantity": "1"}) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."] ) def test_override_unique_for_date_message(self): class CustomPostForm(PostForm): class Meta(PostForm.Meta): error_messages = { "title": { "unique_for_date": ( "%(model_name)s's %(field_label)s not unique " "for %(date_field_label)s date." ), } } Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = CustomPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Post's Title not unique for Posted date."] ) class ModelFormBasicTests(TestCase): def create_basic_data(self): self.c1 = Category.objects.create( name="Entertainment", slug="entertainment", url="entertainment" ) self.c2 = Category.objects.create( name="It's a test", slug="its-test", url="test" ) self.c3 = Category.objects.create( name="Third test", slug="third-test", url="third" ) self.w_royko = Writer.objects.create(name="Mike Royko") self.w_woodward = Writer.objects.create(name="Bob Woodward") def test_base_form(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm() self.assertHTMLEqual( str(f), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'maxlength="20" required id="id_name"></div><div><label for="id_slug">Slug:' '</label><input type="text" name="slug" maxlength="20" required ' 'id="id_slug"></div><div><label for="id_url">The URL:</label>' '<input type="text" name="url" maxlength="40" required id="id_url"></div>', ) self.assertHTMLEqual( str(f.as_ul()), """ <li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li> """, ) self.assertHTMLEqual( str(f["name"]), """<input id="id_name" type="text" name="name" maxlength="20" required>""", ) def test_auto_id(self): f = BaseCategoryForm(auto_id=False) self.assertHTMLEqual( str(f.as_ul()), """<li>Name: <input type="text" name="name" maxlength="20" required></li> <li>Slug: <input type="text" name="slug" maxlength="20" required></li> <li>The URL: <input type="text" name="url" maxlength="40" required></li>""", ) def test_initial_values(self): self.create_basic_data() # Initial values can be provided for model forms f = ArticleForm( auto_id=False, initial={ "headline": "Your headline here", "categories": [str(self.c1.id), str(self.c2.id)], }, ) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s" selected>It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) # When the ModelForm is passed an instance, that instance's current values are # inserted as 'initial' data in each Field. f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), '<div>Name:<div class="helptext">Use both first and last names.</div>' '<input type="text" name="name" value="Mike Royko" maxlength="50" ' "required></div>", ) art = Article.objects.create( headline="Test article", slug="test-article", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, article="Hello.", ) art_id_1 = art.id f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) f = ArticleForm( { "headline": "Test headline", "slug": "test-headline", "pub_date": "1984-02-06", "writer": str(self.w_royko.pk), "article": "Hello.", }, instance=art, ) self.assertEqual(f.errors, {}) self.assertTrue(f.is_valid()) test_art = f.save() self.assertEqual(test_art.id, art_id_1) test_art = Article.objects.get(id=art_id_1) self.assertEqual(test_art.headline, "Test headline") def test_m2m_initial_callable(self): """ A callable can be provided as the initial value for an m2m field. """ self.maxDiff = 1200 self.create_basic_data() # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == "categories": kwargs["initial"] = lambda: Category.objects.order_by("name")[:2] return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory( Article, fields=["headline", "categories"], formfield_callback=formfield_for_dbfield, ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" required></li> <li><label for="id_categories">Categories:</label> <select multiple name="categories" id="id_categories"> <option value="%d" selected>Entertainment</option> <option value="%d" selected>It&#x27;s a test</option> <option value="%d">Third test</option> </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk), ) def test_basic_creation(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm( { "name": "Entertainment", "slug": "entertainment", "url": "entertainment", } ) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["name"], "Entertainment") self.assertEqual(f.cleaned_data["slug"], "entertainment") self.assertEqual(f.cleaned_data["url"], "entertainment") c1 = f.save() # Testing whether the same object is returned from the # ORM... not the fastest way... self.assertEqual(Category.objects.count(), 1) self.assertEqual(c1, Category.objects.all()[0]) self.assertEqual(c1.name, "Entertainment") def test_save_commit_false(self): # If you call save() with commit=False, then it will return an object that # hasn't yet been saved to the database. In this case, it's up to you to call # save() on the resulting model instance. f = BaseCategoryForm( {"name": "Third test", "slug": "third-test", "url": "third"} ) self.assertTrue(f.is_valid()) c1 = f.save(commit=False) self.assertEqual(c1.name, "Third test") self.assertEqual(Category.objects.count(), 0) c1.save() self.assertEqual(Category.objects.count(), 1) def test_save_with_data_errors(self): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({"name": "", "slug": "not a slug!", "url": "foo"}) self.assertEqual(f.errors["name"], ["This field is required."]) self.assertEqual( f.errors["slug"], [ "Enter a valid “slug” consisting of letters, numbers, underscores or " "hyphens." ], ) self.assertEqual(f.cleaned_data, {"url": "foo"}) msg = "The Category could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): f.save() f = BaseCategoryForm({"name": "", "slug": "", "url": "foo"}) with self.assertRaisesMessage(ValueError, msg): f.save() def test_multi_fields(self): self.create_basic_data() self.maxDiff = None # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any # fields with the 'choices' attribute are represented by a ChoiceField. f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), """ <div>Headline: <input type="text" name="headline" maxlength="50" required> </div> <div>Slug: <input type="text" name="slug" maxlength="50" required> </div> <div>Pub date: <input type="text" name="pub_date" required> </div> <div>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select> </div> <div>Article: <textarea name="article" cols="40" rows="10" required></textarea> </div> <div>Categories: <select name="categories" multiple> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </div> <div>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option><option value="2">Pending</option> <option value="3">Live</option> </select> </div> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) # Add some categories and test the many-to-many form output. new_art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, ) new_art.categories.add(Category.objects.get(name="Entertainment")) self.assertSequenceEqual(new_art.categories.all(), [self.c1]) f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) def test_subset_fields(self): # You can restrict a form to a subset of the complete list of fields # by providing a 'fields' argument. If you try to save a # model created with such a form, you need to ensure that the fields # that are _not_ on the form have default values, or are allowed to have # a value of None. If a field isn't specified on a form, the object created # from the form can't provide a value for that field! class PartialArticleForm(forms.ModelForm): class Meta: model = Article fields = ("headline", "pub_date") f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '<div>Headline:<input type="text" name="headline" maxlength="50" required>' '</div><div>Pub date:<input type="text" name="pub_date" required></div>', ) class PartialArticleFormWithSlug(forms.ModelForm): class Meta: model = Article fields = ("headline", "slug", "pub_date") w_royko = Writer.objects.create(name="Mike Royko") art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=w_royko, ) f = PartialArticleFormWithSlug( { "headline": "New headline", "slug": "new-headline", "pub_date": "1988-01-04", }, auto_id=False, instance=art, ) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> """, ) self.assertTrue(f.is_valid()) new_art = f.save() self.assertEqual(new_art.id, art.id) new_art = Article.objects.get(id=art.id) self.assertEqual(new_art.headline, "New headline") def test_m2m_editing(self): self.create_basic_data() form_data = { "headline": "New headline", "slug": "new-headline", "pub_date": "1988-01-04", "writer": str(self.w_royko.pk), "article": "Hello.", "categories": [str(self.c1.id), str(self.c2.id)], } # Create a new article, with categories, via the form. f = ArticleForm(form_data) new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id self.assertSequenceEqual( new_art.categories.order_by("name"), [self.c1, self.c2] ) # Now, submit form data with no categories. This deletes the existing # categories. form_data["categories"] = [] f = ArticleForm(form_data, instance=new_art) new_art = f.save() self.assertEqual(new_art.id, art_id_1) new_art = Article.objects.get(id=art_id_1) self.assertSequenceEqual(new_art.categories.all(), []) # Create a new article, with no categories, via the form. f = ArticleForm(form_data) new_art = f.save() art_id_2 = new_art.id self.assertNotIn(art_id_2, (None, art_id_1)) new_art = Article.objects.get(id=art_id_2) self.assertSequenceEqual(new_art.categories.all(), []) # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. form_data["categories"] = [str(self.c1.id), str(self.c2.id)] f = ArticleForm(form_data) new_art = f.save(commit=False) # Manually save the instance new_art.save() art_id_3 = new_art.id self.assertNotIn(art_id_3, (None, art_id_1, art_id_2)) # The instance doesn't have m2m data yet new_art = Article.objects.get(id=art_id_3) self.assertSequenceEqual(new_art.categories.all(), []) # Save the m2m data on the form f.save_m2m() self.assertSequenceEqual( new_art.categories.order_by("name"), [self.c1, self.c2] ) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the # same fields as the Category model, we can just call the form's save() # to apply its changes to an existing Category instance. class ShortCategory(forms.ModelForm): name = forms.CharField(max_length=5) slug = forms.CharField(max_length=5) url = forms.CharField(max_length=3) class Meta: model = Category fields = "__all__" cat = Category.objects.create(name="Third test") form = ShortCategory( {"name": "Third", "slug": "third", "url": "3rd"}, instance=cat ) self.assertEqual(form.save().name, "Third") self.assertEqual(Category.objects.get(id=cat.id).name, "Third") def test_runtime_choicefield_populated(self): self.maxDiff = None # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined # at runtime, based on the data in the database when the form is displayed, not # the data in the database when the form is instantiated. self.create_basic_data() f = ArticleForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), '<li>Headline: <input type="text" name="headline" maxlength="50" required>' "</li>" '<li>Slug: <input type="text" name="slug" maxlength="50" required></li>' '<li>Pub date: <input type="text" name="pub_date" required></li>' '<li>Writer: <select name="writer" required>' '<option value="" selected>---------</option>' '<option value="%s">Bob Woodward</option>' '<option value="%s">Mike Royko</option>' "</select></li>" '<li>Article: <textarea rows="10" cols="40" name="article" required>' "</textarea></li>" '<li>Categories: <select multiple name="categories">' '<option value="%s">Entertainment</option>' '<option value="%s">It&#x27;s a test</option>' '<option value="%s">Third test</option>' "</select> </li>" '<li>Status: <select name="status">' '<option value="" selected>---------</option>' '<option value="1">Draft</option>' '<option value="2">Pending</option>' '<option value="3">Live</option>' "</select></li>" % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) c4 = Category.objects.create(name="Fourth", url="4th") w_bernstein = Writer.objects.create(name="Carl Bernstein") self.assertHTMLEqual( f.as_ul(), '<li>Headline: <input type="text" name="headline" maxlength="50" required>' "</li>" '<li>Slug: <input type="text" name="slug" maxlength="50" required></li>' '<li>Pub date: <input type="text" name="pub_date" required></li>' '<li>Writer: <select name="writer" required>' '<option value="" selected>---------</option>' '<option value="%s">Bob Woodward</option>' '<option value="%s">Carl Bernstein</option>' '<option value="%s">Mike Royko</option>' "</select></li>" '<li>Article: <textarea rows="10" cols="40" name="article" required>' "</textarea></li>" '<li>Categories: <select multiple name="categories">' '<option value="%s">Entertainment</option>' '<option value="%s">It&#x27;s a test</option>' '<option value="%s">Third test</option>' '<option value="%s">Fourth</option>' "</select></li>" '<li>Status: <select name="status">' '<option value="" selected>---------</option>' '<option value="1">Draft</option>' '<option value="2">Pending</option>' '<option value="3">Live</option>' "</select></li>" % ( self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk, ), ) def test_recleaning_model_form_instance(self): """ Re-cleaning an instance that was added via a ModelForm shouldn't raise a pk uniqueness error. """ class AuthorForm(forms.ModelForm): class Meta: model = Author fields = "__all__" form = AuthorForm({"full_name": "Bob"}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = "Alice" obj.full_clean() def test_validate_foreign_key_uses_default_manager(self): class MyForm(forms.ModelForm): class Meta: model = Article fields = "__all__" # Archived writers are filtered out by the default manager. w = Writer.objects.create(name="Randy", archived=True) data = { "headline": "My Article", "slug": "my-article", "pub_date": datetime.date.today(), "writer": w.pk, "article": "lorem ipsum", } form = MyForm(data) self.assertIs(form.is_valid(), False) self.assertEqual( form.errors, { "writer": [ "Select a valid choice. That choice is not one of the available " "choices." ] }, ) def test_validate_foreign_key_to_model_with_overridden_manager(self): class MyForm(forms.ModelForm): class Meta: model = Article fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Allow archived authors. self.fields["writer"].queryset = Writer._base_manager.all() w = Writer.objects.create(name="Randy", archived=True) data = { "headline": "My Article", "slug": "my-article", "pub_date": datetime.date.today(), "writer": w.pk, "article": "lorem ipsum", } form = MyForm(data) self.assertIs(form.is_valid(), True) article = form.save() self.assertEqual(article.writer, w) class ModelMultipleChoiceFieldTests(TestCase): @classmethod def setUpTestData(cls): cls.c1 = Category.objects.create( name="Entertainment", slug="entertainment", url="entertainment" ) cls.c2 = Category.objects.create( name="It's a test", slug="its-test", url="test" ) cls.c3 = Category.objects.create(name="Third", slug="third-test", url="third") def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertCountEqual( list(f.choices), [ (self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test"), (self.c3.pk, "Third"), ], ) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): f.clean([]) self.assertCountEqual(f.clean([self.c1.id]), [self.c1]) self.assertCountEqual(f.clean([self.c2.id]), [self.c2]) self.assertCountEqual(f.clean([str(self.c1.id)]), [self.c1]) self.assertCountEqual( f.clean([str(self.c1.id), str(self.c2.id)]), [self.c1, self.c2], ) self.assertCountEqual( f.clean([self.c1.id, str(self.c2.id)]), [self.c1, self.c2], ) self.assertCountEqual( f.clean((self.c1.id, str(self.c2.id))), [self.c1, self.c2], ) with self.assertRaises(ValidationError): f.clean(["0"]) with self.assertRaises(ValidationError): f.clean("hello") with self.assertRaises(ValidationError): f.clean(["fail"]) # Invalid types that require TypeError to be caught (#22808). with self.assertRaises(ValidationError): f.clean([["fail"]]) with self.assertRaises(ValidationError): f.clean([{"foo": "bar"}]) # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. # Note, we are using an id of 1006 here since tests that run before # this may create categories with primary keys up to 6. Use # a number that will not conflict. c6 = Category.objects.create(id=1006, name="Sixth", url="6th") self.assertCountEqual(f.clean([c6.id]), [c6]) # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. Category.objects.get(url="6th").delete() with self.assertRaises(ValidationError): f.clean([c6.id]) def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(["0"]) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), "0"]) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), "0"]) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name="Third") self.assertCountEqual( list(f.choices), [(self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test")], ) self.assertSequenceEqual(f.clean([self.c2.id]), [self.c2]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertCountEqual( list(f.choices), [ (self.c1.pk, "multicategory Entertainment"), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, "multicategory Third"), ], ) def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField( queryset=Writer.objects.all(), validators=[my_validator] ) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) def test_model_multiple_choice_show_hidden_initial(self): """ Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all() ) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") form = WriterForm( initial={"persons": [person1, person2]}, data={ "initial-persons": [str(person1.pk), str(person2.pk)], "persons": [str(person1.pk), str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertFalse(form.has_changed()) form = WriterForm( initial={"persons": [person1, person2]}, data={ "initial-persons": [str(person1.pk), str(person2.pk)], "persons": [str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertTrue(form.has_changed()) def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField( Category.objects.all(), widget=forms.CheckboxSelectMultiple ) form = ModelMultipleChoiceForm() field = form["categories"] # BoundField template = Template("{{ field.name }}{{ field }}{{ field.help_text }}") with self.assertNumQueries(1): template.render(Context({"field": field})) def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all() ) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={"initial-persons": writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed()) def test_clean_does_deduplicate_values(self): class PersonForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) person1 = Person.objects.create(name="Person 1") form = PersonForm(data={}) queryset = form.fields["persons"].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1) def test_to_field_name_with_initial_data(self): class ArticleCategoriesForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField( Category.objects.all(), to_field_name="slug" ) class Meta: model = Article fields = ["categories"] article = Article.objects.create( headline="Test article", slug="test-article", pub_date=datetime.date(1988, 1, 4), writer=Writer.objects.create(name="Test writer"), article="Hello.", ) article.categories.add(self.c2, self.c3) form = ArticleCategoriesForm(instance=article) self.assertCountEqual(form["categories"].value(), [self.c2.slug, self.c3.slug]) class ModelOneToOneFieldTests(TestCase): def test_modelform_onetoonefield(self): class ImprovedArticleForm(forms.ModelForm): class Meta: model = ImprovedArticle fields = "__all__" class ImprovedArticleWithParentLinkForm(forms.ModelForm): class Meta: model = ImprovedArticleWithParentLink fields = "__all__" self.assertEqual(list(ImprovedArticleForm.base_fields), ["article"]) self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), []) def test_modelform_subclassed_model(self): class BetterWriterForm(forms.ModelForm): class Meta: # BetterWriter model is a subclass of Writer with an additional # `score` field. model = BetterWriter fields = "__all__" bw = BetterWriter.objects.create(name="Joe Better", score=10) self.assertEqual( sorted(model_to_dict(bw)), ["id", "name", "score", "writer_ptr"] ) self.assertEqual(sorted(model_to_dict(bw, fields=[])), []) self.assertEqual( sorted(model_to_dict(bw, fields=["id", "name"])), ["id", "name"] ) self.assertEqual( sorted(model_to_dict(bw, exclude=[])), ["id", "name", "score", "writer_ptr"] ) self.assertEqual( sorted(model_to_dict(bw, exclude=["id", "name"])), ["score", "writer_ptr"] ) form = BetterWriterForm({"name": "Some Name", "score": 12}) self.assertTrue(form.is_valid()) bw2 = form.save() self.assertEqual(bw2.score, 12) def test_onetoonefield(self): class WriterProfileForm(forms.ModelForm): class Meta: # WriterProfile has a OneToOneField to Writer model = WriterProfile fields = "__all__" self.w_royko = Writer.objects.create(name="Mike Royko") self.w_woodward = Writer.objects.create(name="Bob Woodward") form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), """ <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p> """ % ( self.w_woodward.pk, self.w_royko.pk, ), ) data = { "writer": str(self.w_woodward.pk), "age": "65", } form = WriterProfileForm(data) instance = form.save() self.assertEqual(str(instance), "Bob Woodward is 65") form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="">---------</option> <option value="%s" selected>Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" required> </p>""" % ( self.w_woodward.pk, self.w_royko.pk, ), ) def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ["publication", "full_name"] publication = Publication.objects.create( title="Pravda", date_published=datetime.date(1991, 8, 22) ) author = Author.objects.create(publication=publication, full_name="John Doe") form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author) self.assertTrue(form.is_valid()) self.assertIsNone(form.cleaned_data["publication"]) author = form.save() # author object returned from form still retains original publication object # that's why we need to retrieve it from database again new_author = Author.objects.get(pk=author.pk) self.assertIsNone(new_author.publication) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ["publication", "full_name"] publication = Publication.objects.create( title="Pravda", date_published=datetime.date(1991, 8, 22) ) author = Author1.objects.create(publication=publication, full_name="John Doe") form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author) self.assertFalse(form.is_valid()) class FileAndImageFieldTests(TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, "initial"), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, "initial"), "initial") with self.assertRaises(ValidationError): f.clean(False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn("myfile-clear", str(form)) form = DocumentForm( files={"myfile": SimpleUploadedFile("something.txt", b"content")} ) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, "something.txt") form = DocumentForm(instance=doc) self.assertIn("myfile-clear", str(form)) form = DocumentForm(instance=doc, data={"myfile-clear": "true"}) doc = form.save(commit=False) self.assertFalse(doc.myfile) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" form = DocumentForm( files={"myfile": SimpleUploadedFile("something.txt", b"content")} ) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm( instance=doc, files={"myfile": SimpleUploadedFile("something.txt", b"content")}, data={"myfile-clear": "true"}, ) self.assertTrue(not form.is_valid()) self.assertEqual( form.errors["myfile"], ["Please either submit a file or check the clear checkbox, not both."], ) rendered = str(form) self.assertIn("something.txt", rendered) self.assertIn("myfile-clear", rendered) def test_render_empty_file_field(self): class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" doc = Document.objects.create() form = DocumentForm(instance=doc) self.assertHTMLEqual( str(form["myfile"]), '<input id="id_myfile" name="myfile" type="file">' ) def test_file_field_data(self): # Test conditions when files is either not given or empty. f = TextFileForm(data={"description": "Assistance"}) self.assertFalse(f.is_valid()) f = TextFileForm(data={"description": "Assistance"}, files={}) self.assertFalse(f.is_valid()) # Upload a file and ensure it all works as expected. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test1.txt", b"hello world")}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") instance.file.delete() # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test1.txt", b"hello world")}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test-maxlength.txt", b"hello world")}, ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. f = TextFileForm({"description": "Assistance"}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["file"].name, "tests/test1.txt") instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") # Delete the current file since this is not done by Django. instance.file.delete() # Override the file by uploading a new one. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test2.txt", b"hello world")}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "tests/test2.txt") # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={"description": "Assistance"}) f.fields["file"].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "") f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test3.txt", b"hello world")}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "tests/test3.txt") # Instance can be edited w/out re-uploading the file and existing file # should be preserved. f = TextFileForm({"description": "New Description"}, instance=instance) f.fields["file"].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, "New Description") self.assertEqual(instance.file.name, "tests/test3.txt") # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_custom_file_field_save(self): """ Regression for #11149: save_form_data should be called only once """ class CFFForm(forms.ModelForm): class Meta: model = CustomFF fields = "__all__" # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data={"f": None}) form.save() def test_file_field_multiple_save(self): """ Simulate a file upload and check how many times Model.save() gets called. Test for bug #639. """ class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = "__all__" # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.png") with open(filename, "rb") as fp: img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {"title": "Testing"} files = {"image": SimpleUploadedFile("test.png", img, "image/png")} form = PhotoForm(data=data, files=files) p = form.save() try: # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) finally: # Delete the "uploaded" file to avoid clogging /tmp. p = Photo.objects.get() p.image.delete(save=False) def test_file_path_field_blank(self): """FilePathField(blank=True) includes the empty option.""" class FPForm(forms.ModelForm): class Meta: model = FilePathModel fields = "__all__" form = FPForm() self.assertEqual( [name for _, name in form["path"].field.choices], ["---------", "models.py"] ) @skipUnless(test_images, "Pillow not installed") def test_image_field(self): # ImageField and FileField are nearly identical, but they differ slightly when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. with open(os.path.join(os.path.dirname(__file__), "test.png"), "rb") as fp: image_data = fp.read() with open(os.path.join(os.path.dirname(__file__), "test2.png"), "rb") as fp: image_data2 = fp.read() f = ImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Edit an instance that already has the (required) image defined in the # model. This will not save the image again, but leave it exactly as it # is. f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["image"].name, "tests/test.png") instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.height, 16) self.assertEqual(instance.width, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) # Override the file by uploading a new one. f = ImageFileForm( data={"description": "Changed it"}, files={"image": SimpleUploadedFile("test2.png", image_data2)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test2.png") self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() f = ImageFileForm( data={"description": "Changed it"}, files={"image": SimpleUploadedFile("test2.png", image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test2.png") self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() # Test the non-required ImageField # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_imagefield_repr = "" else: expected_null_imagefield_repr = None f = OptionalImageFileForm(data={"description": "Test"}) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertIsNone(instance.width) self.assertIsNone(instance.height) f = OptionalImageFileForm( data={"description": "And a final one"}, files={"image": SimpleUploadedFile("test3.png", image_data)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test3.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. f = OptionalImageFileForm({"description": "New Description"}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, "New Description") self.assertEqual(instance.image.name, "tests/test3.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django. instance.image.delete() instance.delete() f = OptionalImageFileForm( data={"description": "And a final one"}, files={"image": SimpleUploadedFile("test4.png", image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test4.png") self.assertEqual(instance.width, 48) self.assertEqual(instance.height, 32) instance.delete() # Callable upload_to behavior that's dependent on the value of another # field in the model. f = ImageFileForm( data={"description": "And a final one", "path": "foo"}, files={"image": SimpleUploadedFile("test4.png", image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "foo/test4.png") instance.delete() # Editing an instance that has an image without an extension shouldn't # fail validation. First create: f = NoExtensionImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/no_extension") # Then edit: f = NoExtensionImageFileForm( data={"description": "Edited image"}, instance=instance ) self.assertTrue(f.is_valid()) class ModelOtherFieldTests(SimpleTestCase): def test_big_integer_field(self): bif = BigIntForm({"biggie": "-9223372036854775808"}) self.assertTrue(bif.is_valid()) bif = BigIntForm({"biggie": "-9223372036854775809"}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, { "biggie": [ "Ensure this value is greater than or equal to " "-9223372036854775808." ] }, ) bif = BigIntForm({"biggie": "9223372036854775807"}) self.assertTrue(bif.is_valid()) bif = BigIntForm({"biggie": "9223372036854775808"}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, { "biggie": [ "Ensure this value is less than or equal to 9223372036854775807." ] }, ) @ignore_warnings(category=RemovedInDjango60Warning) def test_url_on_modelform(self): "Check basic URL field validation on model forms" class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = "__all__" self.assertFalse(HomepageForm({"url": "foo"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://example"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://example."}).is_valid()) self.assertFalse(HomepageForm({"url": "http://com."}).is_valid()) self.assertTrue(HomepageForm({"url": "http://localhost"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://example.com"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com:8000"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com/test"}).is_valid()) self.assertTrue( HomepageForm({"url": "http://www.example.com:8000/test"}).is_valid() ) self.assertTrue(HomepageForm({"url": "http://example.com/foo/bar"}).is_valid()) def test_url_modelform_assume_scheme_warning(self): msg = ( "The default scheme will be changed from 'http' to 'https' in Django " "6.0. Pass the forms.URLField.assume_scheme argument to silence this " "warning." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = "__all__" def test_modelform_non_editable_field(self): """ When explicitly including a non-editable field in a ModelForm, the error message should be explicit. """ # 'created', non-editable, is excluded by default self.assertNotIn("created", ArticleForm().fields) msg = ( "'created' cannot be specified for Article model form as it is a " "non-editable field" ) with self.assertRaisesMessage(FieldError, msg): class InvalidArticleForm(forms.ModelForm): class Meta: model = Article fields = ("headline", "created") def test_https_prefixing(self): """ If the https:// prefix is omitted on form input, the field adds it again. """ class HomepageForm(forms.ModelForm): # RemovedInDjango60Warning. url = forms.URLField(assume_scheme="https") class Meta: model = Homepage fields = "__all__" form = HomepageForm({"url": "example.com"}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["url"], "https://example.com") form = HomepageForm({"url": "example.com/test"}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["url"], "https://example.com/test") class OtherModelFormTests(TestCase): def test_media_on_modelform(self): # Similar to a regular Form class you can define custom media to be used on # the ModelForm. f = ModelFormWithMedia() self.assertHTMLEqual( str(f.media), '<link href="/some/form/css" media="all" rel="stylesheet">' '<script src="/some/form/javascript"></script>', ) def test_choices_type(self): # Choices on CharField and IntegerField f = ArticleForm() with self.assertRaises(ValidationError): f.fields["status"].clean("42") f = ArticleStatusForm() with self.assertRaises(ValidationError): f.fields["status"].clean("z") def test_prefetch_related_queryset(self): """ ModelChoiceField should respect a prefetch_related() on its queryset. """ blue = Colour.objects.create(name="blue") red = Colour.objects.create(name="red") multicolor_item = ColourfulItem.objects.create() multicolor_item.colours.add(blue, red) red_item = ColourfulItem.objects.create() red_item.colours.add(red) class ColorModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return ", ".join(c.name for c in obj.colours.all()) field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related("colours")) with self.assertNumQueries(3): # would be 4 if prefetch is ignored self.assertEqual( tuple(field.choices), ( ("", "---------"), (multicolor_item.pk, "blue, red"), (red_item.pk, "red"), ), ) def test_foreignkeys_which_use_to_field(self): apple = Inventory.objects.create(barcode=86, name="Apple") pear = Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name="barcode") self.assertEqual( tuple(field.choices), (("", "---------"), (86, "Apple"), (87, "Core"), (22, "Pear")), ) form = InventoryForm(instance=core) self.assertHTMLEqual( str(form["parent"]), """<select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected>Apple</option> <option value="87">Core</option> <option value="22">Pear</option> </select>""", ) data = model_to_dict(core) data["parent"] = "22" form = InventoryForm(data=data, instance=core) core = form.save() self.assertEqual(core.parent.name, "Pear") class CategoryForm(forms.ModelForm): description = forms.CharField() class Meta: model = Category fields = ["description", "url"] self.assertEqual(list(CategoryForm.base_fields), ["description", "url"]) self.assertHTMLEqual( str(CategoryForm()), '<div><label for="id_description">Description:</label><input type="text" ' 'name="description" required id="id_description"></div><div>' '<label for="id_url">The URL:</label><input type="text" name="url" ' 'maxlength="40" required id="id_url"></div>', ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField( Inventory.objects.all(), to_field_name="barcode" ) self.assertEqual( tuple(field.choices), ((86, "Apple"), (87, "Core"), (22, "Pear")) ) self.assertSequenceEqual(field.clean([86]), [apple]) form = SelectInventoryForm({"items": [87, 22]}) self.assertTrue(form.is_valid()) self.assertEqual(len(form.cleaned_data), 1) self.assertSequenceEqual(form.cleaned_data["items"], [core, pear]) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ["name"]) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '<div><label for="id_name">Name:</label><input type="text" ' 'name="name" maxlength="10" required id="id_name"></div>', ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): class Meta: model = ColourfulItem fields = "__all__" colour = Colour.objects.create(name="Blue") form = ColourfulItemForm() self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), """ <p> <label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p> <p><label for="id_colours">Colours:</label> <select multiple name="colours" id="id_colours" required> <option value="%(blue_pk)s">Blue</option> </select></p> """ % {"blue_pk": colour.pk}, ) def test_callable_field_default(self): class PublicationDefaultsForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("title", "date_published", "mode", "category") self.maxDiff = 2000 form = PublicationDefaultsForm() today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_title">Title:</label> <input id="id_title" maxlength="30" name="title" type="text" required> </p> <p><label for="id_date_published">Date published:</label> <input id="id_date_published" name="date_published" type="text" value="{0}" required> <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"> </p> <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode"> <option value="di" selected>direct</option> <option value="de">delayed</option></select> <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"> </p> <p> <label for="id_category">Category:</label> <select id="id_category" name="category"> <option value="1">Games</option> <option value="2">Comics</option> <option value="3" selected>Novel</option></select> <input id="initial-id_category" name="initial-category" type="hidden" value="3"> """.format( today_str ), ) empty_data = { "title": "", "date_published": today_str, "initial-date_published": today_str, "mode": "di", "initial-mode": "di", "category": "3", "initial-category": "3", } bound_form = PublicationDefaultsForm(empty_data) self.assertFalse(bound_form.has_changed()) class ModelFormCustomErrorTests(SimpleTestCase): def test_custom_error_messages(self): data = {"name1": "@#$!!**@#$", "name2": "@#$!!**@#$"} errors = CustomErrorMessageForm(data).errors self.assertHTMLEqual( str(errors["name1"]), '<ul class="errorlist"><li>Form custom error message.</li></ul>', ) self.assertHTMLEqual( str(errors["name2"]), '<ul class="errorlist"><li>Model custom error message.</li></ul>', ) def test_model_clean_error_messages(self): data = {"name1": "FORBIDDEN_VALUE", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors["name1"]), '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>', ) data = {"name1": "FORBIDDEN_VALUE2", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors["name1"]), '<ul class="errorlist">' "<li>Model.clean() error messages (simpler syntax).</li></ul>", ) data = {"name1": "GLOBAL_ERROR", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["__all__"], ["Global error message."]) class CustomCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple fields = "__all__" def clean(self): if not self.cleaned_data["left"] == self.cleaned_data["right"]: raise ValidationError("Left and right should be equal") return self.cleaned_data form = TripleFormWithCleanOverride({"left": 1, "middle": 2, "right": 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) def test_model_form_clean_applies_to_model(self): """ Regression test for #12960. Make sure the cleaned_data returned from ModelForm.clean() is applied to the model instance. """ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = "__all__" def clean(self): self.cleaned_data["name"] = self.cleaned_data["name"].upper() return self.cleaned_data data = {"name": "Test", "slug": "test", "url": "/test"} form = CategoryForm(data) category = form.save() self.assertEqual(category.name, "TEST") class ModelFormInheritanceTests(SimpleTestCase): def test_form_subclass_inheritance(self): class Form(forms.Form): age = forms.IntegerField() class ModelForm(forms.ModelForm, Form): class Meta: model = Writer fields = "__all__" self.assertEqual(list(ModelForm().fields), ["name", "age"]) def test_field_removal(self): class ModelForm(forms.ModelForm): class Meta: model = Writer fields = "__all__" class Mixin: age = None class Form(forms.Form): age = forms.IntegerField() class Form2(forms.Form): foo = forms.IntegerField() self.assertEqual(list(ModelForm().fields), ["name"]) self.assertEqual(list(type("NewForm", (Mixin, Form), {})().fields), []) self.assertEqual( list(type("NewForm", (Form2, Mixin, Form), {})().fields), ["foo"] ) self.assertEqual( list(type("NewForm", (Mixin, ModelForm, Form), {})().fields), ["name"] ) self.assertEqual( list(type("NewForm", (ModelForm, Mixin, Form), {})().fields), ["name"] ) self.assertEqual( list(type("NewForm", (ModelForm, Form, Mixin), {})().fields), ["name", "age"], ) self.assertEqual( list(type("NewForm", (ModelForm, Form), {"age": None})().fields), ["name"] ) def test_field_removal_name_clashes(self): """ Form fields can be removed in subclasses by setting them to None (#22510). """ class MyForm(forms.ModelForm): media = forms.CharField() class Meta: model = Writer fields = "__all__" class SubForm(MyForm): media = None self.assertIn("media", MyForm().fields) self.assertNotIn("media", SubForm().fields) self.assertTrue(hasattr(MyForm, "media")) self.assertTrue(hasattr(SubForm, "media")) class StumpJokeForm(forms.ModelForm): class Meta: model = StumpJoke fields = "__all__" class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field): queryset = 42 class StumpJokeWithCustomFieldForm(forms.ModelForm): custom = CustomFieldWithQuerysetButNoLimitChoicesTo() class Meta: model = StumpJoke fields = () class LimitChoicesToTests(TestCase): """ Tests the functionality of ``limit_choices_to``. """ @classmethod def setUpTestData(cls): cls.threepwood = Character.objects.create( username="threepwood", last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) cls.marley = Character.objects.create( username="marley", last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) def test_limit_choices_to_callable_for_fk_rel(self): """ A ForeignKey can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual( stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood] ) def test_limit_choices_to_callable_for_m2m_rel(self): """ A ManyToManyField can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual( stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood] ) def test_custom_field_with_queryset_but_no_limit_choices_to(self): """ A custom field with a `queryset` attribute but no `limit_choices_to` works (#23795). """ f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields["custom"].queryset, 42) def test_fields_for_model_applies_limit_choices_to(self): fields = fields_for_model(StumpJoke, ["has_fooled_today"]) self.assertSequenceEqual(fields["has_fooled_today"].queryset, [self.threepwood]) def test_callable_called_each_time_form_is_instantiated(self): field = StumpJokeForm.base_fields["most_recently_fooled"] with mock.patch.object(field, "limit_choices_to") as today_callable_dict: StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 1) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 2) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) @isolate_apps("model_forms") def test_limit_choices_to_no_duplicates(self): joke1 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.threepwood, ) joke2 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.threepwood, ) joke3 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.marley, ) StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley) joke1.has_fooled_today.add(self.marley, self.threepwood) joke2.has_fooled_today.add(self.marley) joke3.has_fooled_today.add(self.marley, self.threepwood) class CharacterDetails(models.Model): character1 = models.ForeignKey( Character, models.CASCADE, limit_choices_to=models.Q( jokes__funny=True, jokes_today__funny=True, ), related_name="details_fk_1", ) character2 = models.ForeignKey( Character, models.CASCADE, limit_choices_to={ "jokes__funny": True, "jokes_today__funny": True, }, related_name="details_fk_2", ) character3 = models.ManyToManyField( Character, limit_choices_to=models.Q( jokes__funny=True, jokes_today__funny=True, ), related_name="details_m2m_1", ) class CharacterDetailsForm(forms.ModelForm): class Meta: model = CharacterDetails fields = "__all__" form = CharacterDetailsForm() self.assertCountEqual( form.fields["character1"].queryset, [self.marley, self.threepwood], ) self.assertCountEqual( form.fields["character2"].queryset, [self.marley, self.threepwood], ) self.assertCountEqual( form.fields["character3"].queryset, [self.marley, self.threepwood], ) def test_limit_choices_to_m2m_through(self): class DiceForm(forms.ModelForm): class Meta: model = Dice fields = ["numbers"] Number.objects.create(value=0) n1 = Number.objects.create(value=1) n2 = Number.objects.create(value=2) form = DiceForm() self.assertCountEqual(form.fields["numbers"].queryset, [n1, n2]) class FormFieldCallbackTests(SimpleTestCase): def test_baseform_with_widgets_in_meta(self): """ Using base forms with widgets defined in Meta should not raise errors. """ widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {"name": widget} fields = "__all__" Form = modelform_factory(Person, form=BaseForm) self.assertIsInstance(Form.base_fields["name"].widget, forms.Textarea) def test_factory_with_widget_argument(self): """Regression for #15315: modelform_factory should accept widgets argument """ widget = forms.Textarea() # Without a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__") self.assertNotEqual(Form.base_fields["name"].widget.__class__, forms.Textarea) # With a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__", widgets={"name": widget}) self.assertEqual(Form.base_fields["name"].widget.__class__, forms.Textarea) def test_modelform_factory_without_fields(self): """Regression for #19733""" message = ( "Calling modelform_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelform_factory(Person) def test_modelform_factory_with_all_fields(self): """Regression for #19733""" form = modelform_factory(Person, fields="__all__") self.assertEqual(list(form.base_fields), ["name"]) def test_custom_callback(self): """A custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {"name": widget} fields = "__all__" modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual( callback_args, [(id_field, {}), (name_field, {"widget": widget})] ) def test_bad_callback(self): # A bad callback provided by user still gives an error with self.assertRaises(TypeError): modelform_factory( Person, fields="__all__", formfield_callback="not a function or callable", ) def test_inherit_after_custom_callback(self): def callback(db_field, **kwargs): if isinstance(db_field, models.CharField): return forms.CharField(widget=forms.Textarea) return db_field.formfield(**kwargs) class BaseForm(forms.ModelForm): class Meta: model = Person fields = "__all__" NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback) class InheritedForm(NewForm): pass for name in NewForm.base_fields: self.assertEqual( type(InheritedForm.base_fields[name].widget), type(NewForm.base_fields[name].widget), ) def test_custom_callback_in_meta(self): def callback(db_field, **kwargs): return forms.CharField(widget=forms.Textarea) class NewForm(forms.ModelForm): class Meta: model = Person fields = ["id", "name"] formfield_callback = callback for field in NewForm.base_fields.values(): self.assertEqual(type(field.widget), forms.Textarea) def test_custom_callback_from_base_form_meta(self): def callback(db_field, **kwargs): return forms.CharField(widget=forms.Textarea) class BaseForm(forms.ModelForm): class Meta: model = Person fields = "__all__" formfield_callback = callback NewForm = modelform_factory(model=Person, form=BaseForm) class InheritedForm(NewForm): pass for name, field in NewForm.base_fields.items(): self.assertEqual(type(field.widget), forms.Textarea) self.assertEqual( type(field.widget), type(InheritedForm.base_fields[name].widget), ) class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): class PartiallyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = ( "left", "right", ) fields = "__all__" f = PartiallyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields["left"].localize) self.assertFalse(f.fields["middle"].localize) self.assertTrue(f.fields["right"].localize) def test_model_form_applies_localize_to_all_fields(self): class FullyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "__all__" fields = "__all__" f = FullyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields["left"].localize) self.assertTrue(f.fields["middle"].localize) self.assertTrue(f.fields["right"].localize) def test_model_form_refuses_arbitrary_string(self): msg = ( "BrokenLocalizedTripleForm.Meta.localized_fields " "cannot be a string. Did you mean to type: ('foo',)?" ) with self.assertRaisesMessage(TypeError, msg): class BrokenLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "foo" class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass): pass class CustomMetaclassTestCase(SimpleTestCase): def test_modelform_factory_metaclass(self): new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm) self.assertEqual(new_cls.base_fields, {}) class StrictAssignmentTests(SimpleTestCase): """ Should a model do anything special with __setattr__() or descriptors which raise a ValidationError, a model form should catch the error (#24706). """ def test_setattr_raises_validation_error_field_specific(self): """ A model ValidationError using the dict form should put the error message into the correct key of form.errors. """ form_class = modelform_factory( model=StrictAssignmentFieldSpecific, fields=["title"] ) form = form_class(data={"title": "testing setattr"}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {"title": ["Cannot set attribute", "This field cannot be blank."]}, ) def test_setattr_raises_validation_error_non_field(self): """ A model ValidationError not using the dict form should put the error message into __all__ (i.e. non-field errors) on the form. """ form_class = modelform_factory(model=StrictAssignmentAll, fields=["title"]) form = form_class(data={"title": "testing setattr"}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "__all__": ["Cannot set attribute"], "title": ["This field cannot be blank."], }, ) class ModelToDictTests(TestCase): def test_many_to_many(self): """Data for a ManyToManyField is a list rather than a lazy QuerySet.""" blue = Colour.objects.create(name="blue") red = Colour.objects.create(name="red") item = ColourfulItem.objects.create() item.colours.set([blue]) data = model_to_dict(item)["colours"] self.assertEqual(data, [blue]) item.colours.set([red]) # If data were a QuerySet, it would be reevaluated here and give "red" # instead of the original value. self.assertEqual(data, [blue])
0cd74a4196a202922e17f4bd09c2553cc3b1342825fca43dfa90af8ca7a6ea25
from unittest import skipUnless from django.core import checks from django.db import connection, models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps("invalid_models_tests") class DeprecatedFieldsTests(SimpleTestCase): def test_IPAddressField_deprecated(self): class IPAddressModel(models.Model): ip = models.IPAddressField() model = IPAddressModel() self.assertEqual( model.check(), [ checks.Error( "IPAddressField has been removed except for support in " "historical migrations.", hint="Use GenericIPAddressField instead.", obj=IPAddressModel._meta.get_field("ip"), id="fields.E900", ) ], ) def test_CommaSeparatedIntegerField_deprecated(self): class CommaSeparatedIntegerModel(models.Model): csi = models.CommaSeparatedIntegerField(max_length=64) model = CommaSeparatedIntegerModel() self.assertEqual( model.check(), [ checks.Error( "CommaSeparatedIntegerField is removed except for support in " "historical migrations.", hint=( "Use " "CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), obj=CommaSeparatedIntegerModel._meta.get_field("csi"), id="fields.E901", ) ], ) def test_nullbooleanfield_deprecated(self): class NullBooleanFieldModel(models.Model): nb = models.NullBooleanField() model = NullBooleanFieldModel() self.assertEqual( model.check(), [ checks.Error( "NullBooleanField is removed except for support in historical " "migrations.", hint="Use BooleanField(null=True, blank=True) instead.", obj=NullBooleanFieldModel._meta.get_field("nb"), id="fields.E903", ), ], ) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_postgres_jsonfield_deprecated(self): from django.contrib.postgres.fields import JSONField class PostgresJSONFieldModel(models.Model): field = JSONField() self.assertEqual( PostgresJSONFieldModel.check(), [ checks.Error( "django.contrib.postgres.fields.JSONField is removed except " "for support in historical migrations.", hint="Use django.db.models.JSONField instead.", obj=PostgresJSONFieldModel._meta.get_field("field"), id="fields.E904", ), ], ) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_postgres_ci_fields_deprecated(self): from django.contrib.postgres.fields import ( ArrayField, CICharField, CIEmailField, CITextField, ) class PostgresCIFieldsModel(models.Model): ci_char = CICharField(max_length=255) ci_email = CIEmailField() ci_text = CITextField() array_ci_text = ArrayField(CITextField()) self.assertEqual( PostgresCIFieldsModel.check(), [ checks.Warning( "django.contrib.postgres.fields.CICharField is deprecated. Support " "for it (except in historical migrations) will be removed in " "Django 5.1.", hint=( 'Use CharField(db_collation="…") with a case-insensitive ' "non-deterministic collation instead." ), obj=PostgresCIFieldsModel._meta.get_field("ci_char"), id="fields.W905", ), checks.Warning( "django.contrib.postgres.fields.CIEmailField is deprecated. " "Support for it (except in historical migrations) will be removed " "in Django 5.1.", hint=( 'Use EmailField(db_collation="…") with a case-insensitive ' "non-deterministic collation instead." ), obj=PostgresCIFieldsModel._meta.get_field("ci_email"), id="fields.W906", ), checks.Warning( "django.contrib.postgres.fields.CITextField is deprecated. Support " "for it (except in historical migrations) will be removed in " "Django 5.1.", hint=( 'Use TextField(db_collation="…") with a case-insensitive ' "non-deterministic collation instead." ), obj=PostgresCIFieldsModel._meta.get_field("ci_text"), id="fields.W907", ), checks.Warning( "Base field for array has warnings:\n" " django.contrib.postgres.fields.CITextField is deprecated. " "Support for it (except in historical migrations) will be removed " "in Django 5.1. (fields.W907)", obj=PostgresCIFieldsModel._meta.get_field("array_ci_text"), id="postgres.W004", ), ], )
3506d954a4919a6d3c35926863bfb380db5d74e81a67deeb97fdde8c93523489
import collections.abc import unittest.mock import warnings from datetime import datetime from django.core.paginator import ( EmptyPage, InvalidPage, PageNotAnInteger, Paginator, UnorderedObjectListWarning, ) from django.test import SimpleTestCase, TestCase from .custom import ValidAdjacentNumsPaginator from .models import Article class PaginationTests(SimpleTestCase): """ Tests for the Paginator and Page classes. """ def check_paginator(self, params, output): """ Helper method that instantiates a Paginator object from the passed params and then checks that its attributes match the passed output. """ count, num_pages, page_range = output paginator = Paginator(*params) self.check_attribute("count", paginator, count, params) self.check_attribute("num_pages", paginator, num_pages, params) self.check_attribute("page_range", paginator, page_range, params, coerce=list) def check_attribute(self, name, paginator, expected, params, coerce=None): """ Helper method that checks a single attribute and gives a nice error message upon test failure. """ got = getattr(paginator, name) if coerce is not None: got = coerce(got) self.assertEqual( expected, got, "For '%s', expected %s but got %s. Paginator parameters were: %s" % (name, expected, got, params), ) def test_paginator(self): """ Tests the paginator attributes using varying inputs. """ nine = [1, 2, 3, 4, 5, 6, 7, 8, 9] ten = nine + [10] eleven = ten + [11] tests = ( # Each item is two tuples: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is resulting Paginator attributes - count, # num_pages, and page_range. # Ten items, varying orphans, no empty first page. ((ten, 4, 0, False), (10, 3, [1, 2, 3])), ((ten, 4, 1, False), (10, 3, [1, 2, 3])), ((ten, 4, 2, False), (10, 2, [1, 2])), ((ten, 4, 5, False), (10, 2, [1, 2])), ((ten, 4, 6, False), (10, 1, [1])), # Ten items, varying orphans, allow empty first page. ((ten, 4, 0, True), (10, 3, [1, 2, 3])), ((ten, 4, 1, True), (10, 3, [1, 2, 3])), ((ten, 4, 2, True), (10, 2, [1, 2])), ((ten, 4, 5, True), (10, 2, [1, 2])), ((ten, 4, 6, True), (10, 1, [1])), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1, [1])), (([1], 4, 1, False), (1, 1, [1])), (([1], 4, 2, False), (1, 1, [1])), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1, [1])), (([1], 4, 1, True), (1, 1, [1])), (([1], 4, 2, True), (1, 1, [1])), # Zero items, varying orphans, no empty first page. (([], 4, 0, False), (0, 0, [])), (([], 4, 1, False), (0, 0, [])), (([], 4, 2, False), (0, 0, [])), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 1, [1])), (([], 4, 1, True), (0, 1, [1])), (([], 4, 2, True), (0, 1, [1])), # Number if items one less than per_page. (([], 1, 0, True), (0, 1, [1])), (([], 1, 0, False), (0, 0, [])), (([1], 2, 0, True), (1, 1, [1])), ((nine, 10, 0, True), (9, 1, [1])), # Number if items equal to per_page. (([1], 1, 0, True), (1, 1, [1])), (([1, 2], 2, 0, True), (2, 1, [1])), ((ten, 10, 0, True), (10, 1, [1])), # Number if items one more than per_page. (([1, 2], 1, 0, True), (2, 2, [1, 2])), (([1, 2, 3], 2, 0, True), (3, 2, [1, 2])), ((eleven, 10, 0, True), (11, 2, [1, 2])), # Number if items one more than per_page with one orphan. (([1, 2], 1, 1, True), (2, 1, [1])), (([1, 2, 3], 2, 1, True), (3, 1, [1])), ((eleven, 10, 1, True), (11, 1, [1])), # Non-integer inputs ((ten, "4", 1, False), (10, 3, [1, 2, 3])), ((ten, "4", 1, False), (10, 3, [1, 2, 3])), ((ten, 4, "1", False), (10, 3, [1, 2, 3])), ((ten, 4, "1", False), (10, 3, [1, 2, 3])), ) for params, output in tests: self.check_paginator(params, output) def test_invalid_page_number(self): """ Invalid page numbers result in the correct exception being raised. """ paginator = Paginator([1, 2, 3], 2) with self.assertRaises(InvalidPage): paginator.page(3) with self.assertRaises(PageNotAnInteger): paginator.validate_number(None) with self.assertRaises(PageNotAnInteger): paginator.validate_number("x") with self.assertRaises(PageNotAnInteger): paginator.validate_number(1.2) def test_error_messages(self): error_messages = { "invalid_page": "Wrong page number", "min_page": "Too small", "no_results": "There is nothing here", } paginator = Paginator([1, 2, 3], 2, error_messages=error_messages) msg = "Wrong page number" with self.assertRaisesMessage(PageNotAnInteger, msg): paginator.validate_number(1.2) msg = "Too small" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(-1) msg = "There is nothing here" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(3) error_messages = {"min_page": "Too small"} paginator = Paginator([1, 2, 3], 2, error_messages=error_messages) # Custom message. msg = "Too small" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(-1) # Default message. msg = "That page contains no results" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(3) def test_float_integer_page(self): paginator = Paginator([1, 2, 3], 2) self.assertEqual(paginator.validate_number(1.0), 1) def test_no_content_allow_empty_first_page(self): # With no content and allow_empty_first_page=True, 1 is a valid page number paginator = Paginator([], 2) self.assertEqual(paginator.validate_number(1), 1) def test_paginate_misc_classes(self): class CountContainer: def count(self): return 42 # Paginator can be passed other objects with a count() method. paginator = Paginator(CountContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) # Paginator can be passed other objects that implement __len__. class LenContainer: def __len__(self): return 42 paginator = Paginator(LenContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) def test_count_does_not_silence_attribute_error(self): class AttributeErrorContainer: def count(self): raise AttributeError("abc") with self.assertRaisesMessage(AttributeError, "abc"): Paginator(AttributeErrorContainer(), 10).count def test_count_does_not_silence_type_error(self): class TypeErrorContainer: def count(self): raise TypeError("abc") with self.assertRaisesMessage(TypeError, "abc"): Paginator(TypeErrorContainer(), 10).count def check_indexes(self, params, page_num, indexes): """ Helper method that instantiates a Paginator object from the passed params and then checks that the start and end indexes of the passed page_num match those given as a 2-tuple in indexes. """ paginator = Paginator(*params) if page_num == "first": page_num = 1 elif page_num == "last": page_num = paginator.num_pages page = paginator.page(page_num) start, end = indexes msg = "For %s of page %s, expected %s but got %s. Paginator parameters were: %s" self.assertEqual( start, page.start_index(), msg % ("start index", page_num, start, page.start_index(), params), ) self.assertEqual( end, page.end_index(), msg % ("end index", page_num, end, page.end_index(), params), ) def test_page_indexes(self): """ Paginator pages have the correct start and end indexes. """ ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] tests = ( # Each item is three tuples: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is the start and end indexes of the first page. # Third tuple is the start and end indexes of the last page. # Ten items, varying per_page, no orphans. ((ten, 1, 0, True), (1, 1), (10, 10)), ((ten, 2, 0, True), (1, 2), (9, 10)), ((ten, 3, 0, True), (1, 3), (10, 10)), ((ten, 5, 0, True), (1, 5), (6, 10)), # Ten items, varying per_page, with orphans. ((ten, 1, 1, True), (1, 1), (9, 10)), ((ten, 1, 2, True), (1, 1), (8, 10)), ((ten, 3, 1, True), (1, 3), (7, 10)), ((ten, 3, 2, True), (1, 3), (7, 10)), ((ten, 3, 4, True), (1, 3), (4, 10)), ((ten, 5, 1, True), (1, 5), (6, 10)), ((ten, 5, 2, True), (1, 5), (6, 10)), ((ten, 5, 5, True), (1, 10), (1, 10)), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1), (1, 1)), (([1], 4, 1, False), (1, 1), (1, 1)), (([1], 4, 2, False), (1, 1), (1, 1)), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1), (1, 1)), (([1], 4, 1, True), (1, 1), (1, 1)), (([1], 4, 2, True), (1, 1), (1, 1)), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 0), (0, 0)), (([], 4, 1, True), (0, 0), (0, 0)), (([], 4, 2, True), (0, 0), (0, 0)), ) for params, first, last in tests: self.check_indexes(params, "first", first) self.check_indexes(params, "last", last) # When no items and no empty first page, we should get EmptyPage error. with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 0, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 1, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 2, False), 1, None) def test_page_sequence(self): """ A paginator page acts like a standard sequence. """ eleven = "abcdefghijk" page2 = Paginator(eleven, per_page=5, orphans=1).page(2) self.assertEqual(len(page2), 6) self.assertIn("k", page2) self.assertNotIn("a", page2) self.assertEqual("".join(page2), "fghijk") self.assertEqual("".join(reversed(page2)), "kjihgf") def test_get_page_hook(self): """ A Paginator subclass can use the ``_get_page`` hook to return an alternative to the standard Page class. """ eleven = "abcdefghijk" paginator = ValidAdjacentNumsPaginator(eleven, per_page=6) page1 = paginator.page(1) page2 = paginator.page(2) self.assertIsNone(page1.previous_page_number()) self.assertEqual(page1.next_page_number(), 2) self.assertEqual(page2.previous_page_number(), 1) self.assertIsNone(page2.next_page_number()) def test_page_range_iterator(self): """ Paginator.page_range should be an iterator. """ self.assertIsInstance(Paginator([1, 2, 3], 2).page_range, type(range(0))) def test_get_page(self): """ Paginator.get_page() returns a valid page even with invalid page arguments. """ paginator = Paginator([1, 2, 3], 2) page = paginator.get_page(1) self.assertEqual(page.number, 1) self.assertEqual(page.object_list, [1, 2]) # An empty page returns the last page. self.assertEqual(paginator.get_page(3).number, 2) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) def test_get_page_empty_object_list(self): """Paginator.get_page() with an empty object_list.""" paginator = Paginator([], 2) # An empty page returns the last page. self.assertEqual(paginator.get_page(1).number, 1) self.assertEqual(paginator.get_page(2).number, 1) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) def test_get_page_empty_object_list_and_allow_empty_first_page_false(self): """ Paginator.get_page() raises EmptyPage if allow_empty_first_page=False and object_list is empty. """ paginator = Paginator([], 2, allow_empty_first_page=False) with self.assertRaises(EmptyPage): paginator.get_page(1) def test_paginator_iteration(self): paginator = Paginator([1, 2, 3], 2) page_iterator = iter(paginator) for page, expected in enumerate(([1, 2], [3]), start=1): with self.subTest(page=page): self.assertEqual(expected, list(next(page_iterator))) self.assertEqual( [str(page) for page in iter(paginator)], ["<Page 1 of 2>", "<Page 2 of 2>"], ) def test_get_elided_page_range(self): # Paginator.validate_number() must be called: paginator = Paginator([1, 2, 3], 2) with unittest.mock.patch.object(paginator, "validate_number") as mock: mock.assert_not_called() list(paginator.get_elided_page_range(2)) mock.assert_called_with(2) ELLIPSIS = Paginator.ELLIPSIS # Range is not elided if not enough pages when using default arguments: paginator = Paginator(range(10 * 100), 100) page_range = paginator.get_elided_page_range(1) self.assertIsInstance(page_range, collections.abc.Generator) self.assertNotIn(ELLIPSIS, page_range) paginator = Paginator(range(10 * 100 + 1), 100) self.assertIsInstance(page_range, collections.abc.Generator) page_range = paginator.get_elided_page_range(1) self.assertIn(ELLIPSIS, page_range) # Range should be elided if enough pages when using default arguments: tests = [ # on_each_side=3, on_ends=2 (1, [1, 2, 3, 4, ELLIPSIS, 49, 50]), (6, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 49, 50]), (7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 49, 50]), (8, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 49, 50]), (43, [1, 2, ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, ELLIPSIS, 49, 50]), (44, [1, 2, ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (45, [1, 2, ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (50, [1, 2, ELLIPSIS, 47, 48, 49, 50]), ] paginator = Paginator(range(5000), 100) for number, expected in tests: with self.subTest(number=number): page_range = paginator.get_elided_page_range(number) self.assertIsInstance(page_range, collections.abc.Generator) self.assertEqual(list(page_range), expected) # Range is not elided if not enough pages when using custom arguments: tests = [ (6, 2, 1, 1), (8, 1, 3, 1), (8, 4, 0, 1), (4, 1, 1, 1), # When on_each_side and on_ends are both <= 1 but not both == 1 it # is a special case where the range is not elided until an extra # page is added. (2, 0, 1, 2), (2, 1, 0, 2), (1, 0, 0, 2), ] for pages, on_each_side, on_ends, elided_after in tests: for offset in range(elided_after + 1): with self.subTest( pages=pages, offset=elided_after, on_each_side=on_each_side, on_ends=on_ends, ): paginator = Paginator(range((pages + offset) * 100), 100) page_range = paginator.get_elided_page_range( 1, on_each_side=on_each_side, on_ends=on_ends, ) self.assertIsInstance(page_range, collections.abc.Generator) if offset < elided_after: self.assertNotIn(ELLIPSIS, page_range) else: self.assertIn(ELLIPSIS, page_range) # Range should be elided if enough pages when using custom arguments: tests = [ # on_each_side=2, on_ends=1 (1, 2, 1, [1, 2, 3, ELLIPSIS, 50]), (4, 2, 1, [1, 2, 3, 4, 5, 6, ELLIPSIS, 50]), (5, 2, 1, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 50]), (6, 2, 1, [1, ELLIPSIS, 4, 5, 6, 7, 8, ELLIPSIS, 50]), (45, 2, 1, [1, ELLIPSIS, 43, 44, 45, 46, 47, ELLIPSIS, 50]), (46, 2, 1, [1, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]), (47, 2, 1, [1, ELLIPSIS, 45, 46, 47, 48, 49, 50]), (50, 2, 1, [1, ELLIPSIS, 48, 49, 50]), # on_each_side=1, on_ends=3 (1, 1, 3, [1, 2, ELLIPSIS, 48, 49, 50]), (5, 1, 3, [1, 2, 3, 4, 5, 6, ELLIPSIS, 48, 49, 50]), (6, 1, 3, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 48, 49, 50]), (7, 1, 3, [1, 2, 3, ELLIPSIS, 6, 7, 8, ELLIPSIS, 48, 49, 50]), (44, 1, 3, [1, 2, 3, ELLIPSIS, 43, 44, 45, ELLIPSIS, 48, 49, 50]), (45, 1, 3, [1, 2, 3, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]), (46, 1, 3, [1, 2, 3, ELLIPSIS, 45, 46, 47, 48, 49, 50]), (50, 1, 3, [1, 2, 3, ELLIPSIS, 49, 50]), # on_each_side=4, on_ends=0 (1, 4, 0, [1, 2, 3, 4, 5, ELLIPSIS]), (5, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS]), (6, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS]), (7, 4, 0, [ELLIPSIS, 3, 4, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS]), (44, 4, 0, [ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, 47, 48, ELLIPSIS]), (45, 4, 0, [ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (46, 4, 0, [ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (50, 4, 0, [ELLIPSIS, 46, 47, 48, 49, 50]), # on_each_side=0, on_ends=1 (1, 0, 1, [1, ELLIPSIS, 50]), (2, 0, 1, [1, 2, ELLIPSIS, 50]), (3, 0, 1, [1, 2, 3, ELLIPSIS, 50]), (4, 0, 1, [1, ELLIPSIS, 4, ELLIPSIS, 50]), (47, 0, 1, [1, ELLIPSIS, 47, ELLIPSIS, 50]), (48, 0, 1, [1, ELLIPSIS, 48, 49, 50]), (49, 0, 1, [1, ELLIPSIS, 49, 50]), (50, 0, 1, [1, ELLIPSIS, 50]), # on_each_side=0, on_ends=0 (1, 0, 0, [1, ELLIPSIS]), (2, 0, 0, [1, 2, ELLIPSIS]), (3, 0, 0, [ELLIPSIS, 3, ELLIPSIS]), (48, 0, 0, [ELLIPSIS, 48, ELLIPSIS]), (49, 0, 0, [ELLIPSIS, 49, 50]), (50, 0, 0, [ELLIPSIS, 50]), ] paginator = Paginator(range(5000), 100) for number, on_each_side, on_ends, expected in tests: with self.subTest( number=number, on_each_side=on_each_side, on_ends=on_ends ): page_range = paginator.get_elided_page_range( number, on_each_side=on_each_side, on_ends=on_ends, ) self.assertIsInstance(page_range, collections.abc.Generator) self.assertEqual(list(page_range), expected) class ModelPaginationTests(TestCase): """ Test pagination with Django model instances """ @classmethod def setUpTestData(cls): # Prepare a list of objects for pagination. pub_date = datetime(2005, 7, 29) cls.articles = [ Article.objects.create(headline=f"Article {x}", pub_date=pub_date) for x in range(1, 10) ] def test_first_page(self): paginator = Paginator(Article.objects.order_by("id"), 5) p = paginator.page(1) self.assertEqual("<Page 1 of 2>", str(p)) self.assertSequenceEqual(p.object_list, self.articles[:5]) self.assertTrue(p.has_next()) self.assertFalse(p.has_previous()) self.assertTrue(p.has_other_pages()) self.assertEqual(2, p.next_page_number()) with self.assertRaises(InvalidPage): p.previous_page_number() self.assertEqual(1, p.start_index()) self.assertEqual(5, p.end_index()) def test_last_page(self): paginator = Paginator(Article.objects.order_by("id"), 5) p = paginator.page(2) self.assertEqual("<Page 2 of 2>", str(p)) self.assertSequenceEqual(p.object_list, self.articles[5:]) self.assertFalse(p.has_next()) self.assertTrue(p.has_previous()) self.assertTrue(p.has_other_pages()) with self.assertRaises(InvalidPage): p.next_page_number() self.assertEqual(1, p.previous_page_number()) self.assertEqual(6, p.start_index()) self.assertEqual(9, p.end_index()) def test_page_getitem(self): """ Tests proper behavior of a paginator page __getitem__ (queryset evaluation, slicing, exception raised). """ paginator = Paginator(Article.objects.order_by("id"), 5) p = paginator.page(1) # object_list queryset is not evaluated by an invalid __getitem__ call. # (this happens from the template engine when using e.g.: # {% page_obj.has_previous %}). self.assertIsNone(p.object_list._result_cache) msg = "Page indices must be integers or slices, not str." with self.assertRaisesMessage(TypeError, msg): p["has_previous"] self.assertIsNone(p.object_list._result_cache) self.assertNotIsInstance(p.object_list, list) # Make sure slicing the Page object with numbers and slice objects work. self.assertEqual(p[0], self.articles[0]) self.assertSequenceEqual(p[slice(2)], self.articles[:2]) # After __getitem__ is called, object_list is a list self.assertIsInstance(p.object_list, list) def test_paginating_unordered_queryset_raises_warning(self): msg = ( "Pagination may yield inconsistent results with an unordered " "object_list: <class 'pagination.models.Article'> QuerySet." ) with self.assertWarnsMessage(UnorderedObjectListWarning, msg) as cm: Paginator(Article.objects.all(), 5) # The warning points at the Paginator caller (i.e. the stacklevel # is appropriate). self.assertEqual(cm.filename, __file__) def test_paginating_empty_queryset_does_not_warn(self): with warnings.catch_warnings(record=True) as recorded: Paginator(Article.objects.none(), 5) self.assertEqual(len(recorded), 0) def test_paginating_unordered_object_list_raises_warning(self): """ Unordered object list warning with an object that has an ordered attribute but not a model attribute. """ class ObjectList: ordered = False object_list = ObjectList() msg = ( "Pagination may yield inconsistent results with an unordered " "object_list: {!r}.".format(object_list) ) with self.assertWarnsMessage(UnorderedObjectListWarning, msg): Paginator(object_list, 5)
a0b77b75b31650307f6f6d4cb42138956f9be6df276586809f788d5fe97b03de
import copy import datetime import pickle from operator import attrgetter from django.core.exceptions import FieldError from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils import translation from django.utils.deprecation import RemovedInDjango60Warning from .models import ( Article, ArticleIdea, ArticleTag, ArticleTranslation, Country, Friendship, Group, Membership, NewsArticle, Person, ) # Note that these tests are testing internal implementation details. # ForeignObject is not part of public API. class MultiColumnFKTests(TestCase): @classmethod def setUpTestData(cls): # Creating countries cls.usa = Country.objects.create(name="United States of America") cls.soviet_union = Country.objects.create(name="Soviet Union") # Creating People cls.bob = Person.objects.create(name="Bob", person_country=cls.usa) cls.jim = Person.objects.create(name="Jim", person_country=cls.usa) cls.george = Person.objects.create(name="George", person_country=cls.usa) cls.jane = Person.objects.create(name="Jane", person_country=cls.soviet_union) cls.mark = Person.objects.create(name="Mark", person_country=cls.soviet_union) cls.sam = Person.objects.create(name="Sam", person_country=cls.soviet_union) # Creating Groups cls.kgb = Group.objects.create(name="KGB", group_country=cls.soviet_union) cls.cia = Group.objects.create(name="CIA", group_country=cls.usa) cls.republican = Group.objects.create(name="Republican", group_country=cls.usa) cls.democrat = Group.objects.create(name="Democrat", group_country=cls.usa) def test_get_succeeds_on_multicolumn_match(self): # Membership objects have access to their related Person if both # country_ids match between them membership = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) person = membership.person self.assertEqual((person.id, person.name), (self.bob.id, "Bob")) def test_get_fails_on_multicolumn_mismatch(self): # Membership objects returns DoesNotExist error when there is no # Person with the same id and country_id membership = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jane.id, group_id=self.cia.id, ) with self.assertRaises(Person.DoesNotExist): getattr(membership, "person") def test_reverse_query_returns_correct_result(self): # Creating a valid membership because it has the same country has the person Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) # Creating an invalid membership because it has a different country has # the person. Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.bob.id, group_id=self.republican.id, ) with self.assertNumQueries(1): membership = self.bob.membership_set.get() self.assertEqual(membership.group_id, self.cia.id) self.assertIs(membership.person, self.bob) def test_query_filters_correctly(self): # Creating a to valid memberships Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, ) self.assertQuerySetEqual( Membership.objects.filter(person__name__contains="o"), [self.bob.id], attrgetter("person_id"), ) def test_reverse_query_filters_correctly(self): timemark = datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None) timedelta = datetime.timedelta(days=1) # Creating a to valid memberships Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, date_joined=timemark - timedelta, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, date_joined=timemark + timedelta, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, date_joined=timemark + timedelta, ) self.assertQuerySetEqual( Person.objects.filter(membership__date_joined__gte=timemark), ["Jim"], attrgetter("name"), ) def test_forward_in_lookup_filters_correctly(self): Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, ) self.assertQuerySetEqual( Membership.objects.filter(person__in=[self.george, self.jim]), [ self.jim.id, ], attrgetter("person_id"), ) self.assertQuerySetEqual( Membership.objects.filter(person__in=Person.objects.filter(name="Jim")), [ self.jim.id, ], attrgetter("person_id"), ) def test_double_nested_query(self): m1 = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) m2 = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) Friendship.objects.create( from_friend_country_id=self.usa.id, from_friend_id=self.bob.id, to_friend_country_id=self.usa.id, to_friend_id=self.jim.id, ) self.assertSequenceEqual( Membership.objects.filter( person__in=Person.objects.filter( from_friend__in=Friendship.objects.filter( to_friend__in=Person.objects.all() ) ) ), [m1], ) self.assertSequenceEqual( Membership.objects.exclude( person__in=Person.objects.filter( from_friend__in=Friendship.objects.filter( to_friend__in=Person.objects.all() ) ) ), [m2], ) def test_select_related_foreignkey_forward_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(1): people = [ m.person for m in Membership.objects.select_related("person").order_by("pk") ] normal_people = [m.person for m in Membership.objects.order_by("pk")] self.assertEqual(people, normal_people) def test_prefetch_foreignkey_forward_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): people = [ m.person for m in Membership.objects.prefetch_related("person").order_by("pk") ] normal_people = [m.person for m in Membership.objects.order_by("pk")] self.assertEqual(people, normal_people) def test_prefetch_foreignkey_reverse_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): membership_sets = [ list(p.membership_set.all()) for p in Person.objects.prefetch_related("membership_set").order_by( "pk" ) ] with self.assertNumQueries(7): normal_membership_sets = [ list(p.membership_set.all()) for p in Person.objects.order_by("pk") ] self.assertEqual(membership_sets, normal_membership_sets) def test_m2m_through_forward_returns_valid_members(self): # We start out by making sure that the Group 'CIA' has no members. self.assertQuerySetEqual(self.cia.members.all(), []) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.cia ) # Bob and Jim should be members of the CIA. self.assertQuerySetEqual( self.cia.members.all(), ["Bob", "Jim"], attrgetter("name") ) def test_m2m_through_reverse_returns_valid_members(self): # We start out by making sure that Bob is in no groups. self.assertQuerySetEqual(self.bob.groups.all(), []) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.republican ) # Bob should be in the CIA and a Republican self.assertQuerySetEqual( self.bob.groups.all(), ["CIA", "Republican"], attrgetter("name") ) def test_m2m_through_forward_ignores_invalid_members(self): # We start out by making sure that the Group 'CIA' has no members. self.assertQuerySetEqual(self.cia.members.all(), []) # Something adds jane to group CIA but Jane is in Soviet Union which # isn't CIA's country. Membership.objects.create( membership_country=self.usa, person=self.jane, group=self.cia ) # There should still be no members in CIA self.assertQuerySetEqual(self.cia.members.all(), []) def test_m2m_through_reverse_ignores_invalid_members(self): # We start out by making sure that Jane has no groups. self.assertQuerySetEqual(self.jane.groups.all(), []) # Something adds jane to group CIA but Jane is in Soviet Union which # isn't CIA's country. Membership.objects.create( membership_country=self.usa, person=self.jane, group=self.cia ) # Jane should still not be in any groups self.assertQuerySetEqual(self.jane.groups.all(), []) def test_m2m_through_on_self_works(self): self.assertQuerySetEqual(self.jane.friends.all(), []) Friendship.objects.create( from_friend_country=self.jane.person_country, from_friend=self.jane, to_friend_country=self.george.person_country, to_friend=self.george, ) self.assertQuerySetEqual( self.jane.friends.all(), ["George"], attrgetter("name") ) def test_m2m_through_on_self_ignores_mismatch_columns(self): self.assertQuerySetEqual(self.jane.friends.all(), []) # Note that we use ids instead of instances. This is because instances # on ForeignObject properties will set all related field off of the # given instance. Friendship.objects.create( from_friend_id=self.jane.id, to_friend_id=self.george.id, to_friend_country_id=self.jane.person_country_id, from_friend_country_id=self.george.person_country_id, ) self.assertQuerySetEqual(self.jane.friends.all(), []) def test_prefetch_related_m2m_forward_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): members_lists = [ list(g.members.all()) for g in Group.objects.prefetch_related("members") ] normal_members_lists = [list(g.members.all()) for g in Group.objects.all()] self.assertEqual(members_lists, normal_members_lists) def test_prefetch_related_m2m_reverse_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): groups_lists = [ list(p.groups.all()) for p in Person.objects.prefetch_related("groups") ] normal_groups_lists = [list(p.groups.all()) for p in Person.objects.all()] self.assertEqual(groups_lists, normal_groups_lists) @translation.override("fi") def test_translations(self): a1 = Article.objects.create(pub_date=datetime.date.today()) at1_fi = ArticleTranslation( article=a1, lang="fi", title="Otsikko", body="Diipadaapa" ) at1_fi.save() at2_en = ArticleTranslation( article=a1, lang="en", title="Title", body="Lalalalala" ) at2_en.save() self.assertEqual(Article.objects.get(pk=a1.pk).active_translation, at1_fi) with self.assertNumQueries(1): fetched = Article.objects.select_related("active_translation").get( active_translation__title="Otsikko" ) self.assertEqual(fetched.active_translation.title, "Otsikko") a2 = Article.objects.create(pub_date=datetime.date.today()) at2_fi = ArticleTranslation( article=a2, lang="fi", title="Atsikko", body="Diipadaapa", abstract="dipad" ) at2_fi.save() a3 = Article.objects.create(pub_date=datetime.date.today()) at3_en = ArticleTranslation( article=a3, lang="en", title="A title", body="lalalalala", abstract="lala" ) at3_en.save() # Test model initialization with active_translation field. a3 = Article(id=a3.id, pub_date=a3.pub_date, active_translation=at3_en) a3.save() self.assertEqual( list(Article.objects.filter(active_translation__abstract=None)), [a1, a3] ) self.assertEqual( list( Article.objects.filter( active_translation__abstract=None, active_translation__pk__isnull=False, ) ), [a1], ) with translation.override("en"): self.assertEqual( list(Article.objects.filter(active_translation__abstract=None)), [a1, a2], ) def test_foreign_key_raises_informative_does_not_exist(self): referrer = ArticleTranslation() with self.assertRaisesMessage( Article.DoesNotExist, "ArticleTranslation has no article" ): referrer.article def test_foreign_key_related_query_name(self): a1 = Article.objects.create(pub_date=datetime.date.today()) ArticleTag.objects.create(article=a1, name="foo") self.assertEqual(Article.objects.filter(tag__name="foo").count(), 1) self.assertEqual(Article.objects.filter(tag__name="bar").count(), 0) msg = ( "Cannot resolve keyword 'tags' into field. Choices are: " "active_translation, active_translation_q, articletranslation, " "id, idea_things, newsarticle, pub_date, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(tags__name="foo") def test_many_to_many_related_query_name(self): a1 = Article.objects.create(pub_date=datetime.date.today()) i1 = ArticleIdea.objects.create(name="idea1") a1.ideas.add(i1) self.assertEqual(Article.objects.filter(idea_things__name="idea1").count(), 1) self.assertEqual(Article.objects.filter(idea_things__name="idea2").count(), 0) msg = ( "Cannot resolve keyword 'ideas' into field. Choices are: " "active_translation, active_translation_q, articletranslation, " "id, idea_things, newsarticle, pub_date, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(ideas__name="idea1") @translation.override("fi") def test_inheritance(self): na = NewsArticle.objects.create(pub_date=datetime.date.today()) ArticleTranslation.objects.create( article=na, lang="fi", title="foo", body="bar" ) self.assertSequenceEqual( NewsArticle.objects.select_related("active_translation"), [na] ) with self.assertNumQueries(1): self.assertEqual( NewsArticle.objects.select_related("active_translation")[ 0 ].active_translation.title, "foo", ) @skipUnlessDBFeature("has_bulk_insert") def test_batch_create_foreign_object(self): objs = [ Person(name="abcd_%s" % i, person_country=self.usa) for i in range(0, 5) ] Person.objects.bulk_create(objs, 10) def test_isnull_lookup(self): m1 = Membership.objects.create( membership_country=self.usa, person=self.bob, group_id=None ) m2 = Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) self.assertSequenceEqual( Membership.objects.filter(group__isnull=True), [m1], ) self.assertSequenceEqual( Membership.objects.filter(group__isnull=False), [m2], ) class TestModelCheckTests(SimpleTestCase): @isolate_apps("foreign_object") def test_check_composite_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() class Meta: unique_together = (("a", "b"),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() value = models.CharField(max_length=255) parent = models.ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=("a", "b"), to_fields=("a", "b"), related_name="children", ) self.assertEqual(Child._meta.get_field("parent").check(from_model=Child), []) @isolate_apps("foreign_object") def test_check_subset_composite_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() class Meta: unique_together = (("a", "b"),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() d = models.CharField(max_length=255) parent = models.ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=("a", "b", "c"), to_fields=("a", "b", "c"), related_name="children", ) self.assertEqual(Child._meta.get_field("parent").check(from_model=Child), []) class TestExtraJoinFilterQ(TestCase): @translation.override("fi") def test_extra_join_filter_q(self): a = Article.objects.create(pub_date=datetime.datetime.today()) ArticleTranslation.objects.create( article=a, lang="fi", title="title", body="body" ) qs = Article.objects.all() with self.assertNumQueries(2): self.assertEqual(qs[0].active_translation_q.title, "title") qs = qs.select_related("active_translation_q") with self.assertNumQueries(1): self.assertEqual(qs[0].active_translation_q.title, "title") class TestCachedPathInfo(TestCase): def test_equality(self): """ The path_infos and reverse_path_infos attributes are equivalent to calling the get_<method>() with no arguments. """ foreign_object = Membership._meta.get_field("person") self.assertEqual( foreign_object.path_infos, foreign_object.get_path_info(), ) self.assertEqual( foreign_object.reverse_path_infos, foreign_object.get_reverse_path_info(), ) def test_copy_removes_direct_cached_values(self): """ Shallow copying a ForeignObject (or a ForeignObjectRel) removes the object's direct cached PathInfo values. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObject's __dict__. foreign_object.path_infos foreign_object.reverse_path_infos # The ForeignObjectRel doesn't have reverse_path_infos. foreign_object.remote_field.path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) self.assertIn("path_infos", foreign_object.remote_field.__dict__) # Cached value is removed via __getstate__() on ForeignObjectRel # because no __copy__() method exists, so __reduce_ex__() is used. remote_field_copy = copy.copy(foreign_object.remote_field) self.assertNotIn("path_infos", remote_field_copy.__dict__) # Cached values are removed via __copy__() on ForeignObject for # consistency of behavior. foreign_object_copy = copy.copy(foreign_object) self.assertNotIn("path_infos", foreign_object_copy.__dict__) self.assertNotIn("reverse_path_infos", foreign_object_copy.__dict__) # ForeignObjectRel's remains because it's part of a shallow copy. self.assertIn("path_infos", foreign_object_copy.remote_field.__dict__) def test_deepcopy_removes_cached_values(self): """ Deep copying a ForeignObject removes the object's cached PathInfo values, including those of the related ForeignObjectRel. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObject's __dict__. foreign_object.path_infos foreign_object.reverse_path_infos # The ForeignObjectRel doesn't have reverse_path_infos. foreign_object.remote_field.path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) self.assertIn("path_infos", foreign_object.remote_field.__dict__) # Cached value is removed via __getstate__() on ForeignObjectRel # because no __deepcopy__() method exists, so __reduce_ex__() is used. remote_field_copy = copy.deepcopy(foreign_object.remote_field) self.assertNotIn("path_infos", remote_field_copy.__dict__) # Field.__deepcopy__() internally uses __copy__() on both the # ForeignObject and ForeignObjectRel, so all cached values are removed. foreign_object_copy = copy.deepcopy(foreign_object) self.assertNotIn("path_infos", foreign_object_copy.__dict__) self.assertNotIn("reverse_path_infos", foreign_object_copy.__dict__) self.assertNotIn("path_infos", foreign_object_copy.remote_field.__dict__) def test_pickling_foreignobjectrel(self): """ Pickling a ForeignObjectRel removes the path_infos attribute. ForeignObjectRel implements __getstate__(), so copy and pickle modules both use that, but ForeignObject implements __reduce__() and __copy__() separately, so doesn't share the same behaviour. """ foreign_object_rel = Membership._meta.get_field("person").remote_field # Trigger storage of cached_property into ForeignObjectRel's __dict__. foreign_object_rel.path_infos self.assertIn("path_infos", foreign_object_rel.__dict__) foreign_object_rel_restored = pickle.loads(pickle.dumps(foreign_object_rel)) self.assertNotIn("path_infos", foreign_object_rel_restored.__dict__) def test_pickling_foreignobject(self): """ Pickling a ForeignObject does not remove the cached PathInfo values. ForeignObject will always keep the path_infos and reverse_path_infos attributes within the same process, because of the way Field.__reduce__() is used for restoring values. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObjectRel's __dict__ foreign_object.path_infos foreign_object.reverse_path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) foreign_object_restored = pickle.loads(pickle.dumps(foreign_object)) self.assertIn("path_infos", foreign_object_restored.__dict__) self.assertIn("reverse_path_infos", foreign_object_restored.__dict__) class GetJoiningDeprecationTests(TestCase): def test_foreign_object_get_joining_columns_warning(self): msg = ( "ForeignObject.get_joining_columns() is deprecated. Use " "get_joining_fields() instead." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): Membership.person.field.get_joining_columns() def test_foreign_object_get_reverse_joining_columns_warning(self): msg = ( "ForeignObject.get_reverse_joining_columns() is deprecated. Use " "get_reverse_joining_fields() instead." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): Membership.person.field.get_reverse_joining_columns() def test_foreign_object_rel_get_joining_columns_warning(self): msg = ( "ForeignObjectRel.get_joining_columns() is deprecated. Use " "get_joining_fields() instead." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): Membership.person.field.remote_field.get_joining_columns() def test_join_get_joining_columns_warning(self): class CustomForeignKey(models.ForeignKey): def __getattribute__(self, attr): if attr == "get_joining_fields": raise AttributeError return super().__getattribute__(attr) class CustomParent(models.Model): value = models.CharField(max_length=255) class CustomChild(models.Model): links = CustomForeignKey(CustomParent, models.CASCADE) msg = ( "The usage of get_joining_columns() in Join is deprecated. Implement " "get_joining_fields() instead." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): CustomChild.objects.filter(links__value="value")
6b451b0e561afa4959692c8705265c541a2f3317189bec7fd68413d1479856f1
import datetime import decimal import ipaddress import uuid from django.db import models from django.template import Context, Template from django.test import SimpleTestCase from django.utils.functional import Promise from django.utils.translation import gettext_lazy as _ class Suit(models.IntegerChoices): DIAMOND = 1, _("Diamond") SPADE = 2, _("Spade") HEART = 3, _("Heart") CLUB = 4, _("Club") class YearInSchool(models.TextChoices): FRESHMAN = "FR", _("Freshman") SOPHOMORE = "SO", _("Sophomore") JUNIOR = "JR", _("Junior") SENIOR = "SR", _("Senior") GRADUATE = "GR", _("Graduate") class Vehicle(models.IntegerChoices): CAR = 1, "Carriage" TRUCK = 2 JET_SKI = 3 __empty__ = _("(Unknown)") class Gender(models.TextChoices): MALE = "M" FEMALE = "F" NOT_SPECIFIED = "X" __empty__ = "(Undeclared)" class ChoicesTests(SimpleTestCase): def test_integerchoices(self): self.assertEqual( Suit.choices, [(1, "Diamond"), (2, "Spade"), (3, "Heart"), (4, "Club")] ) self.assertEqual(Suit.labels, ["Diamond", "Spade", "Heart", "Club"]) self.assertEqual(Suit.values, [1, 2, 3, 4]) self.assertEqual(Suit.names, ["DIAMOND", "SPADE", "HEART", "CLUB"]) self.assertEqual(repr(Suit.DIAMOND), "Suit.DIAMOND") self.assertEqual(Suit.DIAMOND.label, "Diamond") self.assertEqual(Suit.DIAMOND.value, 1) self.assertEqual(Suit["DIAMOND"], Suit.DIAMOND) self.assertEqual(Suit(1), Suit.DIAMOND) self.assertIsInstance(Suit, type(models.Choices)) self.assertIsInstance(Suit.DIAMOND, Suit) self.assertIsInstance(Suit.DIAMOND.label, Promise) self.assertIsInstance(Suit.DIAMOND.value, int) def test_integerchoices_auto_label(self): self.assertEqual(Vehicle.CAR.label, "Carriage") self.assertEqual(Vehicle.TRUCK.label, "Truck") self.assertEqual(Vehicle.JET_SKI.label, "Jet Ski") def test_integerchoices_empty_label(self): self.assertEqual(Vehicle.choices[0], (None, "(Unknown)")) self.assertEqual(Vehicle.labels[0], "(Unknown)") self.assertIsNone(Vehicle.values[0]) self.assertEqual(Vehicle.names[0], "__empty__") def test_integerchoices_functional_api(self): Place = models.IntegerChoices("Place", "FIRST SECOND THIRD") self.assertEqual(Place.labels, ["First", "Second", "Third"]) self.assertEqual(Place.values, [1, 2, 3]) self.assertEqual(Place.names, ["FIRST", "SECOND", "THIRD"]) def test_integerchoices_containment(self): self.assertIn(Suit.DIAMOND, Suit) self.assertIn(1, Suit) self.assertNotIn(0, Suit) def test_textchoices(self): self.assertEqual( YearInSchool.choices, [ ("FR", "Freshman"), ("SO", "Sophomore"), ("JR", "Junior"), ("SR", "Senior"), ("GR", "Graduate"), ], ) self.assertEqual( YearInSchool.labels, ["Freshman", "Sophomore", "Junior", "Senior", "Graduate"], ) self.assertEqual(YearInSchool.values, ["FR", "SO", "JR", "SR", "GR"]) self.assertEqual( YearInSchool.names, ["FRESHMAN", "SOPHOMORE", "JUNIOR", "SENIOR", "GRADUATE"], ) self.assertEqual(repr(YearInSchool.FRESHMAN), "YearInSchool.FRESHMAN") self.assertEqual(YearInSchool.FRESHMAN.label, "Freshman") self.assertEqual(YearInSchool.FRESHMAN.value, "FR") self.assertEqual(YearInSchool["FRESHMAN"], YearInSchool.FRESHMAN) self.assertEqual(YearInSchool("FR"), YearInSchool.FRESHMAN) self.assertIsInstance(YearInSchool, type(models.Choices)) self.assertIsInstance(YearInSchool.FRESHMAN, YearInSchool) self.assertIsInstance(YearInSchool.FRESHMAN.label, Promise) self.assertIsInstance(YearInSchool.FRESHMAN.value, str) def test_textchoices_auto_label(self): self.assertEqual(Gender.MALE.label, "Male") self.assertEqual(Gender.FEMALE.label, "Female") self.assertEqual(Gender.NOT_SPECIFIED.label, "Not Specified") def test_textchoices_empty_label(self): self.assertEqual(Gender.choices[0], (None, "(Undeclared)")) self.assertEqual(Gender.labels[0], "(Undeclared)") self.assertIsNone(Gender.values[0]) self.assertEqual(Gender.names[0], "__empty__") def test_textchoices_functional_api(self): Medal = models.TextChoices("Medal", "GOLD SILVER BRONZE") self.assertEqual(Medal.labels, ["Gold", "Silver", "Bronze"]) self.assertEqual(Medal.values, ["GOLD", "SILVER", "BRONZE"]) self.assertEqual(Medal.names, ["GOLD", "SILVER", "BRONZE"]) def test_textchoices_containment(self): self.assertIn(YearInSchool.FRESHMAN, YearInSchool) self.assertIn("FR", YearInSchool) self.assertNotIn("XX", YearInSchool) def test_textchoices_blank_value(self): class BlankStr(models.TextChoices): EMPTY = "", "(Empty)" ONE = "ONE", "One" self.assertEqual(BlankStr.labels, ["(Empty)", "One"]) self.assertEqual(BlankStr.values, ["", "ONE"]) self.assertEqual(BlankStr.names, ["EMPTY", "ONE"]) def test_invalid_definition(self): msg = "'str' object cannot be interpreted as an integer" with self.assertRaisesMessage(TypeError, msg): class InvalidArgumentEnum(models.IntegerChoices): # A string is not permitted as the second argument to int(). ONE = 1, "X", "Invalid" msg = "duplicate values found in <enum 'Fruit'>: PINEAPPLE -> APPLE" with self.assertRaisesMessage(ValueError, msg): class Fruit(models.IntegerChoices): APPLE = 1, "Apple" PINEAPPLE = 1, "Pineapple" def test_str(self): for test in [Gender, Suit, YearInSchool, Vehicle]: for member in test: with self.subTest(member=member): self.assertEqual(str(test[member.name]), str(member.value)) def test_templates(self): template = Template("{{ Suit.DIAMOND.label }}|{{ Suit.DIAMOND.value }}") output = template.render(Context({"Suit": Suit})) self.assertEqual(output, "Diamond|1") def test_property_names_conflict_with_member_names(self): with self.assertRaises(AttributeError): models.TextChoices("Properties", "choices labels names values") def test_label_member(self): # label can be used as a member. Stationery = models.TextChoices("Stationery", "label stamp sticker") self.assertEqual(Stationery.label.label, "Label") self.assertEqual(Stationery.label.value, "label") self.assertEqual(Stationery.label.name, "label") def test_do_not_call_in_templates_member(self): # do_not_call_in_templates is not implicitly treated as a member. Special = models.IntegerChoices("Special", "do_not_call_in_templates") self.assertEqual( Special.do_not_call_in_templates.label, "Do Not Call In Templates", ) self.assertEqual(Special.do_not_call_in_templates.value, 1) self.assertEqual( Special.do_not_call_in_templates.name, "do_not_call_in_templates", ) class Separator(bytes, models.Choices): FS = b"\x1c", "File Separator" GS = b"\x1d", "Group Separator" RS = b"\x1e", "Record Separator" US = b"\x1f", "Unit Separator" class Constants(float, models.Choices): PI = 3.141592653589793, "π" TAU = 6.283185307179586, "τ" class Set(frozenset, models.Choices): A = {1, 2} B = {2, 3} UNION = A | B DIFFERENCE = A - B INTERSECTION = A & B class MoonLandings(datetime.date, models.Choices): APOLLO_11 = 1969, 7, 20, "Apollo 11 (Eagle)" APOLLO_12 = 1969, 11, 19, "Apollo 12 (Intrepid)" APOLLO_14 = 1971, 2, 5, "Apollo 14 (Antares)" APOLLO_15 = 1971, 7, 30, "Apollo 15 (Falcon)" APOLLO_16 = 1972, 4, 21, "Apollo 16 (Orion)" APOLLO_17 = 1972, 12, 11, "Apollo 17 (Challenger)" class DateAndTime(datetime.datetime, models.Choices): A = 2010, 10, 10, 10, 10, 10 B = 2011, 11, 11, 11, 11, 11 C = 2012, 12, 12, 12, 12, 12 class MealTimes(datetime.time, models.Choices): BREAKFAST = 7, 0 LUNCH = 13, 0 DINNER = 18, 30 class Frequency(datetime.timedelta, models.Choices): WEEK = 0, 0, 0, 0, 0, 0, 1, "Week" DAY = 1, "Day" HOUR = 0, 0, 0, 0, 0, 1, "Hour" MINUTE = 0, 0, 0, 0, 1, "Hour" SECOND = 0, 1, "Second" class Number(decimal.Decimal, models.Choices): E = 2.718281828459045, "e" PI = "3.141592653589793", "π" TAU = decimal.Decimal("6.283185307179586"), "τ" class IPv4Address(ipaddress.IPv4Address, models.Choices): LOCALHOST = "127.0.0.1", "Localhost" GATEWAY = "192.168.0.1", "Gateway" BROADCAST = "192.168.0.255", "Broadcast" class IPv6Address(ipaddress.IPv6Address, models.Choices): LOCALHOST = "::1", "Localhost" UNSPECIFIED = "::", "Unspecified" class IPv4Network(ipaddress.IPv4Network, models.Choices): LOOPBACK = "127.0.0.0/8", "Loopback" LINK_LOCAL = "169.254.0.0/16", "Link-Local" PRIVATE_USE_A = "10.0.0.0/8", "Private-Use (Class A)" class IPv6Network(ipaddress.IPv6Network, models.Choices): LOOPBACK = "::1/128", "Loopback" UNSPECIFIED = "::/128", "Unspecified" UNIQUE_LOCAL = "fc00::/7", "Unique-Local" LINK_LOCAL_UNICAST = "fe80::/10", "Link-Local Unicast" class CustomChoicesTests(SimpleTestCase): def test_labels_valid(self): enums = ( Separator, Constants, Set, MoonLandings, DateAndTime, MealTimes, Frequency, Number, IPv4Address, IPv6Address, IPv4Network, IPv6Network, ) for choice_enum in enums: with self.subTest(choice_enum.__name__): self.assertNotIn(None, choice_enum.labels) def test_bool_unsupported(self): msg = "type 'bool' is not an acceptable base type" with self.assertRaisesMessage(TypeError, msg): class Boolean(bool, models.Choices): pass def test_timezone_unsupported(self): msg = "type 'datetime.timezone' is not an acceptable base type" with self.assertRaisesMessage(TypeError, msg): class Timezone(datetime.timezone, models.Choices): pass def test_uuid_unsupported(self): with self.assertRaises(TypeError): class Identifier(uuid.UUID, models.Choices): A = "972ce4eb-a95f-4a56-9339-68c208a76f18"
6c6c3a99543d64a07d400ce85e02554c7d0753919a62d92a792ecbd0fbf10988
from django.conf.urls.i18n import i18n_patterns from django.http import HttpResponse from django.urls import path, re_path from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( re_path(r"^(?P<arg>[\w-]+)-page", lambda request, **arg: HttpResponse(_("Yes"))), path("simple/", lambda r: HttpResponse(_("Yes"))), re_path(r"^(.+)/(.+)/$", lambda *args: HttpResponse()), re_path(_(r"^users/$"), lambda *args: HttpResponse(), name="users"), prefix_default_language=False, )
e547abd1498bcf4e28f3810cd38065bd17f13ea0eecc150bb5e50da4e7e7871b
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.utils import translation from django.utils.formats import ( date_format, get_format, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, sanitize_strftime_format, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, "other", "locale"), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override("fr") def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual( ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 année", ) self.assertEqual( ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 années", ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" ) def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") @override_settings(LOCALE_PATHS=extended_locale_paths) @translation.override("fr") def test_multiple_plurals_per_language(self): """ Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po has a different plural equation with 3 plurals, this tests if those plural are honored. """ self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") french = trans_real.catalog() # Internal _catalog can query subcatalogs (from different po files). self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") def test_override(self): activate("de") try: with translation.override("pl"): self.assertEqual(get_language(), "pl") self.assertEqual(get_language(), "de") with translation.override(None): self.assertIsNone(get_language()) with translation.override("pl"): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), "de") finally: deactivate() def test_override_decorator(self): @translation.override("pl") def func_pl(): self.assertEqual(get_language(), "pl") @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate("de") func_pl() self.assertEqual(get_language(), "de") func_none() self.assertEqual(get_language(), "de") finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate("fr") @translation.override("pl") def func_pl(): pass deactivate() try: activate("en") func_pl() self.assertEqual(get_language(), "en") finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy("Add %(name)s") d = {"name": "Ringo"} self.assertEqual("Add Ringo", s % d) with translation.override("de", deactivate=True): self.assertEqual("Ringo hinzuf\xfcgen", s % d) with translation.override("pl"): self.assertEqual("Dodaj Ringo", s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy("Add %(name)s") self.assertEqual(s, s1) s2 = gettext_lazy("Add %(name)s") s3 = gettext_lazy("Add %(name)s") self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy("Some other string") self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy("%d good result", "%d good results") simple_context_with_format = npgettext_lazy( "Exclamation", "%d good result", "%d good results" ) simple_without_format = ngettext_lazy("good result", "good results") with translation.override("de"): self.assertEqual(simple_with_format % 1, "1 gutes Resultat") self.assertEqual(simple_with_format % 4, "4 guten Resultate") self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") self.assertEqual(simple_without_format % 1, "gutes Resultat") self.assertEqual(simple_without_format % 4, "guten Resultate") complex_nonlazy = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 ) complex_deferred = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy % {"num": 4, "name": "Jim"}, "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 1}, "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 5}, "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred % {"name": "Jim"} self.assertEqual( complex_context_nonlazy % {"num": 4, "name": "Jim"}, "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 1}, "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 5}, "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred % {"name": "Jim"} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy("{} good result", "{} good results") simple_context_with_format = npgettext_lazy( "Exclamation", "{} good result", "{} good results" ) with translation.override("de"): self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") self.assertEqual(simple_with_format.format(4), "4 guten Resultate") self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") complex_nonlazy = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 ) complex_deferred = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy.format(num=4, name="Jim"), "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred.format(name="Jim", num=1), "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred.format(name="Jim", num=5), "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred.format(name="Jim") self.assertEqual( complex_context_nonlazy.format(num=4, name="Jim"), "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=1), "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=5), "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred.format(name="Jim") def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy("%d good result", "%d good results")) self.assertFalse(ngettext_lazy("", "")) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy("%d good result", "%d good results") self.assertEqual(s1 % 1, "1 good result") self.assertEqual(s1 % 8, "8 good results") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, "1 good result") self.assertEqual(s2 % 8, "8 good results") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override("de"): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual( npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" ) def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override("de"): self.assertEqual("", gettext("")) s = mark_safe("") self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe("Password") s2 = mark_safe("May") with translation.override("de", deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext("month name", s2)), SafeString) self.assertEqual("aPassword", SafeString("a") + s1) self.assertEqual("Passworda", s1 + SafeString("a")) self.assertEqual("Passworda", s1 + mark_safe("a")) self.assertEqual("aPassword", mark_safe("a") + s1) self.assertEqual("as", mark_safe("a") + mark_safe("s")) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation("ca") ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" with translation.override("ca", deactivate=True): self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) def test_to_locale(self): tests = ( ("en", "en"), ("EN", "en"), ("en-us", "en_US"), ("EN-US", "en_US"), ("en_US", "en_US"), # With > 2 characters after the dash. ("sr-latn", "sr_Latn"), ("sr-LATN", "sr_Latn"), ("sr_Latn", "sr_Latn"), # 3-char language codes. ("ber-MA", "ber_MA"), ("BER-MA", "ber_MA"), ("BER_MA", "ber_MA"), ("ber_MA", "ber_MA"), # With private use subtag (x-informal). ("nl-nl-x-informal", "nl_NL-x-informal"), ("NL-NL-X-INFORMAL", "nl_NL-x-informal"), ("sr-latn-x-informal", "sr_Latn-x-informal"), ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat") def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE="he"): self.assertIs(get_language_bidi(), True) class TranslationLoadingTests(SimpleTestCase): def setUp(self): """Clear translation state.""" self._old_language = get_language() self._old_translations = trans_real._translations deactivate() trans_real._translations = {} def tearDown(self): trans_real._translations = self._old_translations activate(self._old_language) @override_settings( USE_I18N=True, LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("en-ca", "English (Canada)"), ("en-nz", "English (New Zealand)"), ("en-au", "English (Australia)"), ], LOCALE_PATHS=[os.path.join(here, "loading")], INSTALLED_APPS=["i18n.loading_app"], ) def test_translation_loading(self): """ "loading_app" does not have translations for all languages provided by "loading". Catalogs are merged correctly. """ tests = [ ("en", "local country person"), ("en_AU", "aussie"), ("en_NZ", "kiwi"), ("en_CA", "canuck"), ] # Load all relevant translations. for language, _ in tests: activate(language) # Catalogs are merged correctly. for language, nickname in tests: with self.subTest(language=language): activate(language) self.assertEqual(gettext("local country person"), nickname) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations["en-YY"] = None return res trans_real._translations = {sideeffect_str("en-XX"): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate("pl") # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal("66666.666") self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context( { "n": self.n, "t": self.t, "d": self.d, "dt": self.dt, "f": self.f, "l": self.long, } ) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn( "2017", date_format(some_date) ) # Uses DATE_FORMAT by default self.assertIn( "23", time_format(some_datetime) ) # Uses TIME_FORMAT by default self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT")) self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT")) self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT")) self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT")) self.assertIn( "2017", date_format(some_datetime, "SHORT_DATETIME_FORMAT"), ) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual( "66666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "66666A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "66666", nformat( self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" ), ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( "66,666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "6B6B6B6B6A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10,00,00,000.00", nformat( 100000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, 0), thousand_sep=",", ), ) self.assertEqual( "1,0,00,000,0000.00", nformat( 10000000000.00, decimal_sep=".", decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=",", ), ) self.assertEqual( "10000,00,000.00", nformat( 1000000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, -1), thousand_sep=",", ), ) # This unusual grouping/force_grouping combination may be triggered # by the intcomma filter. self.assertEqual( "10000", nformat( self.long, decimal_sep=".", decimal_pos=0, grouping=0, force_grouping=True, ), ) # date filter self.assertEqual( "31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), ) self.assertEqual( "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) ) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override("fr"): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) # Even a second time (after the format has been cached)... self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override("ca", deactivate=True): self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15", time_format(self.t)) self.assertEqual("31 desembre de 2009", date_format(self.d)) self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1))) self.assertEqual( "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") ) self.assertEqual( "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", localize(self.n)) self.assertEqual("99.999,999", localize(self.f)) self.assertEqual("10.000", localize(self.long)) self.assertEqual("True", localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", localize(self.n)) self.assertEqual("99999,999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("31 desembre de 2009", localize(self.d)) self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm( { "decimal_field": "66.666,666", "float_field": "99.999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertTrue(form3.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form3.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form3.cleaned_data["time_field"] ) self.assertEqual(1234, form3.cleaned_data["integer_field"]) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual( "31 desembre de 2009", Template("{{ d }}").render(self.ctxt) ) self.assertEqual( "31 desembre de 2009 a les 20:50", Template("{{ dt }}").render(self.ctxt), ) self.assertEqual( "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000,0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66.666,67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100.000,0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "31/12/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "31/12/2009 20:50", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) self.assertEqual( date_format(datetime.datetime.now()), Template('{% now "DATE_FORMAT" %}').render(self.ctxt), ) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form4.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form4.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form4.cleaned_data["time_field"] ) self.assertEqual(1234, form4.cleaned_data["integer_field"]) form5 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form5.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # Russian locale (with E as month) with translation.override("ru", deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' "</option>" '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' "</option>" "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # English locale with translation.override("en", deactivate=True): self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("Dec. 31, 2009", date_format(self.d)) self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", localize(self.n)) self.assertEqual("99,999.999", localize(self.f)) self.assertEqual("10,000", localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Dec. 31, 2009", localize(self.d)) self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000.0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66,666.67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100,000.0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form5 = I18nForm( { "decimal_field": "66666.666", "float_field": "99999.999", "date_field": "12/31/2009", "datetime_field": "12/31/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form5.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form5.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data["datetime_field"], ) self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) self.assertEqual(1234, form5.cleaned_data["integer_field"]) form6 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form6.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de-at", deactivate=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) with translation.override("es-us", deactivate=True): self.assertEqual("31 de diciembre de 2009", date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): form6 = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" ' ' maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" ' ' id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' " required></li>" '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" ' ' id="id_products_delivered" required>' "</li>", ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00", ) self.assertEqual( datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"], ) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul(), ) def test_localized_input_func(self): tests = ( (True, "True"), (datetime.date(1, 1, 1), "0001-01-01"), (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_strftime_format(self): for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%C", "%02d" % (year // 100)), ("%F", "%04d-01-01" % year), ("%G", "%04d" % year), ("%Y", "%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_strftime_format_with_escaped_percent(self): dt = datetime.date(1, 1, 1) for fmt, expected in [ ("%%C", "%C"), ("%%F", "%F"), ("%%G", "%G"), ("%%Y", "%Y"), ("%%%%C", "%%C"), ("%%%%F", "%%F"), ("%%%%G", "%%G"), ("%%%%Y", "%%Y"), ]: with self.subTest(fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%%%C", "%%%02d" % (year // 100)), ("%%%F", "%%%04d-01-01" % year), ("%%%G", "%%%04d" % year), ("%%%Y", "%%%04d" % year), ("%%%%%C", "%%%%%02d" % (year // 100)), ("%%%%%F", "%%%%%04d-01-01" % year), ("%%%%%G", "%%%%%04d" % year), ("%%%%%Y", "%%%%%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override("ru", deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") self.assertEqual(sanitize_separators("12 345"), "12345") self.assertEqual(sanitize_separators("77 777,777"), "77777.777") with translation.override(None): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats( get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," ): self.assertEqual(sanitize_separators("10.234"), "10234") # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators("10.10"), "10.10") with translation.override(None): with self.settings(DECIMAL_SEPARATOR=","): self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") with self.settings( DECIMAL_SEPARATOR=",", THOUSAND_SEPARATOR=".", USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(sanitize_separators("1.001,10"), "1001.10") self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") # Invalid output. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module("django.conf.locale.de.formats") test_mod = import_module("i18n.other.locale.de.formats") test_mod2 = import_module("i18n.other2.locale.de.formats") with translation.override("de-at", deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules("de")), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules("de", "i18n.other.locale")), [test_mod, default_mod], ) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list( iter_format_modules( "de", ["i18n.other.locale", "i18n.other2.locale"] ) ), [test_mod, test_mod2, default_mod], ) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module("django.conf.locale.en.formats") en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") self.assertEqual( list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] ) def test_get_format_modules_lang(self): with translation.override("de", deactivate=True): self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) def test_get_format_lazy_format(self): self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context( {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} ) template1 = Template( "{% load l10n %}{% localize %}" "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" ) template2 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " "{{ int }}/{{ float }}/{{ date }}" ) template3 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" ) expected_localized = "1.455/3,14/31. Dezember 2016" expected_unlocalized = "1455/3.14/Dez. 31, 2016" output1 = "; ".join([expected_localized, expected_localized]) output2 = "; ".join( [expected_localized, expected_unlocalized, expected_localized] ) output3 = "; ".join([expected_localized, expected_unlocalized]) with translation.override("de", deactivate=True): with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_off_numbers(self): """A string representation is returned for unlocalized numbers.""" template = Template( "{% load l10n %}{% localize off %}" "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" ) context = Context( {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} ) with self.settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") def test_localized_as_text_as_hidden_input(self): """ Form input with 'as_hidden' or 'as_text' is correctly localized. """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): template = Template( "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" ) template_as_text = Template( "{% load l10n %}" "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" ) template_as_hidden = Template( "{% load l10n %}" "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" ) form = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) context = Context({"form": form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" ' 'value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" ' 'value="59,47">', ) def test_format_arbitrary_settings(self): self.assertEqual(get_format("DEBUG"), "DEBUG") def test_get_custom_format(self): reset_format_cache() with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): with translation.override("fr", deactivate=True): self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile("%([^BcdHImMpSwxXyY%])") for language_code, language_name in settings.LANGUAGES: for format_name in ( "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name), ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE="de") def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override("en"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-us"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-ca"): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ("de", [("de", 1.0)]), ("en-AU", [("en-au", 1.0)]), ("es-419", [("es-419", 1.0)]), ("*;q=1.00", [("*", 1.0)]), ("en-AU;q=0.123", [("en-au", 0.123)]), ("en-au;q=0.5", [("en-au", 0.5)]), ("en-au;q=1.0", [("en-au", 1.0)]), ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), ("en-au-xx", [("en-au-xx", 1.0)]), ( "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", [ ("de", 1.0), ("en-au", 0.75), ("en-us", 0.5), ("en", 0.25), ("es", 0.125), ("fa", 0.125), ], ), ("*", [("*", 1.0)]), ("de;q=0.", [("de", 0.0)]), ("en; q=1,", [("en", 1.0)]), ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), ( "en" + "-x" * 20, [("en-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x", 1.0)], ), ( ", ".join(["en; q=1.0"] * 20), [("en", 1.0)] * 20, ), # Bad headers ("en-gb;q=1.0000", []), ("en;q=0.1234", []), ("en;q=.2", []), ("abcdefghi-au", []), ("**", []), ("en,,gb", []), ("en-au;q=0.1.0", []), (("X" * 97) + "Z,en", []), ("da, en-gb;q=0.8, en;q=0.7,#", []), ("de;q=2.0", []), ("de;q=0.a", []), ("12-345", []), ("", []), ("en;q=1e0", []), ("en-au;q=1.0", []), # Invalid as language-range value too long. ("xxxxxxxx" + "-xxxxxxxx" * 500, []), # Header value too long, only parse up to limit. (", ".join(["en; q=1.0"] * 500), [("en", 1.0)] * 45), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual( trans_real.parse_accept_lang_header(value), tuple(expected) ) def test_parse_literal_http_header(self): tests = [ ("pt-br", "pt-br"), ("pt", "pt"), ("es,de", "es"), ("es-a,de", "es"), # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the # preferred language, the main 'es' translation should be selected # instead. ("es-us", "es"), # There isn't a main language (zh) translation of Django but there # is a translation to variation (zh-hans) the user sets zh-hans as # the preferred language, it should be selected without falling # back nor ignoring it. ("zh-hans,de", "zh-hans"), ("NL", "nl"), ("fy", "fy"), ("ia", "ia"), ("sr-latn", "sr-latn"), ("zh-hans", "zh-hans"), ("zh-hant", "zh-hant"), ] for header, expected in tests: with self.subTest(header=header): request = self.rf.get("/", headers={"accept-language": header}) self.assertEqual(get_language_from_request(request), expected) @override_settings( LANGUAGES=[ ("en", "English"), ("zh-hans", "Simplified Chinese"), ("zh-hant", "Traditional Chinese"), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "zh-cn,en"}) self.assertEqual(g(request), "zh-hans") request = self.rf.get("/", headers={"accept-language": "zh-tw,en"}) self.assertEqual(g(request), "zh-hant") def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ request = self.rf.get("/", headers={"accept-language": "zh-my,en"}) self.assertEqual(get_language_from_request(request), "zh-hans") def test_subsequent_code_fallback_language(self): """ Subsequent language codes should be used when the language code is not supported. """ tests = [ ("zh-Hans-CN", "zh-hans"), ("zh-hans-mo", "zh-hans"), ("zh-hans-HK", "zh-hans"), ("zh-Hant-HK", "zh-hant"), ("zh-hant-tw", "zh-hant"), ("zh-hant-SG", "zh-hant"), ] for value, expected in tests: with self.subTest(value=value): request = self.rf.get("/", headers={"accept-language": f"{value},en"}) self.assertEqual(get_language_from_request(request), expected) def test_parse_language_cookie(self): g = get_language_from_request request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br" self.assertEqual("pt-br", g(request)) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt" self.assertEqual("pt", g(request)) request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es" self.assertEqual("es", g(request)) # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the preferred # language, the main 'es' translation should be selected instead. request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us" self.assertEqual(g(request), "es") # There isn't a main language (zh) translation of Django but there is a # translation to variation (zh-hans) the user sets zh-hans as the # preferred language, it should be selected without falling back nor # ignoring it. request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans" self.assertEqual(g(request), "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("ar-dz", "Algerian Arabic"), ("de", "German"), ("de-at", "Austrian German"), ("pt-BR", "Portuguese (Brazil)"), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g("en"), "en") self.assertEqual(g("en-gb"), "en") self.assertEqual(g("de"), "de") self.assertEqual(g("de-at"), "de-at") self.assertEqual(g("de-ch"), "de") self.assertEqual(g("pt-br"), "pt-br") self.assertEqual(g("pt-BR"), "pt-BR") self.assertEqual(g("pt"), "pt-br") self.assertEqual(g("pt-pt"), "pt-br") self.assertEqual(g("ar-dz"), "ar-dz") self.assertEqual(g("ar-DZ"), "ar-DZ") with self.assertRaises(LookupError): g("pt", strict=True) with self.assertRaises(LookupError): g("pt-pt", strict=True) with self.assertRaises(LookupError): g("xyz") with self.assertRaises(LookupError): g("xy-zz") def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g("pt") with self.assertRaises(LookupError): g("de") with self.assertRaises(LookupError): g("de-at") with self.assertRaises(LookupError): g("de", strict=True) with self.assertRaises(LookupError): g("de-at", strict=True) with self.assertRaises(LookupError): g("xyz") @override_settings( LANGUAGES=[ ("en", "English"), ("en-latn-us", "Latin English"), ("de", "German"), ("de-1996", "German, orthography of 1996"), ("de-at", "Austrian German"), ("de-ch-1901", "German, Swiss variant, traditional orthography"), ("i-mingo", "Mingo"), ("kl-tunumiit", "Tunumiisiut"), ("nan-hani-tw", "Hanji"), ("pl", "Polish"), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path tests = [ ("/pl/", "pl"), ("/pl", "pl"), ("/xyz/", None), ("/en/", "en"), ("/en-gb/", "en"), ("/en-latn-us/", "en-latn-us"), ("/en-Latn-US/", "en-Latn-US"), ("/de/", "de"), ("/de-1996/", "de-1996"), ("/de-at/", "de-at"), ("/de-AT/", "de-AT"), ("/de-ch/", "de"), ("/de-ch-1901/", "de-ch-1901"), ("/de-simple-page-test/", None), ("/i-mingo/", "i-mingo"), ("/kl-tunumiit/", "kl-tunumiit"), ("/nan-hani-tw/", "nan-hani-tw"), ] for path, language in tests: with self.subTest(path=path): self.assertEqual(g(path), language) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g("/pl/")) self.assertIsNone(g("/pl")) self.assertIsNone(g("/xyz/")) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "pt-br"}) self.assertEqual("pt-br", g(request)) with self.settings(LANGUAGES=[("en", "English")]): self.assertNotEqual("pt-br", g(request)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate("de") def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is " "'%s'." % (msgstr, msgid, result), ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE="de") def test_app_translation(self): # Original translation. self.assertGettext("Date/time", "Datum/Zeit") # Different translation. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): # Force refreshing translations. activate("de") # Doesn't work because it's added later in the list. self.assertGettext("Date/time", "Datum/Zeit") with self.modify_settings( INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} ): # Force refreshing translations. activate("de") # Unless the original is removed from the list. self.assertGettext("Date/time", "Datum/Zeit (APP)") @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS") class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext("Date/time"), "Datum/Zeit") @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override("de-de"): self.assertGettext("Test 1 (en)", "(de-de)") self.assertGettext("Test 2 (en)", "(de)") class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString("Iñtërnâtiônàlizætiøn1") c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info("de") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info("xx") with translation.override("xx"): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info("de-xx") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info("xx-xx") def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info("zh-my") self.assertEqual(li["code"], "zh-hans") li = get_language_info("zh-hans") self.assertEqual(li["code"], "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get("/fr/streaming/") self.assertContains(response, "Oui/Non") response = self.client.get("/en/streaming/") self.assertContains(response, "Yes/No") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="en", ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") @override_settings(LANGUAGE_CODE="en-us") def test_default_lang_fallback_without_prefix(self): response = self.client.get("/simple/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Yes") def test_other_lang_with_prefix(self): response = self.client.get("/fr/simple/") self.assertEqual(response.content, b"Oui") def test_unprefixed_language_other_than_accept_language(self): response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr") self.assertEqual(response.content, b"Yes") def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get("/de-simple-page-test/") self.assertEqual(response.content, b"Yes") def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get("/group1/group2/") self.assertEqual(response.status_code, 200) response = self.client.get("/nonexistent/") self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ("bg", "Bulgarian"), ("en-us", "English"), ("pt-br", "Portuguese (Brazil)"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language("en")) self.assertTrue(check_for_language("en-us")) self.assertTrue(check_for_language("en-US")) self.assertFalse(check_for_language("en_US")) self.assertTrue(check_for_language("be")) self.assertTrue(check_for_language("be@latin")) self.assertTrue(check_for_language("sr-RS@latin")) self.assertTrue(check_for_language("sr-RS@12345")) self.assertFalse(check_for_language("en-ü")) self.assertFalse(check_for_language("en\x00")) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language("be@ ")) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language("tr-TR.UTF-8")) self.assertFalse(check_for_language("tr-TR.UTF8")) self.assertFalse(check_for_language("de-DE.utf-8")) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language("en"), True) def test_get_language_from_request(self): # issue 19919 request = self.rf.get( "/", headers={"accept-language": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("en-us", lang) request = self.rf.get( "/", headers={"accept-language": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("bg", lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "en") with override_settings(LANGUAGE_CODE="de"): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "de") def test_specific_language_codes(self): # issue 11915 request = self.rf.get( "/", headers={"accept-language": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) request = self.rf.get( "/", headers={"accept-language": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate("en") class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), ("xxx", "Somelanguage"), ], LANGUAGE_CODE="xxx", LOCALE_PATHS=[os.path.join(here, "commands", "locale")], ) def test_non_django_language(self): self.assertEqual(get_language(), "xxx") self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) open( os.path.join( app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" ), "w", ).close() app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) with mock.patch( "django.apps.apps.get_app_configs", return_value=[app_config] ): self.assertIs(check_for_language("dummy-lang"), True) @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), # xyz language has no locale files ("xyz", "XYZ"), ], ) @translation.override("xyz") def test_plural_non_django_language(self): self.assertEqual(get_language(), "xyz") self.assertEqual(ngettext("year", "years", 2), "years") @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {"foo": "bar"} path = Path("test.py") self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {"foo": "bar"}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {"foo": "bar"} trans_real._translations = {"foo": "bar"} trans_real._default = 1 trans_real._active = False path = Path("test.mo") self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0.0, 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1.0, 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0.0, 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1.0, -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
eeb52e5cf52b0274382585e704f323336ad5cb20915e801710396d1dda750f6b
import collections.abc from datetime import datetime from math import ceil from operator import attrgetter from unittest import skipUnless from django.core.exceptions import FieldError from django.db import connection, models from django.db.models import ( BooleanField, Case, Exists, ExpressionWrapper, F, Max, OuterRef, Q, Subquery, Value, When, ) from django.db.models.functions import Abs, Cast, Length, Substr from django.db.models.lookups import ( Exact, GreaterThan, GreaterThanOrEqual, IsNull, LessThan, LessThanOrEqual, ) from django.test import TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps, register_lookup from .models import ( Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Product, Season, Stock, Tag, ) class LookupTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Authors. cls.au1 = Author.objects.create(name="Author 1", alias="a1") cls.au2 = Author.objects.create(name="Author 2", alias="a2") # Create a few Articles. cls.a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), author=cls.au1, slug="a1", ) cls.a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a2", ) cls.a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a3", ) cls.a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), author=cls.au1, slug="a4", ) cls.a5 = Article.objects.create( headline="Article 5", pub_date=datetime(2005, 8, 1, 9, 0), author=cls.au2, slug="a5", ) cls.a6 = Article.objects.create( headline="Article 6", pub_date=datetime(2005, 8, 1, 8, 0), author=cls.au2, slug="a6", ) cls.a7 = Article.objects.create( headline="Article 7", pub_date=datetime(2005, 7, 27), author=cls.au2, slug="a7", ) # Create a few Tags. cls.t1 = Tag.objects.create(name="Tag 1") cls.t1.articles.add(cls.a1, cls.a2, cls.a3) cls.t2 = Tag.objects.create(name="Tag 2") cls.t2.articles.add(cls.a3, cls.a4, cls.a5) cls.t3 = Tag.objects.create(name="Tag 3") cls.t3.articles.add(cls.a5, cls.a6, cls.a7) def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertSequenceEqual( Article.objects.filter(id__iexact=str(self.a1.id)), [self.a1], ) @skipUnlessDBFeature("supports_date_lookup_using_string") def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertSequenceEqual( Article.objects.filter(pub_date__startswith="2005"), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator) self.assertQuerySetEqual( Article.objects.iterator(), [ "Article 5", "Article 6", "Article 4", "Article 2", "Article 3", "Article 7", "Article 1", ], transform=attrgetter("headline"), ) # iterator() can be used on any QuerySet. self.assertQuerySetEqual( Article.objects.filter(headline__endswith="4").iterator(), ["Article 4"], transform=attrgetter("headline"), ) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3 ) self.assertEqual( Article.objects.filter(headline__startswith="Blah blah").count(), 0 ) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual( Article.objects.filter(pub_date__exact="2005-07-27 00:00:00").count(), 3 ) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual( Article.objects.in_bulk(), { self.a1.id: self.a1, self.a2.id: self.a2, self.a3.id: self.a3, self.a4.id: self.a4, self.a5.id: self.a5, self.a6.id: self.a6, self.a7.id: self.a7, }, ) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3}) self.assertEqual( Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3} ) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual( Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1} ) self.assertEqual(Article.objects.in_bulk(iter([])), {}) with self.assertRaises(TypeError): Article.objects.in_bulk(headline__startswith="Blah") def test_in_bulk_lots_of_ids(self): test_range = 2000 max_query_params = connection.features.max_query_params expected_num_queries = ( ceil(test_range / max_query_params) if max_query_params else 1 ) Author.objects.bulk_create( [Author() for i in range(test_range - Author.objects.count())] ) authors = {author.pk: author for author in Author.objects.all()} with self.assertNumQueries(expected_num_queries): self.assertEqual(Author.objects.in_bulk(authors), authors) def test_in_bulk_with_field(self): self.assertEqual( Article.objects.in_bulk( [self.a1.slug, self.a2.slug, self.a3.slug], field_name="slug" ), { self.a1.slug: self.a1, self.a2.slug: self.a2, self.a3.slug: self.a3, }, ) def test_in_bulk_meta_constraint(self): season_2011 = Season.objects.create(year=2011) season_2012 = Season.objects.create(year=2012) Season.objects.create(year=2013) self.assertEqual( Season.objects.in_bulk( [season_2011.year, season_2012.year], field_name="year", ), {season_2011.year: season_2011, season_2012.year: season_2012}, ) def test_in_bulk_non_unique_field(self): msg = "in_bulk()'s field_name must be a unique field but 'author' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.in_bulk([self.au1], field_name="author") @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_preserve_ordering(self): articles = ( Article.objects.order_by("author_id", "-pub_date") .distinct("author_id") .in_bulk([self.au1.id, self.au2.id], field_name="author_id") ) self.assertEqual( articles, {self.au1.id: self.a4, self.au2.id: self.a5}, ) @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_preserve_ordering_with_batch_size(self): old_max_query_params = connection.features.max_query_params connection.features.max_query_params = 1 try: articles = ( Article.objects.order_by("author_id", "-pub_date") .distinct("author_id") .in_bulk([self.au1.id, self.au2.id], field_name="author_id") ) self.assertEqual( articles, {self.au1.id: self.a4, self.au2.id: self.a5}, ) finally: connection.features.max_query_params = old_max_query_params @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_distinct_field(self): self.assertEqual( Article.objects.order_by("headline") .distinct("headline") .in_bulk( [self.a1.headline, self.a5.headline], field_name="headline", ), {self.a1.headline: self.a1, self.a5.headline: self.a5}, ) @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_multiple_distinct_field(self): msg = "in_bulk()'s field_name must be a unique field but 'pub_date' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by("headline", "pub_date").distinct( "headline", "pub_date", ).in_bulk(field_name="pub_date") @isolate_apps("lookup") def test_in_bulk_non_unique_meta_constaint(self): class Model(models.Model): ean = models.CharField(max_length=100) brand = models.CharField(max_length=100) name = models.CharField(max_length=80) class Meta: constraints = [ models.UniqueConstraint( fields=["ean"], name="partial_ean_unique", condition=models.Q(is_active=True), ), models.UniqueConstraint( fields=["brand", "name"], name="together_brand_name_unique", ), ] msg = "in_bulk()'s field_name must be a unique field but '%s' isn't." for field_name in ["brand", "ean"]: with self.subTest(field_name=field_name): with self.assertRaisesMessage(ValueError, msg % field_name): Model.objects.in_bulk(field_name=field_name) def test_in_bulk_sliced_queryset(self): msg = "Cannot use 'limit' or 'offset' with in_bulk()." with self.assertRaisesMessage(TypeError, msg): Article.objects.all()[0:5].in_bulk([self.a1.id, self.a2.id]) def test_values(self): # values() returns a list of dictionaries instead of object instances -- # and you can specify which fields you want to retrieve. self.assertSequenceEqual( Article.objects.values("headline"), [ {"headline": "Article 5"}, {"headline": "Article 6"}, {"headline": "Article 4"}, {"headline": "Article 2"}, {"headline": "Article 3"}, {"headline": "Article 7"}, {"headline": "Article 1"}, ], ) self.assertSequenceEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values("id"), [{"id": self.a2.id}, {"id": self.a3.id}, {"id": self.a7.id}], ) self.assertSequenceEqual( Article.objects.values("id", "headline"), [ {"id": self.a5.id, "headline": "Article 5"}, {"id": self.a6.id, "headline": "Article 6"}, {"id": self.a4.id, "headline": "Article 4"}, {"id": self.a2.id, "headline": "Article 2"}, {"id": self.a3.id, "headline": "Article 3"}, {"id": self.a7.id, "headline": "Article 7"}, {"id": self.a1.id, "headline": "Article 1"}, ], ) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertSequenceEqual( list(Article.objects.values("id", "headline").iterator()), [ {"headline": "Article 5", "id": self.a5.id}, {"headline": "Article 6", "id": self.a6.id}, {"headline": "Article 4", "id": self.a4.id}, {"headline": "Article 2", "id": self.a2.id}, {"headline": "Article 3", "id": self.a3.id}, {"headline": "Article 7", "id": self.a7.id}, {"headline": "Article 1", "id": self.a1.id}, ], ) # The values() method works with "extra" fields specified in extra(select). self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_one" ), [ {"id": self.a5.id, "id_plus_one": self.a5.id + 1}, {"id": self.a6.id, "id_plus_one": self.a6.id + 1}, {"id": self.a4.id, "id_plus_one": self.a4.id + 1}, {"id": self.a2.id, "id_plus_one": self.a2.id + 1}, {"id": self.a3.id, "id_plus_one": self.a3.id + 1}, {"id": self.a7.id, "id_plus_one": self.a7.id + 1}, {"id": self.a1.id, "id_plus_one": self.a1.id + 1}, ], ) data = { "id_plus_one": "id+1", "id_plus_two": "id+2", "id_plus_three": "id+3", "id_plus_four": "id+4", "id_plus_five": "id+5", "id_plus_six": "id+6", "id_plus_seven": "id+7", "id_plus_eight": "id+8", } self.assertSequenceEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data), [ { "id_plus_one": self.a1.id + 1, "id_plus_two": self.a1.id + 2, "id_plus_three": self.a1.id + 3, "id_plus_four": self.a1.id + 4, "id_plus_five": self.a1.id + 5, "id_plus_six": self.a1.id + 6, "id_plus_seven": self.a1.id + 7, "id_plus_eight": self.a1.id + 8, } ], ) # You can specify fields from forward and reverse relations, just like filter(). self.assertSequenceEqual( Article.objects.values("headline", "author__name"), [ {"headline": self.a5.headline, "author__name": self.au2.name}, {"headline": self.a6.headline, "author__name": self.au2.name}, {"headline": self.a4.headline, "author__name": self.au1.name}, {"headline": self.a2.headline, "author__name": self.au1.name}, {"headline": self.a3.headline, "author__name": self.au1.name}, {"headline": self.a7.headline, "author__name": self.au2.name}, {"headline": self.a1.headline, "author__name": self.au1.name}, ], ) self.assertSequenceEqual( Author.objects.values("name", "article__headline").order_by( "name", "article__headline" ), [ {"name": self.au1.name, "article__headline": self.a1.headline}, {"name": self.au1.name, "article__headline": self.a2.headline}, {"name": self.au1.name, "article__headline": self.a3.headline}, {"name": self.au1.name, "article__headline": self.a4.headline}, {"name": self.au2.name, "article__headline": self.a5.headline}, {"name": self.au2.name, "article__headline": self.a6.headline}, {"name": self.au2.name, "article__headline": self.a7.headline}, ], ) self.assertSequenceEqual( ( Author.objects.values( "name", "article__headline", "article__tag__name" ).order_by("name", "article__headline", "article__tag__name") ), [ { "name": self.au1.name, "article__headline": self.a1.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a2.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t2.name, }, { "name": self.au1.name, "article__headline": self.a4.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a6.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a7.headline, "article__tag__name": self.t3.name, }, ], ) # However, an exception FieldDoesNotExist will be thrown if you specify # a nonexistent field name in values() (a field that is neither in the # model nor in extra(select)). msg = ( "Cannot resolve keyword 'id_plus_two' into field. Choices are: " "author, author_id, headline, id, id_plus_one, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_two" ) # If you don't specify field names to values(), all are returned. self.assertSequenceEqual( Article.objects.filter(id=self.a5.id).values(), [ { "id": self.a5.id, "author_id": self.au2.id, "headline": "Article 5", "pub_date": datetime(2005, 8, 1, 9, 0), "slug": "a5", } ], ) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elements is the same as the order # of fields in the values_list() call. self.assertSequenceEqual( Article.objects.values_list("headline"), [ ("Article 5",), ("Article 6",), ("Article 4",), ("Article 2",), ("Article 3",), ("Article 7",), ("Article 1",), ], ) self.assertSequenceEqual( Article.objects.values_list("id").order_by("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.values_list("id", flat=True).order_by("id"), [ self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id, ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id_plus_one", "id"), [ (self.a1.id + 1, self.a1.id), (self.a2.id + 1, self.a2.id), (self.a3.id + 1, self.a3.id), (self.a4.id + 1, self.a4.id), (self.a5.id + 1, self.a5.id), (self.a6.id + 1, self.a6.id), (self.a7.id + 1, self.a7.id), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id", "id_plus_one"), [ (self.a1.id, self.a1.id + 1), (self.a2.id, self.a2.id + 1), (self.a3.id, self.a3.id + 1), (self.a4.id, self.a4.id + 1), (self.a5.id, self.a5.id + 1), (self.a6.id, self.a6.id + 1), (self.a7.id, self.a7.id + 1), ], ) args = ("name", "article__headline", "article__tag__name") self.assertSequenceEqual( Author.objects.values_list(*args).order_by(*args), [ (self.au1.name, self.a1.headline, self.t1.name), (self.au1.name, self.a2.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t2.name), (self.au1.name, self.a4.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t3.name), (self.au2.name, self.a6.headline, self.t3.name), (self.au2.name, self.a7.headline, self.t3.name), ], ) with self.assertRaises(TypeError): Article.objects.values_list("id", "headline", flat=True) def test_get_next_previous_by(self): # Every DateField and DateTimeField creates get_next_by_FOO() and # get_previous_by_FOO() methods. In the case of identical date values, # these methods will use the ID as a fallback check. This guarantees # that no records are skipped or duplicated. self.assertEqual(repr(self.a1.get_next_by_pub_date()), "<Article: Article 2>") self.assertEqual(repr(self.a2.get_next_by_pub_date()), "<Article: Article 3>") self.assertEqual( repr(self.a2.get_next_by_pub_date(headline__endswith="6")), "<Article: Article 6>", ) self.assertEqual(repr(self.a3.get_next_by_pub_date()), "<Article: Article 7>") self.assertEqual(repr(self.a4.get_next_by_pub_date()), "<Article: Article 6>") with self.assertRaises(Article.DoesNotExist): self.a5.get_next_by_pub_date() self.assertEqual(repr(self.a6.get_next_by_pub_date()), "<Article: Article 5>") self.assertEqual(repr(self.a7.get_next_by_pub_date()), "<Article: Article 4>") self.assertEqual( repr(self.a7.get_previous_by_pub_date()), "<Article: Article 3>" ) self.assertEqual( repr(self.a6.get_previous_by_pub_date()), "<Article: Article 4>" ) self.assertEqual( repr(self.a5.get_previous_by_pub_date()), "<Article: Article 6>" ) self.assertEqual( repr(self.a4.get_previous_by_pub_date()), "<Article: Article 7>" ) self.assertEqual( repr(self.a3.get_previous_by_pub_date()), "<Article: Article 2>" ) self.assertEqual( repr(self.a2.get_previous_by_pub_date()), "<Article: Article 1>" ) def test_escaping(self): # Underscores, percent signs and backslashes have special meaning in the # underlying SQL code, but Django handles the quoting of them automatically. a8 = Article.objects.create( headline="Article_ with underscore", pub_date=datetime(2005, 11, 20) ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article"), [a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article_"), [a8], ) a9 = Article.objects.create( headline="Article% with percent sign", pub_date=datetime(2005, 11, 21) ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article"), [a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article%"), [a9], ) a10 = Article.objects.create( headline="Article with \\ backslash", pub_date=datetime(2005, 11, 22) ) self.assertSequenceEqual( Article.objects.filter(headline__contains="\\"), [a10], ) def test_exclude(self): pub_date = datetime(2005, 11, 20) a8 = Article.objects.create( headline="Article_ with underscore", pub_date=pub_date ) a9 = Article.objects.create( headline="Article% with percent sign", pub_date=pub_date ) a10 = Article.objects.create( headline="Article with \\ backslash", pub_date=pub_date ) # exclude() is the opposite of filter() when doing lookups: self.assertSequenceEqual( Article.objects.filter(headline__contains="Article").exclude( headline__contains="with" ), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.exclude(headline__startswith="Article_"), [a10, a9, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.exclude(headline="Article 7"), [a10, a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a1], ) def test_none(self): # none() returns a QuerySet that behaves like any other QuerySet object self.assertSequenceEqual(Article.objects.none(), []) self.assertSequenceEqual( Article.objects.none().filter(headline__startswith="Article"), [] ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article").none(), [] ) self.assertEqual(Article.objects.none().count(), 0) self.assertEqual( Article.objects.none().update(headline="This should not take effect"), 0 ) self.assertSequenceEqual(list(Article.objects.none().iterator()), []) def test_in(self): self.assertSequenceEqual( Article.objects.exclude(id__in=[]), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) def test_in_empty_list(self): self.assertSequenceEqual(Article.objects.filter(id__in=[]), []) def test_in_different_database(self): with self.assertRaisesMessage( ValueError, "Subqueries aren't allowed across different databases. Force the " "inner query to be evaluated using `list(inner_query)`.", ): list(Article.objects.filter(id__in=Article.objects.using("other").all())) def test_in_keeps_value_ordering(self): query = ( Article.objects.filter(slug__in=["a%d" % i for i in range(1, 8)]) .values("pk") .query ) self.assertIn(" IN (a1, a2, a3, a4, a5, a6, a7) ", str(query)) def test_in_ignore_none(self): with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( Article.objects.filter(id__in=[None, self.a1.id]), [self.a1], ) sql = ctx.captured_queries[0]["sql"] self.assertIn("IN (%s)" % self.a1.pk, sql) def test_in_ignore_solo_none(self): with self.assertNumQueries(0): self.assertSequenceEqual(Article.objects.filter(id__in=[None]), []) def test_in_ignore_none_with_unhashable_items(self): class UnhashableInt(int): __hash__ = None with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( Article.objects.filter(id__in=[None, UnhashableInt(self.a1.id)]), [self.a1], ) sql = ctx.captured_queries[0]["sql"] self.assertIn("IN (%s)" % self.a1.pk, sql) def test_error_messages(self): # Programming errors are pointed out with nice error messages with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'pub_date_year' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag", ): Article.objects.filter(pub_date_year="2005").count() def test_unsupported_lookups(self): with self.assertRaisesMessage( FieldError, "Unsupported lookup 'starts' for CharField or join on the field " "not permitted, perhaps you meant startswith or istartswith?", ): Article.objects.filter(headline__starts="Article") with self.assertRaisesMessage( FieldError, "Unsupported lookup 'is_null' for DateTimeField or join on the field " "not permitted, perhaps you meant isnull?", ): Article.objects.filter(pub_date__is_null=True) with self.assertRaisesMessage( FieldError, "Unsupported lookup 'gobbledygook' for DateTimeField or join on the field " "not permitted.", ): Article.objects.filter(pub_date__gobbledygook="blahblah") def test_unsupported_lookups_custom_lookups(self): slug_field = Article._meta.get_field("slug") msg = ( "Unsupported lookup 'lengtp' for SlugField or join on the field not " "permitted, perhaps you meant length?" ) with self.assertRaisesMessage(FieldError, msg): with register_lookup(slug_field, Length): Article.objects.filter(slug__lengtp=20) def test_relation_nested_lookup_error(self): # An invalid nested lookup on a related field raises a useful error. msg = ( "Unsupported lookup 'editor' for ForeignKey or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(author__editor__name="James") msg = ( "Unsupported lookup 'foo' for ForeignKey or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(articles__foo="bar") def test_unsupported_lookup_reverse_foreign_key(self): msg = ( "Unsupported lookup 'title' for ManyToOneRel or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Author.objects.filter(article__title="Article 1") def test_unsupported_lookup_reverse_foreign_key_custom_lookups(self): msg = ( "Unsupported lookup 'abspl' for ManyToOneRel or join on the field not " "permitted, perhaps you meant abspk?" ) fk_field = Article._meta.get_field("author") with self.assertRaisesMessage(FieldError, msg): with register_lookup(fk_field, Abs, lookup_name="abspk"): Author.objects.filter(article__abspl=2) def test_filter_by_reverse_related_field_transform(self): fk_field = Article._meta.get_field("author") with register_lookup(fk_field, Abs): self.assertSequenceEqual( Author.objects.filter(article__abs=self.a1.pk), [self.au1] ) def test_regex(self): # Create some articles with a bit more interesting headlines for # testing field lookups. Article.objects.all().delete() now = datetime.now() Article.objects.bulk_create( [ Article(pub_date=now, headline="f"), Article(pub_date=now, headline="fo"), Article(pub_date=now, headline="foo"), Article(pub_date=now, headline="fooo"), Article(pub_date=now, headline="hey-Foo"), Article(pub_date=now, headline="bar"), Article(pub_date=now, headline="AbBa"), Article(pub_date=now, headline="baz"), Article(pub_date=now, headline="baxZ"), ] ) # zero-or-more self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"fo*"), Article.objects.filter(headline__in=["f", "fo", "foo", "fooo"]), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"fo*"), Article.objects.filter(headline__in=["f", "fo", "foo", "fooo", "hey-Foo"]), ) # one-or-more self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"fo+"), Article.objects.filter(headline__in=["fo", "foo", "fooo"]), ) # wildcard self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"fooo?"), Article.objects.filter(headline__in=["foo", "fooo"]), ) # leading anchor self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"^b"), Article.objects.filter(headline__in=["bar", "baxZ", "baz"]), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"^a"), Article.objects.filter(headline="AbBa"), ) # trailing anchor self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"z$"), Article.objects.filter(headline="baz"), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"z$"), Article.objects.filter(headline__in=["baxZ", "baz"]), ) # character sets self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"ba[rz]"), Article.objects.filter(headline__in=["bar", "baz"]), ) self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"ba.[RxZ]"), Article.objects.filter(headline="baxZ"), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"ba[RxZ]"), Article.objects.filter(headline__in=["bar", "baxZ", "baz"]), ) # and more articles: Article.objects.bulk_create( [ Article(pub_date=now, headline="foobar"), Article(pub_date=now, headline="foobaz"), Article(pub_date=now, headline="ooF"), Article(pub_date=now, headline="foobarbaz"), Article(pub_date=now, headline="zoocarfaz"), Article(pub_date=now, headline="barfoobaz"), Article(pub_date=now, headline="bazbaRFOO"), ] ) # alternation self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"oo(f|b)"), Article.objects.filter( headline__in=[ "barfoobaz", "foobar", "foobarbaz", "foobaz", ] ), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"oo(f|b)"), Article.objects.filter( headline__in=[ "barfoobaz", "foobar", "foobarbaz", "foobaz", "ooF", ] ), ) self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"^foo(f|b)"), Article.objects.filter(headline__in=["foobar", "foobarbaz", "foobaz"]), ) # greedy matching self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"b.*az"), Article.objects.filter( headline__in=[ "barfoobaz", "baz", "bazbaRFOO", "foobarbaz", "foobaz", ] ), ) self.assertQuerySetEqual( Article.objects.filter(headline__iregex=r"b.*ar"), Article.objects.filter( headline__in=[ "bar", "barfoobaz", "bazbaRFOO", "foobar", "foobarbaz", ] ), ) @skipUnlessDBFeature("supports_regex_backreferencing") def test_regex_backreferencing(self): # grouping and backreferences now = datetime.now() Article.objects.bulk_create( [ Article(pub_date=now, headline="foobar"), Article(pub_date=now, headline="foobaz"), Article(pub_date=now, headline="ooF"), Article(pub_date=now, headline="foobarbaz"), Article(pub_date=now, headline="zoocarfaz"), Article(pub_date=now, headline="barfoobaz"), Article(pub_date=now, headline="bazbaRFOO"), ] ) self.assertQuerySetEqual( Article.objects.filter(headline__regex=r"b(.).*b\1").values_list( "headline", flat=True ), ["barfoobaz", "bazbaRFOO", "foobarbaz"], ) def test_regex_null(self): """ A regex lookup does not fail on null/None values """ Season.objects.create(year=2012, gt=None) self.assertQuerySetEqual(Season.objects.filter(gt__regex=r"^$"), []) def test_regex_non_string(self): """ A regex lookup does not fail on non-string fields """ s = Season.objects.create(year=2013, gt=444) self.assertQuerySetEqual(Season.objects.filter(gt__regex=r"^444$"), [s]) def test_regex_non_ascii(self): """ A regex lookup does not trip on non-ASCII characters. """ Player.objects.create(name="\u2660") Player.objects.get(name__regex="\u2660") def test_nonfield_lookups(self): """ A lookup query containing non-fields raises the proper exception. """ msg = ( "Unsupported lookup 'blahblah' for CharField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah=99) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah__exact=99) msg = ( "Cannot resolve keyword 'blahblah' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(blahblah=99) def test_lookup_collision(self): """ Genuine field names don't collide with built-in lookup types ('year', 'gt', 'range', 'in' etc.) (#11670). """ # 'gt' is used as a code number for the year, e.g. 111=>2009. season_2009 = Season.objects.create(year=2009, gt=111) season_2009.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2010 = Season.objects.create(year=2010, gt=222) season_2010.games.create(home="Houston Astros", away="Chicago Cubs") season_2010.games.create(home="Houston Astros", away="Milwaukee Brewers") season_2010.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011 = Season.objects.create(year=2011, gt=333) season_2011.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011.games.create(home="Houston Astros", away="Milwaukee Brewers") hunter_pence = Player.objects.create(name="Hunter Pence") hunter_pence.games.set(Game.objects.filter(season__year__in=[2009, 2010])) pudge = Player.objects.create(name="Ivan Rodriquez") pudge.games.set(Game.objects.filter(season__year=2009)) pedro_feliz = Player.objects.create(name="Pedro Feliz") pedro_feliz.games.set(Game.objects.filter(season__year__in=[2011])) johnson = Player.objects.create(name="Johnson") johnson.games.set(Game.objects.filter(season__year__in=[2011])) # Games in 2010 self.assertEqual(Game.objects.filter(season__year=2010).count(), 3) self.assertEqual(Game.objects.filter(season__year__exact=2010).count(), 3) self.assertEqual(Game.objects.filter(season__gt=222).count(), 3) self.assertEqual(Game.objects.filter(season__gt__exact=222).count(), 3) # Games in 2011 self.assertEqual(Game.objects.filter(season__year=2011).count(), 2) self.assertEqual(Game.objects.filter(season__year__exact=2011).count(), 2) self.assertEqual(Game.objects.filter(season__gt=333).count(), 2) self.assertEqual(Game.objects.filter(season__gt__exact=333).count(), 2) self.assertEqual(Game.objects.filter(season__year__gt=2010).count(), 2) self.assertEqual(Game.objects.filter(season__gt__gt=222).count(), 2) # Games played in 2010 and 2011 self.assertEqual(Game.objects.filter(season__year__in=[2010, 2011]).count(), 5) self.assertEqual(Game.objects.filter(season__year__gt=2009).count(), 5) self.assertEqual(Game.objects.filter(season__gt__in=[222, 333]).count(), 5) self.assertEqual(Game.objects.filter(season__gt__gt=111).count(), 5) # Players who played in 2009 self.assertEqual( Player.objects.filter(games__season__year=2009).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2009).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt=111).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt__exact=111).distinct().count(), 2 ) # Players who played in 2010 self.assertEqual( Player.objects.filter(games__season__year=2010).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2010).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__gt=222).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__gt__exact=222).distinct().count(), 1 ) # Players who played in 2011 self.assertEqual( Player.objects.filter(games__season__year=2011).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2011).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt=333).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__gt=2010).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt__gt=222).distinct().count(), 2 ) def test_chain_date_time_lookups(self): self.assertCountEqual( Article.objects.filter(pub_date__month__gt=7), [self.a5, self.a6], ) self.assertCountEqual( Article.objects.filter(pub_date__day__gte=27), [self.a2, self.a3, self.a4, self.a7], ) self.assertCountEqual( Article.objects.filter(pub_date__hour__lt=8), [self.a1, self.a2, self.a3, self.a4, self.a7], ) self.assertCountEqual( Article.objects.filter(pub_date__minute__lte=0), [self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7], ) def test_exact_none_transform(self): """Transforms are used for __exact=None.""" Season.objects.create(year=1, nulled_text_field="not null") self.assertFalse(Season.objects.filter(nulled_text_field__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__exact=None)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled=None)) def test_exact_sliced_queryset_limit_one(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[:1]), [self.a1, self.a2, self.a3, self.a4], ) def test_exact_sliced_queryset_limit_one_offset(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[1:2]), [self.a5, self.a6, self.a7], ) def test_exact_sliced_queryset_not_limited_to_one(self): msg = ( "The QuerySet value for an exact lookup must be limited to one " "result using slicing." ) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[:2])) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[1:])) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.") def test_exact_booleanfield(self): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. product = Product.objects.create(name="Paper", qty_target=5000) Stock.objects.create(product=product, short=False, qty_available=5100) stock_1 = Stock.objects.create(product=product, short=True, qty_available=180) qs = Stock.objects.filter(short=True) self.assertSequenceEqual(qs, [stock_1]) self.assertIn( "%s = True" % connection.ops.quote_name("short"), str(qs.query), ) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.") def test_exact_booleanfield_annotation(self): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. qs = Author.objects.annotate( case=Case( When(alias="a1", then=True), default=False, output_field=BooleanField(), ) ).filter(case=True) self.assertSequenceEqual(qs, [self.au1]) self.assertIn(" = True", str(qs.query)) qs = Author.objects.annotate( wrapped=ExpressionWrapper(Q(alias="a1"), output_field=BooleanField()), ).filter(wrapped=True) self.assertSequenceEqual(qs, [self.au1]) self.assertIn(" = True", str(qs.query)) # EXISTS(...) shouldn't be compared to a boolean value. qs = Author.objects.annotate( exists=Exists(Author.objects.filter(alias="a1", pk=OuterRef("pk"))), ).filter(exists=True) self.assertSequenceEqual(qs, [self.au1]) self.assertNotIn(" = True", str(qs.query)) def test_custom_field_none_rhs(self): """ __exact=value is transformed to __isnull=True if Field.get_prep_value() converts value to None. """ season = Season.objects.create(year=2012, nulled_text_field=None) self.assertTrue( Season.objects.filter(pk=season.pk, nulled_text_field__isnull=True) ) self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field="")) def test_pattern_lookups_with_substr(self): a = Author.objects.create(name="John Smith", alias="Johx") b = Author.objects.create(name="Rhonda Simpson", alias="sonx") tests = ( ("startswith", [a]), ("istartswith", [a]), ("contains", [a, b]), ("icontains", [a, b]), ("endswith", [b]), ("iendswith", [b]), ) for lookup, result in tests: with self.subTest(lookup=lookup): authors = Author.objects.filter( **{"name__%s" % lookup: Substr("alias", 1, 3)} ) self.assertCountEqual(authors, result) def test_custom_lookup_none_rhs(self): """Lookup.can_use_none_as_rhs=True allows None as a lookup value.""" season = Season.objects.create(year=2012, nulled_text_field=None) query = Season.objects.get_queryset().query field = query.model._meta.get_field("nulled_text_field") self.assertIsInstance( query.build_lookup(["isnull_none_rhs"], field, None), IsNullWithNoneAsRHS ) self.assertTrue( Season.objects.filter(pk=season.pk, nulled_text_field__isnull_none_rhs=True) ) def test_exact_exists(self): qs = Article.objects.filter(pk=OuterRef("pk")) seasons = Season.objects.annotate(pk_exists=Exists(qs)).filter( pk_exists=Exists(qs), ) self.assertCountEqual(seasons, Season.objects.all()) def test_nested_outerref_lhs(self): tag = Tag.objects.create(name=self.au1.alias) tag.articles.add(self.a1) qs = Tag.objects.annotate( has_author_alias_match=Exists( Article.objects.annotate( author_exists=Exists( Author.objects.filter(alias=OuterRef(OuterRef("name"))) ), ).filter(author_exists=True) ), ) self.assertEqual(qs.get(has_author_alias_match=True), tag) def test_exact_query_rhs_with_selected_columns(self): newest_author = Author.objects.create(name="Author 2") authors_max_ids = ( Author.objects.filter( name="Author 2", ) .values( "name", ) .annotate( max_id=Max("id"), ) .values("max_id") ) authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) def test_isnull_non_boolean_value(self): msg = "The QuerySet value for an isnull lookup must be True or False." tests = [ Author.objects.filter(alias__isnull=1), Article.objects.filter(author__isnull=1), Season.objects.filter(games__isnull=1), Freebie.objects.filter(stock__isnull=1), ] for qs in tests: with self.subTest(qs=qs): with self.assertRaisesMessage(ValueError, msg): qs.exists() def test_lookup_rhs(self): product = Product.objects.create(name="GME", qty_target=5000) stock_1 = Stock.objects.create(product=product, short=True, qty_available=180) stock_2 = Stock.objects.create(product=product, short=False, qty_available=5100) Stock.objects.create(product=product, short=False, qty_available=4000) self.assertCountEqual( Stock.objects.filter(short=Q(qty_available__lt=F("product__qty_target"))), [stock_1, stock_2], ) self.assertCountEqual( Stock.objects.filter( short=ExpressionWrapper( Q(qty_available__lt=F("product__qty_target")), output_field=BooleanField(), ) ), [stock_1, stock_2], ) class LookupQueryingTests(TestCase): @classmethod def setUpTestData(cls): cls.s1 = Season.objects.create(year=1942, gt=1942) cls.s2 = Season.objects.create(year=1842, gt=1942, nulled_text_field="text") cls.s3 = Season.objects.create(year=2042, gt=1942) Game.objects.create(season=cls.s1, home="NY", away="Boston") Game.objects.create(season=cls.s1, home="NY", away="Tampa") Game.objects.create(season=cls.s3, home="Boston", away="Tampa") def test_annotate(self): qs = Season.objects.annotate(equal=Exact(F("year"), 1942)) self.assertCountEqual( qs.values_list("year", "equal"), ((1942, True), (1842, False), (2042, False)), ) def test_alias(self): qs = Season.objects.alias(greater=GreaterThan(F("year"), 1910)) self.assertCountEqual(qs.filter(greater=True), [self.s1, self.s3]) def test_annotate_value_greater_than_value(self): qs = Season.objects.annotate(greater=GreaterThan(Value(40), Value(30))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, True), (2042, True)), ) def test_annotate_field_greater_than_field(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), F("gt"))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, False), (2042, True)), ) def test_annotate_field_greater_than_value(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), Value(1930))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_field_greater_than_literal(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), 1930)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_literal_greater_than_field(self): qs = Season.objects.annotate(greater=GreaterThan(1930, F("year"))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, True), (2042, False)), ) def test_annotate_less_than_float(self): qs = Season.objects.annotate(lesser=LessThan(F("year"), 1942.1)) self.assertCountEqual( qs.values_list("year", "lesser"), ((1942, True), (1842, True), (2042, False)), ) def test_annotate_greater_than_or_equal(self): qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_greater_than_or_equal_float(self): qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942.1)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, False), (2042, True)), ) def test_combined_lookups(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression) self.assertCountEqual( qs.values_list("year", "gte"), ((1942, True), (1842, False), (2042, True)), ) def test_lookup_in_filter(self): qs = Season.objects.filter(GreaterThan(F("year"), 1910)) self.assertCountEqual(qs, [self.s1, self.s3]) def test_isnull_lookup_in_filter(self): self.assertSequenceEqual( Season.objects.filter(IsNull(F("nulled_text_field"), False)), [self.s2], ) self.assertCountEqual( Season.objects.filter(IsNull(F("nulled_text_field"), True)), [self.s1, self.s3], ) def test_filter_lookup_lhs(self): qs = Season.objects.annotate(before_20=LessThan(F("year"), 2000)).filter( before_20=LessThan(F("year"), 1900), ) self.assertCountEqual(qs, [self.s2, self.s3]) def test_filter_wrapped_lookup_lhs(self): qs = ( Season.objects.annotate( before_20=ExpressionWrapper( Q(year__lt=2000), output_field=BooleanField(), ) ) .filter(before_20=LessThan(F("year"), 1900)) .values_list("year", flat=True) ) self.assertCountEqual(qs, [1842, 2042]) def test_filter_exists_lhs(self): qs = Season.objects.annotate( before_20=Exists( Season.objects.filter(pk=OuterRef("pk"), year__lt=2000), ) ).filter(before_20=LessThan(F("year"), 1900)) self.assertCountEqual(qs, [self.s2, self.s3]) def test_filter_subquery_lhs(self): qs = Season.objects.annotate( before_20=Subquery( Season.objects.filter(pk=OuterRef("pk")).values( lesser=LessThan(F("year"), 2000), ), ) ).filter(before_20=LessThan(F("year"), 1900)) self.assertCountEqual(qs, [self.s2, self.s3]) def test_combined_lookups_in_filter(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.filter(expression) self.assertCountEqual(qs, [self.s1, self.s3]) def test_combined_annotated_lookups_in_filter(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression).filter(gte=True) self.assertCountEqual(qs, [self.s1, self.s3]) def test_combined_annotated_lookups_in_filter_false(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression).filter(gte=False) self.assertSequenceEqual(qs, [self.s2]) def test_lookup_in_order_by(self): qs = Season.objects.order_by(LessThan(F("year"), 1910), F("year")) self.assertSequenceEqual(qs, [self.s1, self.s3, self.s2]) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_aggregate_combined_lookup(self): expression = Cast(GreaterThan(F("year"), 1900), models.IntegerField()) qs = Season.objects.aggregate(modern=models.Sum(expression)) self.assertEqual(qs["modern"], 2) def test_conditional_expression(self): qs = Season.objects.annotate( century=Case( When( GreaterThan(F("year"), 1900) & LessThanOrEqual(F("year"), 2000), then=Value("20th"), ), default=Value("other"), ) ).values("year", "century") self.assertCountEqual( qs, [ {"year": 1942, "century": "20th"}, {"year": 1842, "century": "other"}, {"year": 2042, "century": "other"}, ], ) def test_multivalued_join_reuse(self): self.assertEqual( Season.objects.get(Exact(F("games__home"), "NY"), games__away="Boston"), self.s1, ) self.assertEqual( Season.objects.get(Exact(F("games__home"), "NY") & Q(games__away="Boston")), self.s1, ) self.assertEqual( Season.objects.get( Exact(F("games__home"), "NY") & Exact(F("games__away"), "Boston") ), self.s1, )
7947b1248e7478eccbbfea64a707289a4845a118fe2dac2e841bea971acf73df
from django.core.exceptions import FieldDoesNotExist, FieldError from django.test import SimpleTestCase, TestCase from .models import ( BigChild, Child, ChildProxy, Primary, RefreshPrimaryProxy, Secondary, ShadowChild, ) class AssertionMixin: def assert_delayed(self, obj, num): """ Instances with deferred fields look the same as normal instances when we examine attribute values. Therefore, this method returns the number of deferred fields on returned instances. """ count = len(obj.get_deferred_fields()) self.assertEqual(count, num) class DeferTests(AssertionMixin, TestCase): @classmethod def setUpTestData(cls): cls.s1 = Secondary.objects.create(first="x1", second="y1") cls.p1 = Primary.objects.create(name="p1", value="xx", related=cls.s1) def test_defer(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name")[0], 1) self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1) self.assert_delayed(qs.defer("related__first")[0], 0) self.assert_delayed(qs.defer("name").defer("value")[0], 2) def test_only(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name")[0], 2) self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2) self.assert_delayed(qs.only("name").only("value")[0], 2) self.assert_delayed(qs.only("related__first")[0], 2) # Using 'pk' with only() should result in 3 deferred fields, namely all # of them except the model's primary key see #15494 self.assert_delayed(qs.only("pk")[0], 3) # You can use 'pk' with reverse foreign key lookups. # The related_id is always set even if it's not fetched from the DB, # so pk and related_id are not deferred. self.assert_delayed(self.s1.primary_set.only("pk")[0], 2) def test_defer_only_chaining(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name", "value").defer("name")[0], 2) self.assert_delayed(qs.defer("name").only("value", "name")[0], 2) self.assert_delayed(qs.defer("name").only("name").only("value")[0], 2) self.assert_delayed(qs.defer("name").only("value")[0], 2) self.assert_delayed(qs.only("name").defer("value")[0], 2) self.assert_delayed(qs.only("name").defer("name").defer("value")[0], 1) self.assert_delayed(qs.only("name").defer("name", "value")[0], 1) def test_defer_only_clear(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name").defer("name")[0], 0) self.assert_delayed(qs.defer("name").only("name")[0], 0) def test_defer_on_an_already_deferred_field(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name")[0], 1) self.assert_delayed(qs.defer("name").defer("name")[0], 1) def test_defer_none_to_clear_deferred_set(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name", "value")[0], 2) self.assert_delayed(qs.defer(None)[0], 0) self.assert_delayed(qs.only("name").defer(None)[0], 0) def test_only_none_raises_error(self): msg = "Cannot pass None as an argument to only()." with self.assertRaisesMessage(TypeError, msg): Primary.objects.only(None) def test_defer_extra(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1) self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1) def test_defer_values_does_not_defer(self): # User values() won't defer anything (you get the full list of # dictionaries back), but it still works. self.assertEqual( Primary.objects.defer("name").values()[0], { "id": self.p1.id, "name": "p1", "value": "xx", "related_id": self.s1.id, }, ) def test_only_values_does_not_defer(self): self.assertEqual( Primary.objects.only("name").values()[0], { "id": self.p1.id, "name": "p1", "value": "xx", "related_id": self.s1.id, }, ) def test_get(self): # Using defer() and only() with get() is also valid. qs = Primary.objects.all() self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1) self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2) def test_defer_with_select_related(self): obj = Primary.objects.select_related().defer( "related__first", "related__second" )[0] self.assert_delayed(obj.related, 2) self.assert_delayed(obj, 0) def test_only_with_select_related(self): obj = Primary.objects.select_related().only("related__first")[0] self.assert_delayed(obj, 2) self.assert_delayed(obj.related, 1) self.assertEqual(obj.related_id, self.s1.pk) self.assertEqual(obj.name, "p1") def test_defer_foreign_keys_are_deferred_and_not_traversed(self): # select_related() overrides defer(). with self.assertNumQueries(1): obj = Primary.objects.defer("related").select_related()[0] self.assert_delayed(obj, 1) self.assertEqual(obj.related.id, self.s1.pk) def test_saving_object_with_deferred_field(self): # Saving models with deferred fields is possible (but inefficient, # since every field has to be retrieved first). Primary.objects.create(name="p2", value="xy", related=self.s1) obj = Primary.objects.defer("value").get(name="p2") obj.name = "a new name" obj.save() self.assertQuerySetEqual( Primary.objects.all(), [ "p1", "a new name", ], lambda p: p.name, ordered=False, ) def test_defer_baseclass_when_subclass_has_no_added_fields(self): # Regression for #10572 - A subclass with no extra fields can defer # fields from the base class Child.objects.create(name="c1", value="foo", related=self.s1) # You can defer a field on a baseclass when the subclass has no fields obj = Child.objects.defer("value").get(name="c1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") def test_only_baseclass_when_subclass_has_no_added_fields(self): # You can retrieve a single column on a base class with no fields Child.objects.create(name="c1", value="foo", related=self.s1) obj = Child.objects.only("name").get(name="c1") # on an inherited model, its PK is also fetched, hence '3' deferred fields. self.assert_delayed(obj, 3) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") def test_defer_of_overridden_scalar(self): ShadowChild.objects.create() obj = ShadowChild.objects.defer("name").get() self.assertEqual(obj.name, "adonis") def test_defer_fk_attname(self): primary = Primary.objects.defer("related_id").get() with self.assertNumQueries(1): self.assertEqual(primary.related_id, self.p1.related_id) class BigChildDeferTests(AssertionMixin, TestCase): @classmethod def setUpTestData(cls): cls.s1 = Secondary.objects.create(first="x1", second="y1") BigChild.objects.create(name="b1", value="foo", related=cls.s1, other="bar") def test_defer_baseclass_when_subclass_has_added_field(self): # You can defer a field on a baseclass obj = BigChild.objects.defer("value").get(name="b1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_defer_subclass(self): # You can defer a field on a subclass obj = BigChild.objects.defer("other").get(name="b1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_defer_subclass_both(self): # Deferring fields from both superclass and subclass works. obj = BigChild.objects.defer("other", "value").get(name="b1") self.assert_delayed(obj, 2) def test_only_baseclass_when_subclass_has_added_field(self): # You can retrieve a single field on a baseclass obj = BigChild.objects.only("name").get(name="b1") # when inherited model, its PK is also fetched, hence '4' deferred fields. self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_only_subclass(self): # You can retrieve a single field on a subclass obj = BigChild.objects.only("other").get(name="b1") self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") class TestDefer2(AssertionMixin, TestCase): def test_defer_proxy(self): """ Ensure select_related together with only on a proxy model behaves as expected. See #17876. """ related = Secondary.objects.create(first="x1", second="x2") ChildProxy.objects.create(name="p1", value="xx", related=related) children = ChildProxy.objects.select_related().only("id", "name") self.assertEqual(len(children), 1) child = children[0] self.assert_delayed(child, 2) self.assertEqual(child.name, "p1") self.assertEqual(child.value, "xx") def test_defer_inheritance_pk_chaining(self): """ When an inherited model is fetched from the DB, its PK is also fetched. When getting the PK of the parent model it is useful to use the already fetched parent model PK if it happens to be available. """ s1 = Secondary.objects.create(first="x1", second="y1") bc = BigChild.objects.create(name="b1", value="foo", related=s1, other="bar") bc_deferred = BigChild.objects.only("name").get(pk=bc.pk) with self.assertNumQueries(0): bc_deferred.id self.assertEqual(bc_deferred.pk, bc_deferred.id) def test_eq(self): s1 = Secondary.objects.create(first="x1", second="y1") s1_defer = Secondary.objects.only("pk").get(pk=s1.pk) self.assertEqual(s1, s1_defer) self.assertEqual(s1_defer, s1) def test_refresh_not_loading_deferred_fields(self): s = Secondary.objects.create() rf = Primary.objects.create(name="foo", value="bar", related=s) rf2 = Primary.objects.only("related", "value").get() rf.name = "new foo" rf.value = "new bar" rf.save() with self.assertNumQueries(1): rf2.refresh_from_db() self.assertEqual(rf2.value, "new bar") with self.assertNumQueries(1): self.assertEqual(rf2.name, "new foo") def test_custom_refresh_on_deferred_loading(self): s = Secondary.objects.create() rf = RefreshPrimaryProxy.objects.create(name="foo", value="bar", related=s) rf2 = RefreshPrimaryProxy.objects.only("related").get() rf.name = "new foo" rf.value = "new bar" rf.save() with self.assertNumQueries(1): # Customized refresh_from_db() reloads all deferred fields on # access of any of them. self.assertEqual(rf2.name, "new foo") self.assertEqual(rf2.value, "new bar") class InvalidDeferTests(SimpleTestCase): def test_invalid_defer(self): msg = "Primary has no field named 'missing'" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Primary.objects.defer("missing")) with self.assertRaisesMessage(FieldError, "missing"): list(Primary.objects.defer("value__missing")) msg = "Secondary has no field named 'missing'" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Primary.objects.defer("related__missing")) def test_invalid_only(self): msg = "Primary has no field named 'missing'" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Primary.objects.only("missing")) with self.assertRaisesMessage(FieldError, "missing"): list(Primary.objects.only("value__missing")) msg = "Secondary has no field named 'missing'" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Primary.objects.only("related__missing")) def test_defer_select_related_raises_invalid_query(self): msg = ( "Field Primary.related cannot be both deferred and traversed using " "select_related at the same time." ) with self.assertRaisesMessage(FieldError, msg): Primary.objects.defer("related").select_related("related")[0] def test_only_select_related_raises_invalid_query(self): msg = ( "Field Primary.related cannot be both deferred and traversed using " "select_related at the same time." ) with self.assertRaisesMessage(FieldError, msg): Primary.objects.only("name").select_related("related")[0]
22256d0acb370fef4b30fde7cd79d14d1b741fd5825c8cdee72d6da470d0a7ae
from datetime import date from decimal import Decimal from unittest import mock from django.db import connection, transaction from django.db.models import ( Case, Count, DecimalField, F, FilteredRelation, Q, Sum, When, ) from django.test import TestCase from django.test.testcases import skipUnlessDBFeature from .models import ( Author, Book, BookDailySales, Borrower, Currency, Editor, ExchangeRate, RentalSession, Reservation, Seller, ) class FilteredRelationTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(name="Alice") cls.author2 = Author.objects.create(name="Jane") cls.editor_a = Editor.objects.create(name="a") cls.editor_b = Editor.objects.create(name="b") cls.book1 = Book.objects.create( title="Poem by Alice", editor=cls.editor_a, author=cls.author1, ) cls.book1.generic_author.set([cls.author2]) cls.book2 = Book.objects.create( title="The book by Jane A", editor=cls.editor_b, author=cls.author2, ) cls.book3 = Book.objects.create( title="The book by Jane B", editor=cls.editor_b, author=cls.author2, ) cls.book4 = Book.objects.create( title="The book by Alice", editor=cls.editor_a, author=cls.author1, ) cls.author1.favorite_books.add(cls.book2) cls.author1.favorite_books.add(cls.book3) def test_select_related(self): qs = ( Author.objects.annotate( book_join=FilteredRelation("book"), ) .select_related("book_join__editor") .order_by("pk", "book_join__pk") ) with self.assertNumQueries(1): self.assertQuerySetEqual( qs, [ (self.author1, self.book1, self.editor_a, self.author1), (self.author1, self.book4, self.editor_a, self.author1), (self.author2, self.book2, self.editor_b, self.author2), (self.author2, self.book3, self.editor_b, self.author2), ], lambda x: (x, x.book_join, x.book_join.editor, x.book_join.author), ) def test_select_related_multiple(self): qs = ( Book.objects.annotate( author_join=FilteredRelation("author"), editor_join=FilteredRelation("editor"), ) .select_related("author_join", "editor_join") .order_by("pk") ) self.assertQuerySetEqual( qs, [ (self.book1, self.author1, self.editor_a), (self.book2, self.author2, self.editor_b), (self.book3, self.author2, self.editor_b), (self.book4, self.author1, self.editor_a), ], lambda x: (x, x.author_join, x.editor_join), ) def test_select_related_with_empty_relation(self): qs = ( Author.objects.annotate( book_join=FilteredRelation("book", condition=Q(pk=-1)), ) .select_related("book_join") .order_by("pk") ) self.assertSequenceEqual(qs, [self.author1, self.author2]) def test_select_related_foreign_key(self): qs = ( Book.objects.annotate( author_join=FilteredRelation("author"), ) .select_related("author_join") .order_by("pk") ) with self.assertNumQueries(1): self.assertQuerySetEqual( qs, [ (self.book1, self.author1), (self.book2, self.author2), (self.book3, self.author2), (self.book4, self.author1), ], lambda x: (x, x.author_join), ) @skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") def test_select_related_foreign_key_for_update_of(self): with transaction.atomic(): qs = ( Book.objects.annotate( author_join=FilteredRelation("author"), ) .select_related("author_join") .select_for_update(of=("self",)) .order_by("pk") ) with self.assertNumQueries(1): self.assertQuerySetEqual( qs, [ (self.book1, self.author1), (self.book2, self.author2), (self.book3, self.author2), (self.book4, self.author1), ], lambda x: (x, x.author_join), ) def test_without_join(self): self.assertCountEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ), [self.author1, self.author2], ) def test_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False), [self.author1], ) def test_with_exclude(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).exclude(book_alice__isnull=False), [self.author2], ) def test_with_join_and_complex_condition(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q( Q(book__title__iexact="poem by alice") | Q(book__state=Book.RENTED) ), ), ).filter(book_alice__isnull=False), [self.author1], ) def test_internal_queryset_alias_mapping(self): queryset = Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False) self.assertIn( "INNER JOIN {} book_alice ON".format( connection.ops.quote_name("filtered_relation_book") ), str(queryset.query), ) def test_multiple(self): qs = ( Author.objects.annotate( book_title_alice=FilteredRelation( "book", condition=Q(book__title__contains="Alice") ), book_title_jane=FilteredRelation( "book", condition=Q(book__title__icontains="Jane") ), ) .filter(name="Jane") .values("book_title_alice__title", "book_title_jane__title") ) empty = "" if connection.features.interprets_empty_strings_as_nulls else None self.assertCountEqual( qs, [ { "book_title_alice__title": empty, "book_title_jane__title": "The book by Jane A", }, { "book_title_alice__title": empty, "book_title_jane__title": "The book by Jane B", }, ], ) def test_with_multiple_filter(self): self.assertSequenceEqual( Author.objects.annotate( book_editor_a=FilteredRelation( "book", condition=Q( book__title__icontains="book", book__editor_id=self.editor_a.pk ), ), ).filter(book_editor_a__isnull=False), [self.author1], ) def test_multiple_times(self): self.assertSequenceEqual( Author.objects.annotate( book_title_alice=FilteredRelation( "book", condition=Q(book__title__icontains="alice") ), ) .filter(book_title_alice__isnull=False) .filter(book_title_alice__isnull=False) .distinct(), [self.author1], ) def test_exclude_relation_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=~Q(book__title__icontains="alice") ), ) .filter(book_alice__isnull=False) .distinct(), [self.author2], ) def test_with_m2m(self): qs = Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( "favorite_books", condition=Q(favorite_books__in=[self.book2]), ), ).filter(favorite_books_written_by_jane__isnull=False) self.assertSequenceEqual(qs, [self.author1]) def test_with_m2m_deep(self): qs = Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( "favorite_books", condition=Q(favorite_books__author=self.author2), ), ).filter(favorite_books_written_by_jane__title="The book by Jane B") self.assertSequenceEqual(qs, [self.author1]) def test_with_m2m_multijoin(self): qs = ( Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( "favorite_books", condition=Q(favorite_books__author=self.author2), ) ) .filter(favorite_books_written_by_jane__editor__name="b") .distinct() ) self.assertSequenceEqual(qs, [self.author1]) def test_values_list(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ) .filter(book_alice__isnull=False) .values_list("book_alice__title", flat=True), ["Poem by Alice"], ) def test_values(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ) .filter(book_alice__isnull=False) .values(), [ { "id": self.author1.pk, "name": "Alice", "content_type_id": None, "object_id": None, } ], ) def test_extra(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ) .filter(book_alice__isnull=False) .extra(where=["1 = 1"]), [self.author1], ) @skipUnlessDBFeature("supports_select_union") def test_union(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation( "book", condition=Q(book__title__iexact="the book by jane a") ), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.union(qs2), [self.author1, self.author2]) @skipUnlessDBFeature("supports_select_intersection") def test_intersection(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation( "book", condition=Q(book__title__iexact="the book by jane a") ), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.intersection(qs2), []) @skipUnlessDBFeature("supports_select_difference") def test_difference(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation( "book", condition=Q(book__title__iexact="the book by jane a") ), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.difference(qs2), [self.author1]) def test_select_for_update(self): self.assertSequenceEqual( Author.objects.annotate( book_jane=FilteredRelation( "book", condition=Q(book__title__iexact="the book by jane a") ), ) .filter(book_jane__isnull=False) .select_for_update(), [self.author2], ) def test_defer(self): # One query for the list and one query for the deferred title. with self.assertNumQueries(2): self.assertQuerySetEqual( Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ) .filter(book_alice__isnull=False) .select_related("book_alice") .defer("book_alice__title"), ["Poem by Alice"], lambda author: author.book_alice.title, ) def test_only_not_supported(self): msg = "only() is not supported with FilteredRelation." with self.assertRaisesMessage(ValueError, msg): Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False).select_related("book_alice").only( "book_alice__state" ) def test_as_subquery(self): inner_qs = Author.objects.annotate( book_alice=FilteredRelation( "book", condition=Q(book__title__iexact="poem by alice") ), ).filter(book_alice__isnull=False) qs = Author.objects.filter(id__in=inner_qs) self.assertSequenceEqual(qs, [self.author1]) def test_nested_foreign_key(self): qs = ( Author.objects.annotate( book_editor_worked_with=FilteredRelation( "book__editor", condition=Q(book__title__icontains="book by"), ), ) .filter( book_editor_worked_with__isnull=False, ) .select_related( "book_editor_worked_with", ) .order_by("pk", "book_editor_worked_with__pk") ) with self.assertNumQueries(1): self.assertQuerySetEqual( qs, [ (self.author1, self.editor_a), (self.author2, self.editor_b), (self.author2, self.editor_b), ], lambda x: (x, x.book_editor_worked_with), ) def test_nested_foreign_key_nested_field(self): qs = ( Author.objects.annotate( book_editor_worked_with=FilteredRelation( "book__editor", condition=Q(book__title__icontains="book by") ), ) .filter( book_editor_worked_with__isnull=False, ) .values( "name", "book_editor_worked_with__name", ) .order_by("name", "book_editor_worked_with__name") .distinct() ) self.assertSequenceEqual( qs, [ { "name": self.author1.name, "book_editor_worked_with__name": self.editor_a.name, }, { "name": self.author2.name, "book_editor_worked_with__name": self.editor_b.name, }, ], ) def test_nested_foreign_key_filtered_base_object(self): qs = ( Author.objects.annotate( alice_editors=FilteredRelation( "book__editor", condition=Q(name="Alice"), ), ) .values( "name", "alice_editors__pk", ) .order_by("name", "alice_editors__name") .distinct() ) self.assertSequenceEqual( qs, [ {"name": self.author1.name, "alice_editors__pk": self.editor_a.pk}, {"name": self.author2.name, "alice_editors__pk": None}, ], ) def test_nested_m2m_filtered(self): qs = ( Book.objects.annotate( favorite_book=FilteredRelation( "author__favorite_books", condition=Q(author__favorite_books__title__icontains="book by"), ), ) .values( "title", "favorite_book__pk", ) .order_by("title", "favorite_book__title") ) self.assertSequenceEqual( qs, [ {"title": self.book1.title, "favorite_book__pk": self.book2.pk}, {"title": self.book1.title, "favorite_book__pk": self.book3.pk}, {"title": self.book4.title, "favorite_book__pk": self.book2.pk}, {"title": self.book4.title, "favorite_book__pk": self.book3.pk}, {"title": self.book2.title, "favorite_book__pk": None}, {"title": self.book3.title, "favorite_book__pk": None}, ], ) def test_nested_chained_relations(self): qs = ( Author.objects.annotate( my_books=FilteredRelation( "book", condition=Q(book__title__icontains="book by"), ), preferred_by_authors=FilteredRelation( "my_books__preferred_by_authors", condition=Q(my_books__preferred_by_authors__name="Alice"), ), ) .annotate( author=F("name"), book_title=F("my_books__title"), preferred_by_author_pk=F("preferred_by_authors"), ) .order_by("author", "book_title", "preferred_by_author_pk") ) self.assertQuerySetEqual( qs, [ ("Alice", "The book by Alice", None), ("Jane", "The book by Jane A", self.author1.pk), ("Jane", "The book by Jane B", self.author1.pk), ], lambda x: (x.author, x.book_title, x.preferred_by_author_pk), ) def test_deep_nested_foreign_key(self): qs = ( Book.objects.annotate( author_favorite_book_editor=FilteredRelation( "author__favorite_books__editor", condition=Q(author__favorite_books__title__icontains="Jane A"), ), ) .filter( author_favorite_book_editor__isnull=False, ) .select_related( "author_favorite_book_editor", ) .order_by("pk", "author_favorite_book_editor__pk") ) with self.assertNumQueries(1): self.assertQuerySetEqual( qs, [ (self.book1, self.editor_b), (self.book4, self.editor_b), ], lambda x: (x, x.author_favorite_book_editor), ) def test_relation_name_lookup(self): msg = ( "FilteredRelation's relation_name cannot contain lookups (got " "'book__title__icontains')." ) with self.assertRaisesMessage(ValueError, msg): Author.objects.annotate( book_title=FilteredRelation( "book__title__icontains", condition=Q(book__title="Poem by Alice"), ), ) def test_condition_outside_relation_name(self): msg = ( "FilteredRelation's condition doesn't support relations outside " "the 'book__editor' (got 'book__author__name__icontains')." ) with self.assertRaisesMessage(ValueError, msg): Author.objects.annotate( book_editor=FilteredRelation( "book__editor", condition=Q(book__author__name__icontains="book"), ), ) def test_condition_deeper_relation_name(self): msg = ( "FilteredRelation's condition doesn't support nested relations " "deeper than the relation_name (got " "'book__editor__name__icontains' for 'book')." ) with self.assertRaisesMessage(ValueError, msg): Author.objects.annotate( book_editor=FilteredRelation( "book", condition=Q(book__editor__name__icontains="b"), ), ) def test_with_empty_relation_name_error(self): with self.assertRaisesMessage(ValueError, "relation_name cannot be empty."): FilteredRelation("", condition=Q(blank="")) def test_with_condition_as_expression_error(self): msg = "condition argument must be a Q() instance." expression = Case( When(book__title__iexact="poem by alice", then=True), default=False, ) with self.assertRaisesMessage(ValueError, msg): FilteredRelation("book", condition=expression) def test_with_prefetch_related(self): msg = "prefetch_related() is not supported with FilteredRelation." qs = Author.objects.annotate( book_title_contains_b=FilteredRelation( "book", condition=Q(book__title__icontains="b") ), ).filter( book_title_contains_b__isnull=False, ) with self.assertRaisesMessage(ValueError, msg): qs.prefetch_related("book_title_contains_b") with self.assertRaisesMessage(ValueError, msg): qs.prefetch_related("book_title_contains_b__editor") def test_with_generic_foreign_key(self): self.assertSequenceEqual( Book.objects.annotate( generic_authored_book=FilteredRelation( "generic_author", condition=Q(generic_author__isnull=False) ), ).filter(generic_authored_book__isnull=False), [self.book1], ) def test_eq(self): self.assertEqual( FilteredRelation("book", condition=Q(book__title="b")), mock.ANY ) class FilteredRelationAggregationTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(name="Alice") cls.editor_a = Editor.objects.create(name="a") cls.book1 = Book.objects.create( title="Poem by Alice", editor=cls.editor_a, author=cls.author1, ) cls.borrower1 = Borrower.objects.create(name="Jenny") cls.borrower2 = Borrower.objects.create(name="Kevin") # borrower 1 reserves, rents, and returns book1. Reservation.objects.create( borrower=cls.borrower1, book=cls.book1, state=Reservation.STOPPED, ) RentalSession.objects.create( borrower=cls.borrower1, book=cls.book1, state=RentalSession.STOPPED, ) # borrower2 reserves, rents, and returns book1. Reservation.objects.create( borrower=cls.borrower2, book=cls.book1, state=Reservation.STOPPED, ) RentalSession.objects.create( borrower=cls.borrower2, book=cls.book1, state=RentalSession.STOPPED, ) def test_aggregate(self): """ filtered_relation() not only improves performance but also creates correct results when aggregating with multiple LEFT JOINs. Books can be reserved then rented by a borrower. Each reservation and rental session are recorded with Reservation and RentalSession models. Every time a reservation or a rental session is over, their state is changed to 'stopped'. Goal: Count number of books that are either currently reserved or rented by borrower1 or available. """ qs = ( Book.objects.annotate( is_reserved_or_rented_by=Case( When( reservation__state=Reservation.NEW, then=F("reservation__borrower__pk"), ), When( rental_session__state=RentalSession.NEW, then=F("rental_session__borrower__pk"), ), default=None, ) ) .filter( Q(is_reserved_or_rented_by=self.borrower1.pk) | Q(state=Book.AVAILABLE) ) .distinct() ) self.assertEqual(qs.count(), 1) # If count is equal to 1, the same aggregation should return in the # same result but it returns 4. self.assertSequenceEqual( qs.annotate(total=Count("pk")).values("total"), [{"total": 4}] ) # With FilteredRelation, the result is as expected (1). qs = ( Book.objects.annotate( active_reservations=FilteredRelation( "reservation", condition=Q( reservation__state=Reservation.NEW, reservation__borrower=self.borrower1, ), ), ) .annotate( active_rental_sessions=FilteredRelation( "rental_session", condition=Q( rental_session__state=RentalSession.NEW, rental_session__borrower=self.borrower1, ), ), ) .filter( ( Q(active_reservations__isnull=False) | Q(active_rental_sessions__isnull=False) ) | Q(state=Book.AVAILABLE) ) .distinct() ) self.assertEqual(qs.count(), 1) self.assertSequenceEqual( qs.annotate(total=Count("pk")).values("total"), [{"total": 1}] ) def test_condition_spans_join(self): self.assertSequenceEqual( Book.objects.annotate( contains_editor_author=FilteredRelation( "author", condition=Q(author__name__icontains=F("editor__name")) ) ).filter( contains_editor_author__isnull=False, ), [self.book1], ) def test_condition_spans_join_chained(self): self.assertSequenceEqual( Book.objects.annotate( contains_editor_author=FilteredRelation( "author", condition=Q(author__name__icontains=F("editor__name")) ), contains_editor_author_ref=FilteredRelation( "author", condition=Q(author__name=F("contains_editor_author__name")), ), ).filter( contains_editor_author_ref__isnull=False, ), [self.book1], ) def test_condition_self_ref(self): self.assertSequenceEqual( Book.objects.annotate( contains_author=FilteredRelation( "author", condition=Q(title__icontains=F("author__name")), ) ).filter( contains_author__isnull=False, ), [self.book1], ) class FilteredRelationAnalyticalAggregationTests(TestCase): @classmethod def setUpTestData(cls): author = Author.objects.create(name="Author") editor = Editor.objects.create(name="Editor") cls.book1 = Book.objects.create( title="Poem by Alice", editor=editor, author=author, ) cls.book2 = Book.objects.create( title="The book by Jane A", editor=editor, author=author, ) cls.book3 = Book.objects.create( title="The book by Jane B", editor=editor, author=author, ) cls.seller1 = Seller.objects.create(name="Seller 1") cls.seller2 = Seller.objects.create(name="Seller 2") cls.usd = Currency.objects.create(currency="USD") cls.eur = Currency.objects.create(currency="EUR") cls.sales_date1 = date(2020, 7, 6) cls.sales_date2 = date(2020, 7, 7) ExchangeRate.objects.bulk_create( [ ExchangeRate( rate_date=cls.sales_date1, from_currency=cls.usd, to_currency=cls.eur, rate=0.40, ), ExchangeRate( rate_date=cls.sales_date1, from_currency=cls.eur, to_currency=cls.usd, rate=1.60, ), ExchangeRate( rate_date=cls.sales_date2, from_currency=cls.usd, to_currency=cls.eur, rate=0.50, ), ExchangeRate( rate_date=cls.sales_date2, from_currency=cls.eur, to_currency=cls.usd, rate=1.50, ), ExchangeRate( rate_date=cls.sales_date2, from_currency=cls.usd, to_currency=cls.usd, rate=1.00, ), ] ) BookDailySales.objects.bulk_create( [ BookDailySales( book=cls.book1, sale_date=cls.sales_date1, currency=cls.usd, sales=100.00, seller=cls.seller1, ), BookDailySales( book=cls.book2, sale_date=cls.sales_date1, currency=cls.eur, sales=200.00, seller=cls.seller1, ), BookDailySales( book=cls.book1, sale_date=cls.sales_date2, currency=cls.usd, sales=50.00, seller=cls.seller2, ), BookDailySales( book=cls.book2, sale_date=cls.sales_date2, currency=cls.eur, sales=100.00, seller=cls.seller2, ), ] ) def test_aggregate(self): tests = [ Q(daily_sales__sale_date__gte=self.sales_date2), ~Q(daily_sales__seller=self.seller1), ] for condition in tests: with self.subTest(condition=condition): qs = ( Book.objects.annotate( recent_sales=FilteredRelation( "daily_sales", condition=condition ), recent_sales_rates=FilteredRelation( "recent_sales__currency__rates_from", condition=Q( recent_sales__currency__rates_from__rate_date=F( "recent_sales__sale_date" ), recent_sales__currency__rates_from__to_currency=( self.usd ), ), ), ) .annotate( sales_sum=Sum( F("recent_sales__sales") * F("recent_sales_rates__rate"), output_field=DecimalField(), ), ) .values("title", "sales_sum") .order_by( F("sales_sum").desc(nulls_last=True), ) ) self.assertSequenceEqual( qs, [ {"title": self.book2.title, "sales_sum": Decimal(150.00)}, {"title": self.book1.title, "sales_sum": Decimal(50.00)}, {"title": self.book3.title, "sales_sum": None}, ], )
513ef75f2535cf22c436b0b28a50e43e3544dc14a44ccff58d474591068fd52e
import gettext import os import re import zoneinfo from datetime import datetime, timedelta from importlib import import_module from unittest import skipUnless from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import ( CharField, DateField, DateTimeField, ForeignKey, ManyToManyField, UUIDField, ) from django.test import SimpleTestCase, TestCase, ignore_warnings, override_settings from django.urls import reverse from django.utils import translation from django.utils.deprecation import RemovedInDjango60Warning from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Image, Individual, Inventory, Member, MyFileField, Profile, ReleaseEvent, School, Student, UnsafeLimitChoicesTo, VideoStream, ) from .widgetadmin import site as widget_admin_site class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email=None ) cls.u2 = User.objects.create_user(username="testser", password="secret") Car.objects.create(owner=cls.superuser, make="Volkswagen", model="Passat") Car.objects.create(owner=cls.u2, make="BMW", model="M3") class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget self.assertIsInstance(widget, widgetclass) # Return the formfield so that other tests can continue return ff def test_DateField(self): self.assertFormfield(Event, "start_date", widgets.AdminDateWidget) def test_DateTimeField(self): self.assertFormfield(Member, "birthdate", widgets.AdminSplitDateTime) def test_TimeField(self): self.assertFormfield(Event, "start_time", widgets.AdminTimeWidget) def test_TextField(self): self.assertFormfield(Event, "description", widgets.AdminTextareaWidget) @ignore_warnings(category=RemovedInDjango60Warning) def test_URLField(self): self.assertFormfield(Event, "link", widgets.AdminURLFieldWidget) def test_IntegerField(self): self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget) def test_CharField(self): self.assertFormfield(Member, "name", widgets.AdminTextInputWidget) def test_EmailField(self): self.assertFormfield(Member, "email", widgets.AdminEmailInputWidget) def test_FileField(self): self.assertFormfield(Album, "cover_art", widgets.AdminFileWidget) def test_ForeignKey(self): self.assertFormfield(Event, "main_band", forms.Select) def test_raw_id_ForeignKey(self): self.assertFormfield( Event, "main_band", widgets.ForeignKeyRawIdWidget, raw_id_fields=["main_band"], ) def test_radio_fields_ForeignKey(self): ff = self.assertFormfield( Event, "main_band", widgets.AdminRadioSelect, radio_fields={"main_band": admin.VERTICAL}, ) self.assertIsNone(ff.empty_label) def test_radio_fields_foreignkey_formfield_overrides_empty_label(self): class MyModelAdmin(admin.ModelAdmin): radio_fields = {"parent": admin.VERTICAL} formfield_overrides = { ForeignKey: {"empty_label": "Custom empty label"}, } ma = MyModelAdmin(Inventory, admin.site) ff = ma.formfield_for_dbfield(Inventory._meta.get_field("parent"), request=None) self.assertEqual(ff.empty_label, "Custom empty label") def test_many_to_many(self): self.assertFormfield(Band, "members", forms.SelectMultiple) def test_raw_id_many_to_many(self): self.assertFormfield( Band, "members", widgets.ManyToManyRawIdWidget, raw_id_fields=["members"] ) def test_filtered_many_to_many(self): self.assertFormfield( Band, "members", widgets.FilteredSelectMultiple, filter_vertical=["members"] ) def test_formfield_overrides(self): self.assertFormfield( Event, "start_date", forms.TextInput, formfield_overrides={DateField: {"widget": forms.TextInput}}, ) def test_formfield_overrides_widget_instances(self): """ Widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {"widget": forms.TextInput(attrs={"size": "10"})} } ma = BandAdmin(Band, admin.site) f1 = ma.formfield_for_dbfield(Band._meta.get_field("name"), request=None) f2 = ma.formfield_for_dbfield(Band._meta.get_field("style"), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs["maxlength"], "100") self.assertEqual(f2.widget.attrs["maxlength"], "20") self.assertEqual(f2.widget.attrs["size"], "10") def test_formfield_overrides_m2m_filter_widget(self): """ The autocomplete_fields, raw_id_fields, filter_vertical, and filter_horizontal widgets for ManyToManyFields may be overridden by specifying a widget in formfield_overrides. """ class BandAdmin(admin.ModelAdmin): filter_vertical = ["members"] formfield_overrides = { ManyToManyField: {"widget": forms.CheckboxSelectMultiple}, } ma = BandAdmin(Band, admin.site) field = ma.formfield_for_dbfield(Band._meta.get_field("members"), request=None) self.assertIsInstance(field.widget.widget, forms.CheckboxSelectMultiple) def test_formfield_overrides_for_datetime_field(self): """ Overriding the widget for DateTimeField doesn't overrides the default form_class for that field (#26449). """ class MemberAdmin(admin.ModelAdmin): formfield_overrides = { DateTimeField: {"widget": widgets.AdminSplitDateTime} } ma = MemberAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Member._meta.get_field("birthdate"), request=None) self.assertIsInstance(f1.widget, widgets.AdminSplitDateTime) self.assertIsInstance(f1, forms.SplitDateTimeField) def test_formfield_overrides_for_custom_field(self): """ formfield_overrides works for a custom field class. """ class AlbumAdmin(admin.ModelAdmin): formfield_overrides = {MyFileField: {"widget": forms.TextInput()}} ma = AlbumAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield( Album._meta.get_field("backside_art"), request=None ) self.assertIsInstance(f1.widget, forms.TextInput) def test_field_with_choices(self): self.assertFormfield(Member, "gender", forms.Select) def test_choices_with_radio_fields(self): self.assertFormfield( Member, "gender", widgets.AdminRadioSelect, radio_fields={"gender": admin.VERTICAL}, ) def test_inheritance(self): self.assertFormfield(Album, "backside_art", widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual( f.help_text, "Hold down “Control”, or “Command” on a Mac, to select more than one.", ) def test_m2m_widgets_no_allow_multiple_selected(self): class NoAllowMultipleSelectedWidget(forms.SelectMultiple): allow_multiple_selected = False class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] formfield_overrides = { ManyToManyField: {"widget": NoAllowMultipleSelectedWidget}, } self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual(f.help_text, "") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase): def test_filter_choices_by_request_user(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.force_login(self.superuser) response = self.client.get(reverse("admin:admin_widgets_cartire_add")) self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagen Passat") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_changelist_ForeignKey(self): response = self.client.get(reverse("admin:admin_widgets_car_changelist")) self.assertContains(response, "/auth/user/add/") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) @ignore_warnings(category=RemovedInDjango60Warning) def test_nonexistent_target_id(self): band = Band.objects.create(name="Bogey Blues") pk = band.pk band.delete() post_data = { "main_band": str(pk), } # Try posting with a nonexistent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse("admin:admin_widgets_event_add"), post_data) self.assertContains( response, "Select a valid choice. That choice is not one of the available choices.", ) @ignore_warnings(category=RemovedInDjango60Warning) def test_invalid_target_id(self): for test_str in ("Iñtërnâtiônàlizætiøn", "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post( reverse("admin:admin_widgets_event_add"), {"main_band": test_str} ) self.assertContains( response, "Select a valid choice. That choice is not one of the available " "choices.", ) def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({"color__in": ("red", "blue")}) lookup2 = widgets.url_params_from_lookup_dict({"color__in": ["red", "blue"]}) self.assertEqual(lookup1, {"color__in": "red,blue"}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return "works" lookup1 = widgets.url_params_from_lookup_dict({"myfield": my_callable}) lookup2 = widgets.url_params_from_lookup_dict({"myfield": my_callable()}) self.assertEqual(lookup1, lookup2) def test_label_and_url_for_value_invalid_uuid(self): field = Bee._meta.get_field("honeycomb") self.assertIsInstance(field.target_field, UUIDField) widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site) self.assertEqual(widget.label_and_url_for_value("invalid-uuid"), ("", "")) class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", False) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilter" ' 'data-field-name="test\\" data-is-stacked="0">\n</select>', ) def test_stacked_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", True) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>', ) class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="vDateField" name="test" ' 'size="10">', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="myDateField" name="test" ' 'size="20">', ) class AdminTimeWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="vTimeField" name="test" ' 'size="8">', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="myTimeField" name="test" ' 'size="20">', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10"><br>' 'Time: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with translation.override("de-at"): w.is_localized = True self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Datum: <input value="01.12.2007" type="text" ' 'class="vDateField" name="test_0"size="10"><br>' 'Zeit: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ["", "/not/a/full/url/", 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): self.assertFalse(w.get_context("name", invalid, {})["url_valid"]) self.assertTrue(w.get_context("name", "http://example.com", {})["url_valid"]) def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", ""), '<input class="vURLField" name="test" type="url">' ) self.assertHTMLEqual( w.render("test", "http://example.com"), '<p class="url">Currently:<a href="http://example.com">' "http://example.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example.com"></p>', ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", "http://example-äüö.com"), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">' "http://example-äüö.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example-äüö.com"></p>', ) def test_render_quoting(self): """ WARNING: This test doesn't use assertHTMLEqual since it will get rid of some escapes which are tested here! """ HREF_RE = re.compile('href="([^"]+)"') VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile("<a[^>]+>([^>]+)</a>") w = widgets.AdminURLFieldWidget() output = w.render("test", "http://example.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://example.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render("test", "http://example-äüö.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://xn--example--7za4pnc.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render( "test", 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"' ) self.assertEqual( HREF_RE.search(output)[1], "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)" "%3C/script%3E%22", ) self.assertEqual( TEXT_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) class AdminUUIDWidgetTests(SimpleTestCase): def test_attrs(self): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="vUUIDField" name="test">', ) w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"}) self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="myUUIDInput" name="test">', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() band = Band.objects.create(name="Linkin Park") cls.album = band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) def test_render(self): w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) self.assertHTMLEqual( w.render("test", SimpleUploadedFile("test", b"content")), '<input type="file" name="test">', ) def test_render_required(self): widget = widgets.AdminFileWidget() widget.is_required = True self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_render_disabled(self): widget = widgets.AdminFileWidget(attrs={"disabled": True}) self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id" disabled>' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" disabled></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_readonly_fields(self): """ File widgets should render as a link when they're marked "read only." """ self.client.force_login(self.superuser) response = self.client.get( reverse("admin:admin_widgets_album_change", args=(self.album.id,)) ) self.assertContains( response, '<div class="readonly"><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' r"albums\hybrid_theory.jpg</a></div>" % {"STORAGE_URL": default_storage.url("")}, html=True, ) self.assertNotContains( response, '<input type="file" name="cover_art" id="id_cover_art">', html=True, ) response = self.client.get(reverse("admin:admin_widgets_album_add")) self.assertContains( response, '<div class="readonly"></div>', html=True, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ForeignKeyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) rel_uuid = Album._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel_uuid, widget_admin_site) self.assertHTMLEqual( w.render("test", band.uuid, attrs={}), '<input type="text" name="test" value="%(banduuid)s" ' 'class="vForeignKeyRawIdAdminField vUUIDField">' '<a href="/admin_widgets/band/?_to_field=uuid" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>&nbsp;<strong>' '<a href="/admin_widgets/band/%(bandpk)s/change/">Linkin Park</a>' "</strong>" % {"banduuid": band.uuid, "bandpk": band.pk}, ) rel_id = ReleaseEvent._meta.get_field("album").remote_field w = widgets.ForeignKeyRawIdWidget(rel_id, widget_admin_site) self.assertHTMLEqual( w.render("test", None, attrs={}), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/album/?_to_field=id" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>', ) def test_relations_to_non_primary_key(self): # ForeignKeyRawIdWidget works with fields which aren't related to # the model's primary key. apple = Inventory.objects.create(barcode=86, name="Apple") Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", core.parent_id, attrs={}), '<input type="text" name="test" value="86" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Apple</a></strong>" % {"pk": apple.pk}, ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = Honeycomb.objects.create(location="Old tree") big_honeycomb.bee_set.create() rel = Bee._meta.get_field("honeycomb").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("honeycomb_widget", big_honeycomb.pk, attrs={}), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s">' "&nbsp;<strong>%(hcomb)s</strong>" % {"hcombpk": big_honeycomb.pk, "hcomb": big_honeycomb}, ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = Individual.objects.create(name="Subject #1") Individual.objects.create(name="Child", parent=subject1) rel = Individual._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("individual_widget", subject1.pk, attrs={}), '<input type="text" name="individual_widget" value="%(subj1pk)s">' "&nbsp;<strong>%(subj1)s</strong>" % {"subj1pk": subject1.pk, "subj1": subject1}, ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = Inventory.objects.create(barcode=93, name="Hidden", hidden=True) child_of_hidden = Inventory.objects.create( barcode=94, name="Child of hidden", parent=hidden ) self.assertHTMLEqual( w.render("test", child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" ' ' class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Hidden</a></strong>" % {"pk": hidden.pk}, ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;' '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" ' 'title="Lookup"></a>', ) def test_render_fk_as_pk_model(self): rel = VideoStream._meta.get_field("release_event").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/releaseevent/?_to_field=album" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ManyToManyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") m1 = Member.objects.create(name="Chester") m2 = Member.objects.create(name="Mike") band.members.add(m1, m2) rel = Band._meta.get_field("members").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", [m1.pk, m2.pk], attrs={}), ( '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk, "m2pk": m2.pk}, ) self.assertHTMLEqual( w.render("test", [m1.pk]), ( '<input type="text" name="test" value="%(m1pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk}, ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = Advisor.objects.create(name="Rockstar Techie") c1 = Company.objects.create(name="Doodle") c2 = Company.objects.create(name="Pear") consultor1.companies.add(c1, c2) rel = Advisor._meta.get_field("companies").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("company_widget1", [c1.pk, c2.pk], attrs={}), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s">' % {"c1pk": c1.pk, "c2pk": c2.pk}, ) self.assertHTMLEqual( w.render("company_widget2", [c1.pk]), '<input type="text" name="company_widget2" value="%(c1pk)s">' % {"c1pk": c1.pk}, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class RelatedFieldWidgetWrapperTests(SimpleTestCase): def test_no_can_add_related(self): rel = Individual._meta.get_field("parent").remote_field w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) def test_select_multiple_widget_cant_change_delete_related(self): rel = Individual._meta.get_field("parent").remote_field widget = forms.SelectMultiple() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertFalse(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_on_delete_cascade_rel_cant_delete_related(self): rel = Individual._meta.get_field("soulmate").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertTrue(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_custom_widget_render(self): class CustomWidget(forms.Select): def render(self, *args, **kwargs): return "custom render output" rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) output = wrapper.render("name", "value") self.assertIn("custom render output", output) def test_widget_delegates_value_omitted_from_data(self): class CustomWidget(forms.Select): def value_omitted_from_data(self, data, files, name): return False rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.value_omitted_from_data({}, {}, "band"), False) def test_widget_is_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.HiddenInput() widget.choices = () wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, True) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], True) output = wrapper.render("name", "value") # Related item links are hidden. self.assertNotIn("<a ", output) def test_widget_is_not_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, False) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], False) output = wrapper.render("name", "value") # Related item links are present. self.assertIn("<a ", output) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminWidgetSeleniumTestCase(AdminSeleniumTestCase): available_apps = ["admin_widgets"] + AdminSeleniumTestCase.available_apps def setUp(self): self.u1 = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): def test_show_hide_date_time_picker_widgets(self): """ Pressing the ESC key or clicking on a widget value closes the date and time picker widgets. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # First, with the date picker widget --------------------------------- cal_icon = self.selenium.find_element(By.ID, "calendarlink0") # The date picker is hidden self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon cal_icon.click() # The date picker is visible self.assertTrue( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The date picker is hidden again self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon, then on the 15th of current month cal_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), '15')]").click() self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_0").get_attribute("value"), datetime.today().strftime("%Y-%m-") + "15", ) # Then, with the time picker widget ---------------------------------- time_icon = self.selenium.find_element(By.ID, "clocklink0") # The time picker is hidden self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon time_icon.click() # The time picker is visible self.assertTrue(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( [ x.text for x in self.selenium.find_elements( By.XPATH, "//ul[@class='timelist']/li/a" ) ], ["Now", "Midnight", "6 a.m.", "Noon", "6 p.m."], ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The time picker is hidden again self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon, then select the 'Noon' value time_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), 'Noon')]").click() self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_1").get_attribute("value"), "12:00:00", ) def test_calendar_nonday_class(self): """ Ensure cells that are not days of the month have the `nonday` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # make sure the first and last 6 cells have class nonday for td in tds[:6] + tds[-6:]: self.assertEqual(td.get_attribute("class"), "nonday") def test_calendar_selected_class(self): """ Ensure cell for the day in the input has the `selected` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify the selected cell selected = tds[6] self.assertEqual(selected.get_attribute("class"), "selected") self.assertEqual(selected.text, "1") def test_calendar_no_selected_class(self): """ Ensure no cells are given the selected class when the field is empty. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify there are no cells with the selected class selected = [td for td in tds if td.get_attribute("class") == "selected"] self.assertEqual(len(selected), 0) def test_calendar_show_date_from_input(self): """ The calendar shows the date from the input field for every locale supported by Django. """ from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.admin_login(username="super", password="secret", login_url="/") # Enter test data member = Member.objects.create( name="Bob", birthdate=datetime(1984, 5, 15), gender="M" ) # Get month name translations for every locale month_string = "May" path = os.path.join( os.path.dirname(import_module("django.contrib.admin").__file__), "locale" ) for language_code, language_name in settings.LANGUAGES: try: catalog = gettext.translation("djangojs", path, [language_code]) except OSError: continue if month_string in catalog._catalog: month_name = catalog._catalog[month_string] else: month_name = month_string # Get the expected caption may_translation = month_name expected_caption = "{:s} {:d}".format(may_translation.upper(), 1984) # Test with every locale with override_settings(LANGUAGE_CODE=language_code): # Open a page that has a date picker widget url = reverse("admin:admin_widgets_member_change", args=(member.pk,)) self.selenium.get(self.live_server_url + url) # Click on the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # Make sure that the right month and year are displayed self.wait_for_text("#calendarin0 caption", expected_caption) @override_settings(TIME_ZONE="Asia/Singapore") class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): def test_date_time_picker_shortcuts(self): """ date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") error_margin = timedelta(seconds=10) # If we are neighbouring a DST, we add an hour of error margin. tz = zoneinfo.ZoneInfo("America/Chicago") utc_now = datetime.now(zoneinfo.ZoneInfo("UTC")) tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname() tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname() if tz_yesterday != tz_tomorrow: error_margin += timedelta(hours=1) self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) self.selenium.find_element(By.ID, "id_name").send_keys("test") # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements( By.CSS_SELECTOR, ".field-birthdate .datetimeshortcuts" ) now = datetime.now() for shortcut in shortcuts: shortcut.find_element(By.TAG_NAME, "a").click() # There is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.assertCountSeleniumElements(".field-birthdate .timezonewarning", 1) # Submit the form. with self.wait_page_loaded(): self.selenium.find_element(By.NAME, "_save").click() # Make sure that "now" in JavaScript is within 10 seconds # from "now" on the server side. member = Member.objects.get(name="test") self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) # The above tests run with Asia/Singapore which are on the positive side of # UTC. Here we test with a timezone on the negative side. @override_settings(TIME_ZONE="US/Eastern") class DateTimePickerAltTimezoneSeleniumTests(DateTimePickerShortcutsSeleniumTests): pass class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() self.lisa = Student.objects.create(name="Lisa") self.john = Student.objects.create(name="John") self.bob = Student.objects.create(name="Bob") self.peter = Student.objects.create(name="Peter") self.jenny = Student.objects.create(name="Jenny") self.jason = Student.objects.create(name="Jason") self.cliff = Student.objects.create(name="Cliff") self.arthur = Student.objects.create(name="Arthur") self.school = School.objects.create(name="School of Awesome") def assertActiveButtons( self, mode, field_name, choose, remove, choose_all=None, remove_all=None ): choose_link = "#id_%s_add_link" % field_name choose_all_link = "#id_%s_add_all_link" % field_name remove_link = "#id_%s_remove_link" % field_name remove_all_link = "#id_%s_remove_all_link" % field_name self.assertEqual(self.has_css_class(choose_link, "active"), choose) self.assertEqual(self.has_css_class(remove_link, "active"), remove) if mode == "horizontal": self.assertEqual(self.has_css_class(choose_all_link, "active"), choose_all) self.assertEqual(self.has_css_class(remove_all_link, "active"), remove_all) def execute_basic_operations(self, mode, field_name): from selenium.webdriver.common.by import By original_url = self.selenium.current_url from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name choose_all_link = "id_%s_add_all_link" % field_name remove_link = "id_%s_remove_link" % field_name remove_all_link = "id_%s_remove_all_link" % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, choose_all_link).click() elif mode == "vertical": # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements( By.CSS_SELECTOR, from_box + " > option" ): option.click() self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, remove_all_link).click() elif mode == "vertical": # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements( By.CSS_SELECTOR, to_box + " > option" ): option.click() self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions( from_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ from_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(from_box, self.lisa.id) ) # Check the title attribute is there for tool tips: ticket #20821 self.assertEqual( from_lisa_select_option.get_attribute("title"), from_lisa_select_option.get_attribute("text"), ) self.select_option(from_box, str(self.lisa.id)) self.select_option(from_box, str(self.jason.id)) self.select_option(from_box, str(self.bob.id)) self.select_option(from_box, str(self.john.id)) self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element(By.ID, choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), ], ) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id), ], ) # Check the tooltip is still there after moving: ticket #20821 to_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(to_box, self.lisa.id) ) self.assertEqual( to_lisa_select_option.get_attribute("title"), to_lisa_select_option.get_attribute("text"), ) # Remove some options ------------------------------------------------- self.select_option(to_box, str(self.lisa.id)) self.select_option(to_box, str(self.bob.id)) self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element(By.ID, remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.arthur.id)) self.select_option(from_box, str(self.cliff.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions( to_box, [ str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id), ], ) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.peter.id)) self.select_option(from_box, str(self.lisa.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(from_box, str(self.peter.id)) self.deselect_option(from_box, str(self.lisa.id)) # Choose some more options -------------------------------------------- self.select_option(to_box, str(self.jason.id)) self.select_option(to_box, str(self.john.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(to_box, str(self.jason.id)) self.deselect_option(to_box, str(self.john.id)) # Pressing buttons shouldn't change the URL. self.assertEqual(self.selenium.current_url, original_url) def test_basic(self): from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) self.wait_page_ready() self.execute_basic_operations("vertical", "students") self.execute_basic_operations("horizontal", "alumni") # Save and check that everything is properly stored in the database --- self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_page_ready() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual( list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john], ) self.assertEqual( list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john], ) def test_filter(self): """ Typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) for field_name in ["students", "alumni"]: from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name remove_link = "id_%s_remove_link" % field_name input = self.selenium.find_element(By.ID, "id_%s_input" % field_name) # Initial values self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # Typing in some characters filters out non-matching options input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys("R") self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # ----------------------------------------------------------------- # Choosing a filtered option sends it properly to the 'to' box. input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) self.select_option(from_box, str(self.jason.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.jason.id), ], ) self.select_option(to_box, str(self.lisa.id)) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id), ], ) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # ----------------------------------------------------------------- # Pressing enter on a filtered option sends it properly to # the 'to' box. self.select_option(to_box, str(self.jason.id)) self.selenium.find_element(By.ID, remove_link).click() input.send_keys("ja") self.assertSelectOptions(from_box, [str(self.jason.id)]) input.send_keys([Keys.ENTER]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE]) # Save and check that everything is properly stored in the database --- with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) def test_back_button_bug(self): """ Some browsers had a bug where navigating away from the change page and then clicking the browser's back button would clear the filter_horizontal/filter_vertical widgets (#13614). """ from selenium.webdriver.common.by import By self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) # Navigate away and go back to the change form page. self.selenium.find_element(By.LINK_TEXT, "Home").click() self.selenium.back() expected_unselected_values = [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ] expected_selected_values = [str(self.lisa.id), str(self.peter.id)] # Everything is still in place self.assertSelectOptions("#id_students_from", expected_unselected_values) self.assertSelectOptions("#id_students_to", expected_selected_values) self.assertSelectOptions("#id_alumni_from", expected_unselected_values) self.assertSelectOptions("#id_alumni_to", expected_selected_values) def test_refresh_page(self): """ Horizontal and vertical filter widgets keep selected options on page reload (#22955). """ self.school.students.add(self.arthur, self.jason) self.school.alumni.add(self.arthur, self.jason) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) self.assertCountSeleniumElements("#id_students_to > option", 2) # self.selenium.refresh() or send_keys(Keys.F5) does hard reload and # doesn't replicate what happens when a user clicks the browser's # 'Refresh' button. with self.wait_page_loaded(): self.selenium.execute_script("location.reload()") self.assertCountSeleniumElements("#id_students_to > option", 2) @ignore_warnings(category=RemovedInDjango60Warning) class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() Band.objects.create(id=42, name="Bogey Blues") Band.objects.create(id=98, name="Green Potatoes") def test_ForeignKey(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_main_band").get_attribute("value"), "" ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the other selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "98") def test_many_to_many(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_supporting_bands").get_attribute( "value" ), "", ) # Help text for the field is displayed self.assertEqual( self.selenium.find_element( By.CSS_SELECTOR, ".field-supporting_bands div.help" ).text, "Supporting Bands.", ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42,98") class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey_using_to_field(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_profile_add") ) main_window = self.selenium.current_window_handle # Click the Add User button to add new self.selenium.find_element(By.ID, "add_id_user").click() self.wait_for_and_switch_to_popup() password_field = self.selenium.find_element(By.ID, "id_password") password_field.send_keys("password") username_field = self.selenium.find_element(By.ID, "id_username") username_value = "newuser" username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) # The field now contains the new user self.selenium.find_element(By.CSS_SELECTOR, "#id_user option[value=newuser]") self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "newuser") self.selenium.back() # Chrome and Safari don't update related object links when selecting # the same option as previously submitted. As a consequence, the # "pencil" and "eye" buttons remain disable, so select "---------" # first. select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_index(0) select.select_by_value("newuser") # Click the Change User button to change it self.selenium.find_element(By.ID, "change_id_user").click() self.wait_for_and_switch_to_popup() username_field = self.selenium.find_element(By.ID, "id_username") username_value = "changednewuser" username_field.clear() username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) self.selenium.find_element( By.CSS_SELECTOR, "#id_user option[value=changednewuser]" ) self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "changednewuser") self.selenium.back() select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_value("changednewuser") # Go ahead and submit the form to make sure it works self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.wait_for_text( "li.success", "The profile “changednewuser” was added successfully." ) profiles = Profile.objects.all() self.assertEqual(len(profiles), 1) self.assertEqual(profiles[0].user.username, username_value) @skipUnless(Image, "Pillow not installed") class ImageFieldWidgetsSeleniumTests(AdminWidgetSeleniumTestCase): name_input_id = "id_name" photo_input_id = "id_photo" tests_files_folder = "%s/files" % os.getcwd() clear_checkbox_id = "photo-clear_id" def _submit_and_wait(self): from selenium.webdriver.common.by import By with self.wait_page_loaded(): self.selenium.find_element( By.CSS_SELECTOR, "input[value='Save and continue editing']" ).click() def _run_image_upload_path(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_student_add"), ) # Add a student. name_input = self.selenium.find_element(By.ID, self.name_input_id) name_input.send_keys("Joe Doe") photo_input = self.selenium.find_element(By.ID, self.photo_input_id) photo_input.send_keys(f"{self.tests_files_folder}/test.png") self._submit_and_wait() student = Student.objects.last() self.assertEqual(student.name, "Joe Doe") self.assertRegex(student.photo.name, r"^photos\/(test|test_.+).png") def test_clearablefileinput_widget(self): from selenium.webdriver.common.by import By self._run_image_upload_path() self.selenium.find_element(By.ID, self.clear_checkbox_id).click() self._submit_and_wait() student = Student.objects.last() self.assertEqual(student.name, "Joe Doe") self.assertEqual(student.photo.name, "") # "Currently" with "Clear" checkbox and "Change" are not shown. photo_field_row = self.selenium.find_element(By.CSS_SELECTOR, ".field-photo") self.assertNotIn("Currently", photo_field_row.text) self.assertNotIn("Change", photo_field_row.text) def test_clearablefileinput_widget_invalid_file(self): from selenium.webdriver.common.by import By self._run_image_upload_path() # Uploading non-image files is not supported by Safari with Selenium, # so upload a broken one instead. photo_input = self.selenium.find_element(By.ID, self.photo_input_id) photo_input.send_keys(f"{self.tests_files_folder}/brokenimg.png") self._submit_and_wait() self.assertEqual( self.selenium.find_element(By.CSS_SELECTOR, ".errorlist li").text, ( "Upload a valid image. The file you uploaded was either not an image " "or a corrupted image." ), ) # "Currently" with "Clear" checkbox and "Change" still shown. photo_field_row = self.selenium.find_element(By.CSS_SELECTOR, ".field-photo") self.assertIn("Currently", photo_field_row.text) self.assertIn("Change", photo_field_row.text) def test_clearablefileinput_widget_preserve_clear_checkbox(self): from selenium.webdriver.common.by import By self._run_image_upload_path() # "Clear" is not checked by default. self.assertIs( self.selenium.find_element(By.ID, self.clear_checkbox_id).is_selected(), False, ) # "Clear" was checked, but a validation error is raised. name_input = self.selenium.find_element(By.ID, self.name_input_id) name_input.clear() self.selenium.find_element(By.ID, self.clear_checkbox_id).click() self._submit_and_wait() self.assertEqual( self.selenium.find_element(By.CSS_SELECTOR, ".errorlist li").text, "This field is required.", ) # "Clear" persists checked. self.assertIs( self.selenium.find_element(By.ID, self.clear_checkbox_id).is_selected(), True, )
3f8cd47939942964432707a7e48bfd6a8ab09339800d30af5fa8c157daeaf4a1
from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ClearableFileInput, FileField, Form, MultiWidget from .base import WidgetTest class FakeFieldFile: """ Quacks like a FieldFile (has a .url and string representation), but doesn't require us to care about storages etc. """ url = "something" def __str__(self): return self.url class ClearableFileInputTest(WidgetTest): def setUp(self): self.widget = ClearableFileInput() def test_clear_input_renders(self): """ A ClearableFileInput with is_required False and rendered with an initial value that is a file renders a clear checkbox. """ self.check_html( self.widget, "myfile", FakeFieldFile(), html=( """ Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id"> <label for="myfile-clear_id">Clear</label><br> Change: <input type="file" name="myfile"> """ ), ) def test_html_escaped(self): """ A ClearableFileInput should escape name, filename, and URL when rendering HTML (#15182). """ class StrangeFieldFile: url = "something?chapter=1&sect=2&copy=3&lang=en" def __str__(self): return """something<div onclick="alert('oops')">.jpg""" self.check_html( ClearableFileInput(), "my<div>file", StrangeFieldFile(), html=( """ Currently: <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"> something&lt;div onclick=&quot;alert(&#x27;oops&#x27;)&quot;&gt;.jpg</a> <input type="checkbox" name="my&lt;div&gt;file-clear" id="my&lt;div&gt;file-clear_id"> <label for="my&lt;div&gt;file-clear_id">Clear</label><br> Change: <input type="file" name="my&lt;div&gt;file"> """ ), ) def test_clear_input_renders_only_if_not_required(self): """ A ClearableFileInput with is_required=True does not render a clear checkbox. """ widget = ClearableFileInput() widget.is_required = True self.check_html( widget, "myfile", FakeFieldFile(), html=( """ Currently: <a href="something">something</a> <br> Change: <input type="file" name="myfile"> """ ), ) def test_clear_input_renders_only_if_initial(self): """ A ClearableFileInput instantiated with no initial value does not render a clear checkbox. """ self.check_html( self.widget, "myfile", None, html='<input type="file" name="myfile">' ) def test_render_disabled(self): self.check_html( self.widget, "myfile", FakeFieldFile(), attrs={"disabled": True}, html=( 'Currently: <a href="something">something</a>' '<input type="checkbox" name="myfile-clear" ' 'id="myfile-clear_id" disabled>' '<label for="myfile-clear_id">Clear</label><br>' 'Change: <input type="file" name="myfile" disabled>' ), ) def test_render_no_disabled(self): class TestForm(Form): clearable_file = FileField( widget=self.widget, initial=FakeFieldFile(), required=False ) form = TestForm() with self.assertNoLogs("django.template", "DEBUG"): form.render() def test_render_as_subwidget(self): """A ClearableFileInput as a subwidget of MultiWidget.""" widget = MultiWidget(widgets=(self.widget,)) self.check_html( widget, "myfile", [FakeFieldFile()], html=( """ Currently: <a href="something">something</a> <input type="checkbox" name="myfile_0-clear" id="myfile_0-clear_id"> <label for="myfile_0-clear_id">Clear</label><br> Change: <input type="file" name="myfile_0"> """ ), ) def test_clear_input_checked_returns_false(self): """ ClearableFileInput.value_from_datadict returns False if the clear checkbox is checked, if not required. """ value = self.widget.value_from_datadict( data={"myfile-clear": True}, files={}, name="myfile", ) self.assertIs(value, False) self.assertIs(self.widget.checked, True) def test_clear_input_checked_returns_false_only_if_not_required(self): """ ClearableFileInput.value_from_datadict never returns False if the field is required. """ widget = ClearableFileInput() widget.is_required = True field = SimpleUploadedFile("something.txt", b"content") value = widget.value_from_datadict( data={"myfile-clear": True}, files={"myfile": field}, name="myfile", ) self.assertEqual(value, field) self.assertIs(widget.checked, True) def test_html_does_not_mask_exceptions(self): """ A ClearableFileInput should not mask exceptions produced while checking that it has a value. """ class FailingURLFieldFile: @property def url(self): raise ValueError("Canary") def __str__(self): return "value" with self.assertRaisesMessage(ValueError, "Canary"): self.widget.render("myfile", FailingURLFieldFile()) def test_url_as_property(self): class URLFieldFile: @property def url(self): return "https://www.python.org/" def __str__(self): return "value" html = self.widget.render("myfile", URLFieldFile()) self.assertInHTML('<a href="https://www.python.org/">value</a>', html) def test_return_false_if_url_does_not_exists(self): class NoURLFieldFile: def __str__(self): return "value" html = self.widget.render("myfile", NoURLFieldFile()) self.assertHTMLEqual(html, '<input name="myfile" type="file">') def test_use_required_attribute(self): # False when initial data exists. The file input is left blank by the # user to keep the existing, initial value. self.assertIs(self.widget.use_required_attribute(None), True) self.assertIs(self.widget.use_required_attribute("resume.txt"), False) def test_value_omitted_from_data(self): widget = ClearableFileInput() self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( widget.value_omitted_from_data({}, {"field": "x"}, "field"), False ) self.assertIs( widget.value_omitted_from_data({"field-clear": "y"}, {}, "field"), False ) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = FileField(widget=self.widget) with_file = FileField(widget=self.widget, initial=FakeFieldFile()) clearable_file = FileField( widget=self.widget, initial=FakeFieldFile(), required=False ) form = TestForm() self.assertIs(self.widget.use_fieldset, False) self.assertHTMLEqual( '<div><label for="id_field">Field:</label>' '<input id="id_field" name="field" type="file" required></div>' '<div><label for="id_with_file">With file:</label>Currently: ' '<a href="something">something</a><br>Change:<input type="file" ' 'name="with_file" id="id_with_file"></div>' '<div><label for="id_clearable_file">Clearable file:</label>' 'Currently: <a href="something">something</a><input ' 'type="checkbox" name="clearable_file-clear" id="clearable_file-clear_id">' '<label for="clearable_file-clear_id">Clear</label><br>Change:' '<input type="file" name="clearable_file" id="id_clearable_file"></div>', form.render(), )
5842ff05580a75d0954471a7431f837aec92171f4282ba15cdfd6e9b1d47b954
from django.core.exceptions import ValidationError from django.forms import URLField from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango60Warning from . import FormFieldAssertionsMixin @ignore_warnings(category=RemovedInDjango60Warning) class URLFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_urlfield_widget(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" required>') def test_urlfield_widget_max_min_length(self): f = URLField(min_length=15, max_length=20) self.assertEqual("http://example.com", f.clean("http://example.com")) self.assertWidgetRendersTo( f, '<input id="id_f" type="url" name="f" maxlength="20" ' 'minlength="15" required>', ) msg = "'Ensure this value has at least 15 characters (it has 12).'" with self.assertRaisesMessage(ValidationError, msg): f.clean("http://f.com") msg = "'Ensure this value has at most 20 characters (it has 37).'" with self.assertRaisesMessage(ValidationError, msg): f.clean("http://abcdefghijklmnopqrstuvwxyz.com") def test_urlfield_clean(self): # RemovedInDjango60Warning: When the deprecation ends, remove the # assume_scheme argument. f = URLField(required=False, assume_scheme="https") tests = [ ("http://localhost", "http://localhost"), ("http://example.com", "http://example.com"), ("http://example.com/test", "http://example.com/test"), ("http://example.com.", "http://example.com."), ("http://www.example.com", "http://www.example.com"), ("http://www.example.com:8000/test", "http://www.example.com:8000/test"), ( "http://example.com?some_param=some_value", "http://example.com?some_param=some_value", ), ("valid-with-hyphens.com", "https://valid-with-hyphens.com"), ("subdomain.domain.com", "https://subdomain.domain.com"), ("http://200.8.9.10", "http://200.8.9.10"), ("http://200.8.9.10:8000/test", "http://200.8.9.10:8000/test"), ("http://valid-----hyphens.com", "http://valid-----hyphens.com"), ( "http://some.idn.xyzäöüßabc.domain.com:123/blah", "http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah", ), ( "www.example.com/s/http://code.djangoproject.com/ticket/13804", "https://www.example.com/s/http://code.djangoproject.com/ticket/13804", ), # Normalization. ("http://example.com/ ", "http://example.com/"), # Valid IDN. ("http://עברית.idn.icann.org/", "http://עברית.idn.icann.org/"), ("http://sãopaulo.com/", "http://sãopaulo.com/"), ("http://sãopaulo.com.br/", "http://sãopaulo.com.br/"), ("http://пример.испытание/", "http://пример.испытание/"), ("http://مثال.إختبار/", "http://مثال.إختبار/"), ("http://例子.测试/", "http://例子.测试/"), ("http://例子.測試/", "http://例子.測試/"), ( "http://उदाहरण.परीक्षा/", "http://उदाहरण.परीक्षा/", ), ("http://例え.テスト/", "http://例え.テスト/"), ("http://مثال.آزمایشی/", "http://مثال.آزمایشی/"), ("http://실례.테스트/", "http://실례.테스트/"), ("http://العربية.idn.icann.org/", "http://العربية.idn.icann.org/"), # IPv6. ("http://[12:34::3a53]/", "http://[12:34::3a53]/"), ("http://[a34:9238::]:8080/", "http://[a34:9238::]:8080/"), ] for url, expected in tests: with self.subTest(url=url): self.assertEqual(f.clean(url), expected) def test_urlfield_clean_invalid(self): f = URLField() tests = [ "foo", "com.", ".", "http://", "http://example", "http://example.", "http://.com", "http://invalid-.com", "http://-invalid.com", "http://inv-.alid-.com", "http://inv-.-alid.com", "[a", "http://[a", # Non-string. 23, # Hangs "forever" before fixing a catastrophic backtracking, # see #11198. "http://%s" % ("X" * 60,), # A second example, to make sure the problem is really addressed, # even on domains that don't fail the domain label length check in # the regex. "http://%s" % ("X" * 200,), # urlsplit() raises ValueError. "////]@N.AN", # Empty hostname. "#@A.bO", ] msg = "'Enter a valid URL.'" for value in tests: with self.subTest(value=value): with self.assertRaisesMessage(ValidationError, msg): f.clean(value) def test_urlfield_clean_required(self): f = URLField() msg = "'This field is required.'" with self.assertRaisesMessage(ValidationError, msg): f.clean(None) with self.assertRaisesMessage(ValidationError, msg): f.clean("") def test_urlfield_clean_not_required(self): f = URLField(required=False) self.assertEqual(f.clean(None), "") self.assertEqual(f.clean(""), "") def test_urlfield_strip_on_none_value(self): f = URLField(required=False, empty_value=None) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) def test_urlfield_unable_to_set_strip_kwarg(self): msg = "__init__() got multiple values for keyword argument 'strip'" with self.assertRaisesMessage(TypeError, msg): URLField(strip=False) def test_urlfield_assume_scheme(self): f = URLField() # RemovedInDjango60Warning: When the deprecation ends, replace with: # "https://example.com" self.assertEqual(f.clean("example.com"), "http://example.com") f = URLField(assume_scheme="http") self.assertEqual(f.clean("example.com"), "http://example.com") f = URLField(assume_scheme="https") self.assertEqual(f.clean("example.com"), "https://example.com") class URLFieldAssumeSchemeDeprecationTest(FormFieldAssertionsMixin, SimpleTestCase): def test_urlfield_raises_warning(self): msg = ( "The default scheme will be changed from 'http' to 'https' in Django 6.0. " "Pass the forms.URLField.assume_scheme argument to silence this warning." ) with self.assertWarnsMessage(RemovedInDjango60Warning, msg): f = URLField() self.assertEqual(f.clean("example.com"), "http://example.com")
a4634bb02b8540d181510658377f49a11e9da95023aaf5be763f18d8984c6b26
from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ( BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, EmailField, FileField, FloatField, Form, GenericIPAddressField, IntegerField, ModelChoiceField, ModelMultipleChoiceField, MultipleChoiceField, RegexField, SplitDateTimeField, TimeField, URLField, utils, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango60Warning from django.utils.safestring import mark_safe from ..models import ChoiceModel class AssertFormErrorsMixin: def assertFormErrors(self, expected, the_callable, *args, **kwargs): with self.assertRaises(ValidationError) as cm: the_callable(*args, **kwargs) self.assertEqual(cm.exception.messages, expected) class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin): def test_charfield(self): e = { "required": "REQUIRED", "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s", "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s", } f = CharField(min_length=5, max_length=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["LENGTH 4, MIN LENGTH 5"], f.clean, "1234") self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "12345678901") def test_integerfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_value": "MIN VALUE IS %(limit_value)s", "max_value": "MAX VALUE IS %(limit_value)s", } f = IntegerField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4") self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11") def test_floatfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_value": "MIN VALUE IS %(limit_value)s", "max_value": "MAX VALUE IS %(limit_value)s", } f = FloatField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4") self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11") def test_decimalfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_value": "MIN VALUE IS %(limit_value)s", "max_value": "MAX VALUE IS %(limit_value)s", "max_digits": "MAX DIGITS IS %(max)s", "max_decimal_places": "MAX DP IS %(max)s", "max_whole_digits": "MAX DIGITS BEFORE DP IS %(max)s", } f = DecimalField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4") self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11") f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) self.assertFormErrors(["MAX DIGITS IS 4"], f2.clean, "123.45") self.assertFormErrors(["MAX DP IS 2"], f2.clean, "1.234") self.assertFormErrors(["MAX DIGITS BEFORE DP IS 2"], f2.clean, "123.4") def test_datefield(self): e = { "required": "REQUIRED", "invalid": "INVALID", } f = DateField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") def test_timefield(self): e = { "required": "REQUIRED", "invalid": "INVALID", } f = TimeField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") def test_datetimefield(self): e = { "required": "REQUIRED", "invalid": "INVALID", } f = DateTimeField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") def test_regexfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s", "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s", } f = RegexField(r"^[0-9]+$", min_length=5, max_length=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abcde") self.assertFormErrors(["LENGTH 4, MIN LENGTH 5"], f.clean, "1234") self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "12345678901") def test_emailfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s", "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s", } f = EmailField(min_length=8, max_length=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abcdefgh") self.assertFormErrors(["LENGTH 7, MIN LENGTH 8"], f.clean, "[email protected]") self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "[email protected]") def test_filefield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "missing": "MISSING", "empty": "EMPTY FILE", } f = FileField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc") self.assertFormErrors(["EMPTY FILE"], f.clean, SimpleUploadedFile("name", None)) self.assertFormErrors(["EMPTY FILE"], f.clean, SimpleUploadedFile("name", "")) def test_urlfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "max_length": '"%(value)s" has more than %(limit_value)d characters.', } with ignore_warnings(category=RemovedInDjango60Warning): f = URLField(error_messages=e, max_length=17) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abc.c") self.assertFormErrors( ['"http://djangoproject.com" has more than 17 characters.'], f.clean, "djangoproject.com", ) def test_booleanfield(self): e = { "required": "REQUIRED", } f = BooleanField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") def test_choicefield(self): e = { "required": "REQUIRED", "invalid_choice": "%(value)s IS INVALID CHOICE", } f = ChoiceField(choices=[("a", "aye")], error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["b IS INVALID CHOICE"], f.clean, "b") def test_multiplechoicefield(self): e = { "required": "REQUIRED", "invalid_choice": "%(value)s IS INVALID CHOICE", "invalid_list": "NOT A LIST", } f = MultipleChoiceField(choices=[("a", "aye")], error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["NOT A LIST"], f.clean, "b") self.assertFormErrors(["b IS INVALID CHOICE"], f.clean, ["b"]) def test_splitdatetimefield(self): e = { "required": "REQUIRED", "invalid_date": "INVALID DATE", "invalid_time": "INVALID TIME", } f = SplitDateTimeField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID DATE", "INVALID TIME"], f.clean, ["a", "b"]) def test_generic_ipaddressfield(self): e = { "required": "REQUIRED", "invalid": "INVALID IP ADDRESS", } f = GenericIPAddressField(error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID IP ADDRESS"], f.clean, "127.0.0") def test_subclassing_errorlist(self): class TestForm(Form): first_name = CharField() last_name = CharField() birthday = DateField() def clean(self): raise ValidationError("I like to be awkward.") class CustomErrorList(utils.ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return "" return mark_safe( '<div class="error">%s</div>' % "".join("<p>%s</p>" % e for e in self) ) # This form should print errors the default way. form1 = TestForm({"first_name": "John"}) self.assertHTMLEqual( str(form1["last_name"].errors), '<ul class="errorlist"><li>This field is required.</li></ul>', ) self.assertHTMLEqual( str(form1.errors["__all__"]), '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>', ) # This one should wrap error groups in the customized way. form2 = TestForm({"first_name": "John"}, error_class=CustomErrorList) self.assertHTMLEqual( str(form2["last_name"].errors), '<div class="error"><p>This field is required.</p></div>', ) self.assertHTMLEqual( str(form2.errors["__all__"]), '<div class="error"><p>I like to be awkward.</p></div>', ) def test_error_messages_escaping(self): # The forms layer doesn't escape input values directly because error # messages might be presented in non-HTML contexts. Instead, the # message is marked for escaping by the template engine, so a template # is needed to trigger the escaping. t = Template("{{ form.errors }}") class SomeForm(Form): field = ChoiceField(choices=[("one", "One")]) f = SomeForm({"field": "<script>"}) self.assertHTMLEqual( t.render(Context({"form": f})), '<ul class="errorlist"><li>field<ul class="errorlist">' "<li>Select a valid choice. &lt;script&gt; is not one of the " "available choices.</li></ul></li></ul>", ) class SomeForm(Form): field = MultipleChoiceField(choices=[("one", "One")]) f = SomeForm({"field": ["<script>"]}) self.assertHTMLEqual( t.render(Context({"form": f})), '<ul class="errorlist"><li>field<ul class="errorlist">' "<li>Select a valid choice. &lt;script&gt; is not one of the " "available choices.</li></ul></li></ul>", ) class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({"field": ["<script>"]}) self.assertHTMLEqual( t.render(Context({"form": f})), '<ul class="errorlist"><li>field<ul class="errorlist">' "<li>“&lt;script&gt;” is not a valid value.</li>" "</ul></li></ul>", ) class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): def test_modelchoicefield(self): # Create choices for the model choice field tests below. ChoiceModel.objects.create(pk=1, name="a") ChoiceModel.objects.create(pk=2, name="b") ChoiceModel.objects.create(pk=3, name="c") # ModelChoiceField e = { "required": "REQUIRED", "invalid_choice": "INVALID CHOICE", } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID CHOICE"], f.clean, "4") # ModelMultipleChoiceField e = { "required": "REQUIRED", "invalid_choice": "%(value)s IS INVALID CHOICE", "invalid_list": "NOT A LIST OF VALUES", } f = ModelMultipleChoiceField( queryset=ChoiceModel.objects.all(), error_messages=e ) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["NOT A LIST OF VALUES"], f.clean, "3") self.assertFormErrors(["4 IS INVALID CHOICE"], f.clean, ["4"]) def test_modelchoicefield_value_placeholder(self): f = ModelChoiceField( queryset=ChoiceModel.objects.all(), error_messages={ "invalid_choice": '"%(value)s" is not one of the available choices.', }, ) self.assertFormErrors( ['"invalid" is not one of the available choices.'], f.clean, "invalid", )
e88b5dcc8051d54e6ee964e029584519b78adeb5ee21e2256ec3fce52d2ea941
from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class RandomTests(SimpleTestCase): @setup({"random01": "{{ a|random }} {{ b|random }}"}) def test_random01(self): output = self.engine.render_to_string( "random01", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} ) self.assertEqual(output, "a&amp;b a&b") @setup( { "random02": ( "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}" ) } ) def test_random02(self): output = self.engine.render_to_string( "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} ) self.assertEqual(output, "a&b a&b") @setup({"empty_list": "{{ list|random }}"}) def test_empty_list(self): output = self.engine.render_to_string("empty_list", {"list": []}) self.assertEqual(output, "")
248d7f99dc3618ebaeaea464a38a0c8c4f7a0da1003c07f3b312ea5b2cd23c54
import decimal from django.core.management.color import no_style from django.db import NotSupportedError, connection, transaction from django.db.backends.base.operations import BaseDatabaseOperations from django.db.models import DurationField, Value from django.db.models.expressions import Col from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, override_settings, skipIfDBFeature, ) from django.utils import timezone from ..models import Author, Book class SimpleDatabaseOperationTests(SimpleTestCase): may_require_msg = "subclasses of BaseDatabaseOperations may require a %s() method" def setUp(self): self.ops = BaseDatabaseOperations(connection=connection) def test_deferrable_sql(self): self.assertEqual(self.ops.deferrable_sql(), "") def test_end_transaction_rollback(self): self.assertEqual(self.ops.end_transaction_sql(success=False), "ROLLBACK;") def test_no_limit_value(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "no_limit_value" ): self.ops.no_limit_value() def test_quote_name(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "quote_name" ): self.ops.quote_name("a") def test_regex_lookup(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "regex_lookup" ): self.ops.regex_lookup(lookup_type="regex") def test_set_time_zone_sql(self): self.assertEqual(self.ops.set_time_zone_sql(), "") def test_sql_flush(self): msg = "subclasses of BaseDatabaseOperations must provide an sql_flush() method" with self.assertRaisesMessage(NotImplementedError, msg): self.ops.sql_flush(None, None) def test_pk_default_value(self): self.assertEqual(self.ops.pk_default_value(), "DEFAULT") def test_tablespace_sql(self): self.assertEqual(self.ops.tablespace_sql(None), "") def test_sequence_reset_by_name_sql(self): self.assertEqual(self.ops.sequence_reset_by_name_sql(None, []), []) def test_adapt_unknown_value_decimal(self): value = decimal.Decimal("3.14") self.assertEqual( self.ops.adapt_unknown_value(value), self.ops.adapt_decimalfield_value(value), ) def test_adapt_unknown_value_date(self): value = timezone.now().date() self.assertEqual( self.ops.adapt_unknown_value(value), self.ops.adapt_datefield_value(value) ) def test_adapt_unknown_value_time(self): value = timezone.now().time() self.assertEqual( self.ops.adapt_unknown_value(value), self.ops.adapt_timefield_value(value) ) def test_adapt_timefield_value_none(self): self.assertIsNone(self.ops.adapt_timefield_value(None)) def test_adapt_timefield_value_expression(self): value = Value(timezone.now().time()) self.assertEqual(self.ops.adapt_timefield_value(value), value) def test_adapt_datetimefield_value_none(self): self.assertIsNone(self.ops.adapt_datetimefield_value(None)) def test_adapt_datetimefield_value_expression(self): value = Value(timezone.now()) self.assertEqual(self.ops.adapt_datetimefield_value(value), value) def test_adapt_timefield_value(self): msg = "Django does not support timezone-aware times." with self.assertRaisesMessage(ValueError, msg): self.ops.adapt_timefield_value(timezone.make_aware(timezone.now())) @override_settings(USE_TZ=False) def test_adapt_timefield_value_unaware(self): now = timezone.now() self.assertEqual(self.ops.adapt_timefield_value(now), str(now)) def test_format_for_duration_arithmetic(self): msg = self.may_require_msg % "format_for_duration_arithmetic" with self.assertRaisesMessage(NotImplementedError, msg): self.ops.format_for_duration_arithmetic(None) def test_date_extract_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "date_extract_sql" ): self.ops.date_extract_sql(None, None, None) def test_time_extract_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "date_extract_sql" ): self.ops.time_extract_sql(None, None, None) def test_date_trunc_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "date_trunc_sql" ): self.ops.date_trunc_sql(None, None, None) def test_time_trunc_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "time_trunc_sql" ): self.ops.time_trunc_sql(None, None, None) def test_datetime_trunc_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "datetime_trunc_sql" ): self.ops.datetime_trunc_sql(None, None, None, None) def test_datetime_cast_date_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "datetime_cast_date_sql" ): self.ops.datetime_cast_date_sql(None, None, None) def test_datetime_cast_time_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "datetime_cast_time_sql" ): self.ops.datetime_cast_time_sql(None, None, None) def test_datetime_extract_sql(self): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "datetime_extract_sql" ): self.ops.datetime_extract_sql(None, None, None, None) def test_prepare_join_on_clause(self): author_table = Author._meta.db_table author_id_field = Author._meta.get_field("id") book_table = Book._meta.db_table book_fk_field = Book._meta.get_field("author") lhs_expr, rhs_expr = self.ops.prepare_join_on_clause( author_table, author_id_field, book_table, book_fk_field, ) self.assertEqual(lhs_expr, Col(author_table, author_id_field)) self.assertEqual(rhs_expr, Col(book_table, book_fk_field)) class DatabaseOperationTests(TestCase): def setUp(self): self.ops = BaseDatabaseOperations(connection=connection) @skipIfDBFeature("supports_over_clause") def test_window_frame_raise_not_supported_error(self): msg = "This backend does not support window expressions." with self.assertRaisesMessage(NotSupportedError, msg): self.ops.window_frame_rows_start_end() @skipIfDBFeature("can_distinct_on_fields") def test_distinct_on_fields(self): msg = "DISTINCT ON fields is not supported by this database backend" with self.assertRaisesMessage(NotSupportedError, msg): self.ops.distinct_sql(["a", "b"], None) @skipIfDBFeature("supports_temporal_subtraction") def test_subtract_temporals(self): duration_field = DurationField() duration_field_internal_type = duration_field.get_internal_type() msg = ( "This backend does not support %s subtraction." % duration_field_internal_type ) with self.assertRaisesMessage(NotSupportedError, msg): self.ops.subtract_temporals(duration_field_internal_type, None, None) class SqlFlushTests(TransactionTestCase): available_apps = ["backends"] def test_sql_flush_no_tables(self): self.assertEqual(connection.ops.sql_flush(no_style(), []), []) def test_execute_sql_flush_statements(self): with transaction.atomic(): author = Author.objects.create(name="George Orwell") Book.objects.create(author=author) author = Author.objects.create(name="Harper Lee") Book.objects.create(author=author) Book.objects.create(author=author) self.assertIs(Author.objects.exists(), True) self.assertIs(Book.objects.exists(), True) sql_list = connection.ops.sql_flush( no_style(), [Author._meta.db_table, Book._meta.db_table], reset_sequences=True, allow_cascade=True, ) connection.ops.execute_sql_flush(sql_list) with transaction.atomic(): self.assertIs(Author.objects.exists(), False) self.assertIs(Book.objects.exists(), False) if connection.features.supports_sequence_reset: author = Author.objects.create(name="F. Scott Fitzgerald") self.assertEqual(author.pk, 1) book = Book.objects.create(author=author) self.assertEqual(book.pk, 1)
663d74bb4072b8c0f9be91695a633887111f15b9bdbd20e93ce76dee215f3392
import copy import unittest from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError, connection, connections, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.test import TestCase, override_settings try: from django.db.backends.postgresql.psycopg_any import errors, is_psycopg3 except ImportError: is_psycopg3 = False @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class Tests(TestCase): databases = {"default", "other"} def test_nodb_cursor(self): """ The _nodb_cursor() fallbacks to the default connection database when access to the 'postgres' database is not granted. """ orig_connect = BaseDatabaseWrapper.connect def mocked_connect(self): if self.settings_dict["NAME"] is None: raise DatabaseError() return orig_connect(self) with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIsNone(cursor.db.settings_dict["NAME"]) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with mock.patch.object( connection, "settings_dict", {**connection.settings_dict, "NAME": "postgres"}, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) self.assertIsNotNone(cursor.db.settings_dict["NAME"]) self.assertEqual( cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"] ) # Cursor is yielded only for the first PostgreSQL database. with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) def test_nodb_cursor_raises_postgres_authentication_failure(self): """ _nodb_cursor() re-raises authentication failure to the 'postgres' db when other connection to the PostgreSQL database isn't available. """ def mocked_connect(self): raise DatabaseError() def mocked_all(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy(connection.settings_dict) test_connection.settings_dict["NAME"] = "postgres" return [test_connection] msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): mocker_connections_all = mock.patch( "django.utils.connection.BaseConnectionHandler.all", side_effect=mocked_all, autospec=True, ) mocker_connect = mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ) with mocker_connections_all, mocker_connect: with self.assertRaises(DatabaseError): with connection._nodb_cursor(): pass def test_nodb_cursor_reraise_exceptions(self): with self.assertRaisesMessage(DatabaseError, "exception"): with connection._nodb_cursor(): raise DatabaseError("exception") def test_database_name_too_long(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() max_name_length = connection.ops.max_name_length() settings["NAME"] = "a" + (max_name_length * "a") msg = ( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %s characters. Supply a shorter NAME in " "settings.DATABASES." ) % (settings["NAME"], max_name_length + 1, max_name_length) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_database_name_empty(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = "" msg = ( "settings.DATABASES is improperly configured. Please supply the " "NAME or OPTIONS['service'] value." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_service_name(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["OPTIONS"] = {"service": "my_service"} settings["NAME"] = "" params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["service"], "my_service") self.assertNotIn("database", params) def test_service_name_default_db(self): # None is used to connect to the default 'postgres' db. from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = None settings["OPTIONS"] = {"service": "django_test"} params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["dbname"], "postgres") self.assertNotIn("service", params) def test_connect_and_rollback(self): """ PostgreSQL shouldn't roll back SET TIME ZONE, even if the first transaction is rolled back (#17062). """ new_connection = connection.copy() try: # Ensure the database default time zone is different than # the time zone in new_connection.settings_dict. We can # get the default time zone by reset & show. with new_connection.cursor() as cursor: cursor.execute("RESET TIMEZONE") cursor.execute("SHOW TIMEZONE") db_default_tz = cursor.fetchone()[0] new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC" new_connection.close() # Invalidate timezone name cache, because the setting_changed # handler cannot know about new_connection. del new_connection.timezone_name # Fetch a new connection with the new_tz as default # time zone, run a query and rollback. with self.settings(TIME_ZONE=new_tz): new_connection.set_autocommit(False) new_connection.rollback() # Now let's see if the rollback rolled back the SET TIME ZONE. with new_connection.cursor() as cursor: cursor.execute("SHOW TIMEZONE") tz = cursor.fetchone()[0] self.assertEqual(new_tz, tz) finally: new_connection.close() def test_connect_non_autocommit(self): """ The connection wrapper shouldn't believe that autocommit is enabled after setting the time zone when AUTOCOMMIT is False (#21452). """ new_connection = connection.copy() new_connection.settings_dict["AUTOCOMMIT"] = False try: # Open a database connection. with new_connection.cursor(): self.assertFalse(new_connection.get_autocommit()) finally: new_connection.close() def test_connect_isolation_level(self): """ The transaction level can be configured with DATABASES ['OPTIONS']['isolation_level']. """ from django.db.backends.postgresql.psycopg_any import IsolationLevel # Since this is a django.test.TestCase, a transaction is in progress # and the isolation level isn't reported as 0. This test assumes that # PostgreSQL is configured with the default isolation level. # Check the level on the psycopg connection, not the Django wrapper. self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = IsolationLevel.SERIALIZABLE try: # Start a transaction so the isolation level isn't reported as 0. new_connection.set_autocommit(False) # Check the level on the psycopg connection, not the Django wrapper. self.assertEqual( new_connection.connection.isolation_level, IsolationLevel.SERIALIZABLE, ) finally: new_connection.close() def test_connect_invalid_isolation_level(self): self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = -1 msg = ( "Invalid transaction isolation level -1 specified. Use one of the " "psycopg.IsolationLevel values." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.ensure_connection() def test_connect_role(self): """ The session role can be configured with DATABASES ["OPTIONS"]["assume_role"]. """ try: custom_role = "django_nonexistent_role" new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["assume_role"] = custom_role msg = f'role "{custom_role}" does not exist' with self.assertRaisesMessage(errors.InvalidParameterValue, msg): new_connection.connect() finally: new_connection.close() @unittest.skipUnless(is_psycopg3, "psycopg3 specific test") def test_connect_server_side_binding(self): """ The server-side parameters binding role can be enabled with DATABASES ["OPTIONS"]["server_side_binding"]. """ from django.db.backends.postgresql.base import ServerBindingCursor new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["server_side_binding"] = True try: new_connection.connect() self.assertEqual( new_connection.connection.cursor_factory, ServerBindingCursor, ) finally: new_connection.close() def test_connect_custom_cursor_factory(self): """ A custom cursor factory can be configured with DATABASES["options"] ["cursor_factory"]. """ from django.db.backends.postgresql.base import Cursor class MyCursor(Cursor): pass new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["cursor_factory"] = MyCursor try: new_connection.connect() self.assertEqual(new_connection.connection.cursor_factory, MyCursor) finally: new_connection.close() def test_connect_no_is_usable_checks(self): new_connection = connection.copy() try: with mock.patch.object(new_connection, "is_usable") as is_usable: new_connection.connect() is_usable.assert_not_called() finally: new_connection.close() def test_client_encoding_utf8_enforce(self): new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["client_encoding"] = "iso-8859-2" try: new_connection.connect() if is_psycopg3: self.assertEqual(new_connection.connection.info.encoding, "utf-8") else: self.assertEqual(new_connection.connection.encoding, "UTF8") finally: new_connection.close() def _select(self, val): with connection.cursor() as cursor: cursor.execute("SELECT %s::text[]", (val,)) return cursor.fetchone()[0] def test_select_ascii_array(self): a = ["awef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_select_unicode_array(self): a = ["ᄲawef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_lookup_cast(self): from django.db.backends.postgresql.operations import DatabaseOperations do = DatabaseOperations(connection=None) lookups = ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ) for lookup in lookups: with self.subTest(lookup=lookup): self.assertIn("::text", do.lookup_cast(lookup)) # RemovedInDjango51Warning. for lookup in lookups: for field_type in ("CICharField", "CIEmailField", "CITextField"): with self.subTest(lookup=lookup, field_type=field_type): self.assertIn( "::citext", do.lookup_cast(lookup, internal_type=field_type) ) def test_correct_extraction_psycopg_version(self): from django.db.backends.postgresql.base import Database, psycopg_version with mock.patch.object(Database, "__version__", "4.2.1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg_version(), (4, 2, 1)) with mock.patch.object( Database, "__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)" ): self.assertEqual(psycopg_version(), (4, 2)) @override_settings(DEBUG=True) @unittest.skipIf(is_psycopg3, "psycopg2 specific test") def test_copy_to_expert_cursors(self): out = StringIO() copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: cursor.copy_expert(copy_expert_sql, out) cursor.copy_to(out, "django_session") self.assertEqual( [q["sql"] for q in connection.queries], [copy_expert_sql, "COPY django_session TO STDOUT"], ) @override_settings(DEBUG=True) @unittest.skipUnless(is_psycopg3, "psycopg3 specific test") def test_copy_cursors(self): copy_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: with cursor.copy(copy_sql) as copy: for row in copy: pass self.assertEqual([q["sql"] for q in connection.queries], [copy_sql]) def test_get_database_version(self): new_connection = connection.copy() new_connection.pg_version = 110009 self.assertEqual(new_connection.get_database_version(), (11, 9)) @mock.patch.object(connection, "get_database_version", return_value=(11,)) def test_check_database_version_supported(self, mocked_get_database_version): msg = "PostgreSQL 12 or later is required (found 11)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called) def test_compose_sql_when_no_connection(self): new_connection = connection.copy() try: self.assertEqual( new_connection.ops.compose_sql("SELECT %s", ["test"]), "SELECT 'test'", ) finally: new_connection.close()
562b0ba80c7424557a9d80d3afb9e90420abd89d7338ade9a4aaf50c6da86435
import unittest from django.core.management.color import no_style from django.db import connection from django.db.models.expressions import Col from django.db.models.functions import Cast from django.test import SimpleTestCase from ..models import Author, Book, Person, Tag @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests.") class PostgreSQLOperationsTests(SimpleTestCase): def test_sql_flush(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], ), ['TRUNCATE "backends_person", "backends_tag";'], ) def test_sql_flush_allow_cascade(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=True, ), ['TRUNCATE "backends_person", "backends_tag" CASCADE;'], ) def test_sql_flush_sequences(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, ), ['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY;'], ) def test_sql_flush_sequences_allow_cascade(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=True, ), ['TRUNCATE "backends_person", "backends_tag" RESTART IDENTITY CASCADE;'], ) def test_prepare_join_on_clause_same_type(self): author_table = Author._meta.db_table author_id_field = Author._meta.get_field("id") lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause( author_table, author_id_field, author_table, author_id_field, ) self.assertEqual(lhs_expr, Col(author_table, author_id_field)) self.assertEqual(rhs_expr, Col(author_table, author_id_field)) def test_prepare_join_on_clause_different_types(self): author_table = Author._meta.db_table author_id_field = Author._meta.get_field("id") book_table = Book._meta.db_table book_fk_field = Book._meta.get_field("author") lhs_expr, rhs_expr = connection.ops.prepare_join_on_clause( author_table, author_id_field, book_table, book_fk_field, ) self.assertEqual(lhs_expr, Col(author_table, author_id_field)) self.assertEqual( rhs_expr, Cast(Col(book_table, book_fk_field), author_id_field) )
d82455262782e9d20251ec67eb9ff3ec302f341cb46bb656a13be1484f5a99a7
from django.db import models from django.db.models.fields.related import ReverseManyToOneDescriptor from django.db.models.lookups import StartsWith from django.db.models.query_utils import PathInfo class CustomForeignObjectRel(models.ForeignObjectRel): """ Define some extra Field methods so this Rel acts more like a Field, which lets us use ReverseManyToOneDescriptor in both directions. """ @property def foreign_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.field.related_fields) def get_attname(self): return self.name class StartsWithRelation(models.ForeignObject): """ A ForeignObject that uses StartsWith operator in its joins instead of the default equality operator. This is logically a many-to-many relation and creates a ReverseManyToOneDescriptor in both directions. """ auto_created = False many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = CustomForeignObjectRel def __init__(self, *args, **kwargs): kwargs["on_delete"] = models.DO_NOTHING super().__init__(*args, **kwargs) @property def field(self): """ Makes ReverseManyToOneDescriptor work in both directions. """ return self.remote_field def get_extra_restriction(self, alias, related_alias): to_field = self.remote_field.model._meta.get_field(self.to_fields[0]) from_field = self.model._meta.get_field(self.from_fields[0]) return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias)) def get_joining_fields(self, reverse_join=False): return () def get_path_info(self, filtered_relation=None): to_opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def get_reverse_path_info(self, filtered_relation=None): to_opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self.remote_field, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def contribute_to_class(self, cls, name, private_only=False): super().contribute_to_class(cls, name, private_only) setattr(cls, self.name, ReverseManyToOneDescriptor(self)) class BrokenContainsRelation(StartsWithRelation): """ This model is designed to yield no join conditions and raise an exception in ``Join.as_sql()``. """ def get_extra_restriction(self, alias, related_alias): return None class SlugPage(models.Model): slug = models.CharField(max_length=20, unique=True) descendants = StartsWithRelation( "self", from_fields=["slug"], to_fields=["slug"], related_name="ascendants", ) containers = BrokenContainsRelation( "self", from_fields=["slug"], to_fields=["slug"], ) class Meta: ordering = ["slug"] def __str__(self): return "SlugPage %s" % self.slug
a54e2e520658f74c8e4b9496fe11985a9382499b34b78269df036ae6e4d4e3a9
from django.db.models import F, IntegerField from django.db.models.functions import Chr, Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ChrTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("J"))), [self.john]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("J"))), [self.elena, self.rhonda] ) def test_non_ascii(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("É"))), [self.elena]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("É"))), [self.john, self.rhonda] ) def test_transform(self): with register_lookup(IntegerField, Chr): authors = Author.objects.annotate(name_code_point=Ord("name")) self.assertCountEqual( authors.filter(name_code_point__chr=Chr(ord("J"))), [self.john] ) self.assertCountEqual( authors.exclude(name_code_point__chr=Chr(ord("J"))), [self.elena, self.rhonda], ) def test_annotate(self): authors = Author.objects.annotate( first_initial=Left("name", 1), initial_chr=Chr(ord("J")), ) self.assertSequenceEqual( authors.filter(first_initial=F("initial_chr")), [self.john], )
94803fba17d9bcddbe446840560def92e5ab82794c8c4224fe03236a7f0dfa0c
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse, HttpResponsePermanentRedirect from django.middleware.locale import LocaleMiddleware from django.template import Context, Template from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory from django.test.utils import override_script_prefix from django.urls import clear_url_caches, resolve, reverse, translate_url from django.utils import translation class PermanentRedirectLocaleMiddleWare(LocaleMiddleware): response_redirect_class = HttpResponsePermanentRedirect @override_settings( USE_I18N=True, LOCALE_PATHS=[ os.path.join(os.path.dirname(__file__), "locale"), ], LANGUAGE_CODE="en-us", LANGUAGES=[ ("nl", "Dutch"), ("en", "English"), ("pt-br", "Brazilian Portuguese"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.patterns.urls.default", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(os.path.dirname(__file__), "templates")], "OPTIONS": { "context_processors": [ "django.template.context_processors.i18n", ], }, } ], ) class URLTestCaseBase(SimpleTestCase): """ TestCase base-class for the URL tests. """ def setUp(self): # Make sure the cache is empty before we are doing our tests. clear_url_caches() def tearDown(self): # Make sure we will leave an empty cache for other testcases. clear_url_caches() class URLPrefixTests(URLTestCaseBase): """ Tests if the `i18n_patterns` is adding the prefix correctly. """ def test_not_prefixed(self): with translation.override("en"): self.assertEqual(reverse("not-prefixed"), "/not-prefixed/") self.assertEqual( reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/" ) with translation.override("nl"): self.assertEqual(reverse("not-prefixed"), "/not-prefixed/") self.assertEqual( reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/" ) def test_prefixed(self): with translation.override("en"): self.assertEqual(reverse("prefixed"), "/en/prefixed/") with translation.override("nl"): self.assertEqual(reverse("prefixed"), "/nl/prefixed/") with translation.override(None): self.assertEqual( reverse("prefixed"), "/%s/prefixed/" % settings.LANGUAGE_CODE ) @override_settings(ROOT_URLCONF="i18n.patterns.urls.wrong") def test_invalid_prefix_use(self): msg = "Using i18n_patterns in an included URLconf is not allowed." with self.assertRaisesMessage(ImproperlyConfigured, msg): reverse("account:register") @override_settings(ROOT_URLCONF="i18n.patterns.urls.disabled") class URLDisabledTests(URLTestCaseBase): @override_settings(USE_I18N=False) def test_prefixed_i18n_disabled(self): with translation.override("en"): self.assertEqual(reverse("prefixed"), "/prefixed/") with translation.override("nl"): self.assertEqual(reverse("prefixed"), "/prefixed/") class RequestURLConfTests(SimpleTestCase): @override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused") def test_request_urlconf_considered(self): request = RequestFactory().get("/nl/") request.urlconf = "i18n.patterns.urls.default" middleware = LocaleMiddleware(lambda req: HttpResponse()) with translation.override("nl"): middleware.process_request(request) self.assertEqual(request.LANGUAGE_CODE, "nl") @override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused") class PathUnusedTests(URLTestCaseBase): """ If no i18n_patterns is used in root URLconfs, then no language activation activation happens based on url prefix. """ def test_no_lang_activate(self): response = self.client.get("/nl/foo/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") class URLTranslationTests(URLTestCaseBase): """ Tests if the pattern-strings are translated correctly (within the `i18n_patterns` and the normal `patterns` function). """ def test_no_prefix_translated(self): with translation.override("en"): self.assertEqual(reverse("no-prefix-translated"), "/translated/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/translated/yeah/", ) with translation.override("nl"): self.assertEqual(reverse("no-prefix-translated"), "/vertaald/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/vertaald/yeah/", ) with translation.override("pt-br"): self.assertEqual(reverse("no-prefix-translated"), "/traduzidos/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/traduzidos/yeah/", ) def test_users_url(self): with translation.override("en"): self.assertEqual(reverse("users"), "/en/users/") with translation.override("nl"): self.assertEqual(reverse("users"), "/nl/gebruikers/") self.assertEqual(reverse("prefixed_xml"), "/nl/prefixed.xml") with translation.override("pt-br"): self.assertEqual(reverse("users"), "/pt-br/usuarios/") def test_translate_url_utility(self): with translation.override("en"): self.assertEqual( translate_url("/en/nonexistent/", "nl"), "/en/nonexistent/" ) self.assertEqual(translate_url("/en/users/", "nl"), "/nl/gebruikers/") # Namespaced URL self.assertEqual( translate_url("/en/account/register/", "nl"), "/nl/profiel/registreren/" ) # path() URL pattern self.assertEqual( translate_url("/en/account/register-as-path/", "nl"), "/nl/profiel/registreren-als-pad/", ) self.assertEqual(translation.get_language(), "en") # URL with parameters. self.assertEqual( translate_url("/en/with-arguments/regular-argument/", "nl"), "/nl/with-arguments/regular-argument/", ) self.assertEqual( translate_url( "/en/with-arguments/regular-argument/optional.html", "nl" ), "/nl/with-arguments/regular-argument/optional.html", ) with translation.override("nl"): self.assertEqual(translate_url("/nl/gebruikers/", "en"), "/en/users/") self.assertEqual(translation.get_language(), "nl") def test_reverse_translated_with_captured_kwargs(self): with translation.override("en"): match = resolve("/translated/apo/") # Links to the same page in other languages. tests = [ ("nl", "/vertaald/apo/"), ("pt-br", "/traduzidos/apo/"), ] for lang, expected_link in tests: with translation.override(lang): self.assertEqual( reverse( match.url_name, args=match.args, kwargs=match.captured_kwargs ), expected_link, ) def test_locale_not_interepreted_as_regex(self): with translation.override("e("): # Would previously error: # re.error: missing ), unterminated subpattern at position 1 reverse("users") class URLNamespaceTests(URLTestCaseBase): """ Tests if the translations are still working within namespaces. """ def test_account_register(self): with translation.override("en"): self.assertEqual(reverse("account:register"), "/en/account/register/") self.assertEqual( reverse("account:register-as-path"), "/en/account/register-as-path/" ) with translation.override("nl"): self.assertEqual(reverse("account:register"), "/nl/profiel/registreren/") self.assertEqual( reverse("account:register-as-path"), "/nl/profiel/registreren-als-pad/" ) class URLRedirectTests(URLTestCaseBase): """ Tests if the user gets redirected to the right URL when there is no language-prefix in the request URL. """ def test_no_prefix_response(self): response = self.client.get("/not-prefixed/") self.assertEqual(response.status_code, 200) def test_en_redirect(self): response = self.client.get( "/account/register/", headers={"accept-language": "en"} ) self.assertRedirects(response, "/en/account/register/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_en_redirect_wrong_url(self): response = self.client.get( "/profiel/registreren/", headers={"accept-language": "en"} ) self.assertEqual(response.status_code, 404) def test_nl_redirect(self): response = self.client.get( "/profiel/registreren/", headers={"accept-language": "nl"} ) self.assertRedirects(response, "/nl/profiel/registreren/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_nl_redirect_wrong_url(self): response = self.client.get( "/account/register/", headers={"accept-language": "nl"} ) self.assertEqual(response.status_code, 404) def test_pt_br_redirect(self): response = self.client.get( "/conta/registre-se/", headers={"accept-language": "pt-br"} ) self.assertRedirects(response, "/pt-br/conta/registre-se/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_pl_pl_redirect(self): # language from outside of the supported LANGUAGES list response = self.client.get( "/account/register/", headers={"accept-language": "pl-pl"} ) self.assertRedirects(response, "/en/account/register/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) @override_settings( MIDDLEWARE=[ "i18n.patterns.tests.PermanentRedirectLocaleMiddleWare", "django.middleware.common.CommonMiddleware", ], ) def test_custom_redirect_class(self): response = self.client.get( "/account/register/", headers={"accept-language": "en"} ) self.assertRedirects(response, "/en/account/register/", 301) class URLVaryAcceptLanguageTests(URLTestCaseBase): """ 'Accept-Language' is not added to the Vary header when using prefixed URLs. """ def test_no_prefix_response(self): response = self.client.get("/not-prefixed/") self.assertEqual(response.status_code, 200) self.assertEqual(response.get("Vary"), "Accept-Language") def test_en_redirect(self): """ The redirect to a prefixed URL depends on 'Accept-Language' and 'Cookie', but once prefixed no header is set. """ response = self.client.get( "/account/register/", headers={"accept-language": "en"} ) self.assertRedirects(response, "/en/account/register/") self.assertEqual(response.get("Vary"), "Accept-Language, Cookie") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) self.assertFalse(response.get("Vary")) class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=True`). """ def test_not_prefixed_redirect(self): response = self.client.get("/not-prefixed", headers={"accept-language": "en"}) self.assertRedirects(response, "/not-prefixed/", 301) def test_en_redirect(self): response = self.client.get( "/account/register", headers={"accept-language": "en"}, follow=True ) # We only want one redirect, bypassing CommonMiddleware self.assertEqual(response.redirect_chain, [("/en/account/register/", 302)]) self.assertRedirects(response, "/en/account/register/", 302) response = self.client.get( "/prefixed.xml", headers={"accept-language": "en"}, follow=True ) self.assertRedirects(response, "/en/prefixed.xml", 302) class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=False`). """ @override_settings(APPEND_SLASH=False) def test_not_prefixed_redirect(self): response = self.client.get("/not-prefixed", headers={"accept-language": "en"}) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=False) def test_en_redirect(self): response = self.client.get( "/account/register-without-slash", headers={"accept-language": "en"} ) self.assertRedirects(response, "/en/account/register-without-slash", 302) response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) class URLResponseTests(URLTestCaseBase): """Tests if the response has the correct language code.""" def test_not_prefixed_with_prefix(self): response = self.client.get("/en/not-prefixed/") self.assertEqual(response.status_code, 404) def test_en_url(self): response = self.client.get("/en/account/register/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") def test_nl_url(self): response = self.client.get("/nl/profiel/registreren/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "nl") self.assertEqual(response.context["LANGUAGE_CODE"], "nl") def test_wrong_en_prefix(self): response = self.client.get("/en/profiel/registreren/") self.assertEqual(response.status_code, 404) def test_wrong_nl_prefix(self): response = self.client.get("/nl/account/register/") self.assertEqual(response.status_code, 404) def test_pt_br_url(self): response = self.client.get("/pt-br/conta/registre-se/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "pt-br") self.assertEqual(response.context["LANGUAGE_CODE"], "pt-br") def test_en_path(self): response = self.client.get("/en/account/register-as-path/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") def test_nl_path(self): response = self.client.get("/nl/profiel/registreren-als-pad/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "nl") self.assertEqual(response.context["LANGUAGE_CODE"], "nl") @override_settings(ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="nl") class URLPrefixedFalseTranslatedTests(URLTestCaseBase): def test_translated_path_unprefixed_language_other_than_accepted_header(self): response = self.client.get("/gebruikers/", headers={"accept-language": "en"}) self.assertEqual(response.status_code, 200) def test_translated_path_unprefixed_language_other_than_cookie_language(self): self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "en"}) response = self.client.get("/gebruikers/") self.assertEqual(response.status_code, 200) def test_translated_path_prefixed_language_other_than_accepted_header(self): response = self.client.get("/en/users/", headers={"accept-language": "nl"}) self.assertEqual(response.status_code, 200) def test_translated_path_prefixed_language_other_than_cookie_language(self): self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "nl"}) response = self.client.get("/en/users/") self.assertEqual(response.status_code, 200) class URLRedirectWithScriptAliasTests(URLTestCaseBase): """ #21579 - LocaleMiddleware should respect the script prefix. """ def test_language_prefix_with_script_prefix(self): prefix = "/script_prefix" with override_script_prefix(prefix): response = self.client.get( "/prefixed/", headers={"accept-language": "en"}, SCRIPT_NAME=prefix ) self.assertRedirects( response, "%s/en/prefixed/" % prefix, target_status_code=404 ) class URLTagTests(URLTestCaseBase): """ Test if the language tag works. """ def test_strings_only(self): t = Template( """{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""" ) self.assertEqual( t.render(Context({})).strip().split(), ["/vertaald/", "/traduzidos/"] ) def test_context(self): ctx = Context({"lang1": "nl", "lang2": "pt-br"}) tpl = Template( """{% load i18n %} {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""" ) self.assertEqual( tpl.render(ctx).strip().split(), ["/vertaald/", "/traduzidos/"] ) def test_args(self): tpl = Template( """ {% load i18n %} {% language 'nl' %} {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %} {% language 'pt-br' %} {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %} """ ) self.assertEqual( tpl.render(Context({})).strip().split(), ["/vertaald/apo/", "/traduzidos/apo/"], ) def test_kwargs(self): tpl = Template( """ {% load i18n %} {% language 'nl' %} {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} {% language 'pt-br' %} {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} """ ) self.assertEqual( tpl.render(Context({})).strip().split(), ["/vertaald/apo/", "/traduzidos/apo/"], )
2ab58ac9659b9068b8245f5387bba8b2b0f4917d5a4105b9fb9d353df6a78c0e
""" This module converts requested URLs to callback view functions. URLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ import functools import inspect import re import string from importlib import import_module from pickle import PicklingError from urllib.parse import quote from asgiref.local import Local from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import _lazy_re_compile, normalize from django.utils.translation import get_language, get_supported_language_variant from .converters import get_converter from .exceptions import NoReverseMatch, Resolver404 from .utils import get_callable class ResolverMatch: def __init__( self, func, args, kwargs, url_name=None, app_names=None, namespaces=None, route=None, tried=None, captured_kwargs=None, extra_kwargs=None, ): self.func = func self.args = args self.kwargs = kwargs self.url_name = url_name self.route = route self.tried = tried self.captured_kwargs = captured_kwargs self.extra_kwargs = extra_kwargs # If a URLRegexResolver doesn't have a namespace or app_name, it passes # in an empty value. self.app_names = [x for x in app_names if x] if app_names else [] self.app_name = ":".join(self.app_names) self.namespaces = [x for x in namespaces if x] if namespaces else [] self.namespace = ":".join(self.namespaces) if hasattr(func, "view_class"): func = func.view_class if not hasattr(func, "__name__"): # A class-based view self._func_path = func.__class__.__module__ + "." + func.__class__.__name__ else: # A function-based view self._func_path = func.__module__ + "." + func.__name__ view_path = url_name or self._func_path self.view_name = ":".join(self.namespaces + [view_path]) def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): if isinstance(self.func, functools.partial): func = repr(self.func) else: func = self._func_path return ( "ResolverMatch(func=%s, args=%r, kwargs=%r, url_name=%r, " "app_names=%r, namespaces=%r, route=%r%s%s)" % ( func, self.args, self.kwargs, self.url_name, self.app_names, self.namespaces, self.route, f", captured_kwargs={self.captured_kwargs!r}" if self.captured_kwargs else "", f", extra_kwargs={self.extra_kwargs!r}" if self.extra_kwargs else "", ) ) def __reduce_ex__(self, protocol): raise PicklingError(f"Cannot pickle {self.__class__.__qualname__}.") def get_resolver(urlconf=None): if urlconf is None: urlconf = settings.ROOT_URLCONF return _get_cached_resolver(urlconf) @functools.cache def _get_cached_resolver(urlconf=None): return URLResolver(RegexPattern(r"^/"), urlconf) @functools.cache def get_ns_resolver(ns_pattern, resolver, converters): # Build a namespaced resolver for the given parent URLconf pattern. # This makes it possible to have captured parameters in the parent # URLconf pattern. pattern = RegexPattern(ns_pattern) pattern.converters = dict(converters) ns_resolver = URLResolver(pattern, resolver.url_patterns) return URLResolver(RegexPattern(r"^/"), [ns_resolver]) class LocaleRegexDescriptor: def __init__(self, attr): self.attr = attr def __get__(self, instance, cls=None): """ Return a compiled regular expression based on the active language. """ if instance is None: return self # As a performance optimization, if the given regex string is a regular # string (not a lazily-translated string proxy), compile it once and # avoid per-language compilation. pattern = getattr(instance, self.attr) if isinstance(pattern, str): instance.__dict__["regex"] = instance._compile(pattern) return instance.__dict__["regex"] language_code = get_language() if language_code not in instance._regex_dict: instance._regex_dict[language_code] = instance._compile(str(pattern)) return instance._regex_dict[language_code] class CheckURLMixin: def describe(self): """ Format the URL pattern for display in warning messages. """ description = "'{}'".format(self) if self.name: description += " [name='{}']".format(self.name) return description def _check_pattern_startswith_slash(self): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = self.regex.pattern if not settings.APPEND_SLASH: # Skip check as it can be useful to start a URL pattern with a slash # when APPEND_SLASH=False. return [] if regex_pattern.startswith(("/", "^/", "^\\/")) and not regex_pattern.endswith( "/" ): warning = Warning( "Your URL pattern {} has a route beginning with a '/'. Remove this " "slash as it is unnecessary. If this pattern is targeted in an " "include(), ensure the include() pattern has a trailing '/'.".format( self.describe() ), id="urls.W002", ) return [warning] else: return [] class RegexPattern(CheckURLMixin): regex = LocaleRegexDescriptor("_regex") def __init__(self, regex, name=None, is_endpoint=False): self._regex = regex self._regex_dict = {} self._is_endpoint = is_endpoint self.name = name self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith("$") else self.regex.search(path) ) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. kwargs = match.groupdict() args = () if kwargs else match.groups() kwargs = {k: v for k, v in kwargs.items() if v is not None} return path[match.end() :], args, kwargs return None def check(self): warnings = [] warnings.extend(self._check_pattern_startswith_slash()) if not self._is_endpoint: warnings.extend(self._check_include_trailing_dollar()) return warnings def _check_include_trailing_dollar(self): regex_pattern = self.regex.pattern if regex_pattern.endswith("$") and not regex_pattern.endswith(r"\$"): return [ Warning( "Your URL pattern {} uses include with a route ending with a '$'. " "Remove the dollar from the route to avoid problems including " "URLs.".format(self.describe()), id="urls.W001", ) ] else: return [] def _compile(self, regex): """Compile and return the given regular expression.""" try: return re.compile(regex) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, e) ) from e def __str__(self): return str(self._regex) _PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile( r"<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>" ) def _route_to_regex(route, is_endpoint=False): """ Convert a path pattern into a regular expression. Return the regular expression and a dictionary mapping the capture names to the converters. For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)' and {'pk': <django.urls.converters.IntConverter>}. """ original_route = route parts = ["^"] converters = {} while True: match = _PATH_PARAMETER_COMPONENT_RE.search(route) if not match: parts.append(re.escape(route)) break elif not set(match.group()).isdisjoint(string.whitespace): raise ImproperlyConfigured( "URL route '%s' cannot contain whitespace in angle brackets " "<…>." % original_route ) parts.append(re.escape(route[: match.start()])) route = route[match.end() :] parameter = match["parameter"] if not parameter.isidentifier(): raise ImproperlyConfigured( "URL route '%s' uses parameter name %r which isn't a valid " "Python identifier." % (original_route, parameter) ) raw_converter = match["converter"] if raw_converter is None: # If a converter isn't specified, the default is `str`. raw_converter = "str" try: converter = get_converter(raw_converter) except KeyError as e: raise ImproperlyConfigured( "URL route %r uses invalid converter %r." % (original_route, raw_converter) ) from e converters[parameter] = converter parts.append("(?P<" + parameter + ">" + converter.regex + ")") if is_endpoint: parts.append(r"\Z") return "".join(parts), converters class RoutePattern(CheckURLMixin): regex = LocaleRegexDescriptor("_route") def __init__(self, route, name=None, is_endpoint=False): self._route = route self._regex_dict = {} self._is_endpoint = is_endpoint self.name = name self.converters = _route_to_regex(str(route), is_endpoint)[1] def match(self, path): match = self.regex.search(path) if match: # RoutePattern doesn't allow non-named groups so args are ignored. kwargs = match.groupdict() for key, value in kwargs.items(): converter = self.converters[key] try: kwargs[key] = converter.to_python(value) except ValueError: return None return path[match.end() :], (), kwargs return None def check(self): warnings = self._check_pattern_startswith_slash() route = self._route if "(?P<" in route or route.startswith("^") or route.endswith("$"): warnings.append( Warning( "Your URL pattern {} has a route that contains '(?P<', begins " "with a '^', or ends with a '$'. This was likely an oversight " "when migrating to django.urls.path().".format(self.describe()), id="2_0.W001", ) ) return warnings def _compile(self, route): return re.compile(_route_to_regex(route, self._is_endpoint)[0]) def __str__(self): return str(self._route) class LocalePrefixPattern: def __init__(self, prefix_default_language=True): self.prefix_default_language = prefix_default_language self.converters = {} @property def regex(self): # This is only used by reverse() and cached in _reverse_dict. return re.compile(re.escape(self.language_prefix)) @property def language_prefix(self): language_code = get_language() or settings.LANGUAGE_CODE default_language = get_supported_language_variant(settings.LANGUAGE_CODE) if language_code == default_language and not self.prefix_default_language: return "" else: return "%s/" % language_code def match(self, path): language_prefix = self.language_prefix if path.startswith(language_prefix): return path.removeprefix(language_prefix), (), {} return None def check(self): return [] def describe(self): return "'{}'".format(self) def __str__(self): return self.language_prefix class URLPattern: def __init__(self, pattern, callback, default_args=None, name=None): self.pattern = pattern self.callback = callback # the view self.default_args = default_args or {} self.name = name def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.pattern.describe()) def check(self): warnings = self._check_pattern_name() warnings.extend(self.pattern.check()) warnings.extend(self._check_callback()) return warnings def _check_pattern_name(self): """ Check that the pattern name does not contain a colon. """ if self.pattern.name is not None and ":" in self.pattern.name: warning = Warning( "Your URL pattern {} has a name including a ':'. Remove the colon, to " "avoid ambiguous namespace references.".format(self.pattern.describe()), id="urls.W003", ) return [warning] else: return [] def _check_callback(self): from django.views import View view = self.callback if inspect.isclass(view) and issubclass(view, View): return [ Error( "Your URL pattern %s has an invalid view, pass %s.as_view() " "instead of %s." % ( self.pattern.describe(), view.__name__, view.__name__, ), id="urls.E009", ) ] return [] def resolve(self, path): match = self.pattern.match(path) if match: new_path, args, captured_kwargs = match # Pass any default args as **kwargs. kwargs = {**captured_kwargs, **self.default_args} return ResolverMatch( self.callback, args, kwargs, self.pattern.name, route=str(self.pattern), captured_kwargs=captured_kwargs, extra_kwargs=self.default_args, ) @cached_property def lookup_str(self): """ A string that identifies the view (e.g. 'path.to.view_function' or 'path.to.ClassBasedView'). """ callback = self.callback if isinstance(callback, functools.partial): callback = callback.func if hasattr(callback, "view_class"): callback = callback.view_class elif not hasattr(callback, "__name__"): return callback.__module__ + "." + callback.__class__.__name__ return callback.__module__ + "." + callback.__qualname__ class URLResolver: def __init__( self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None ): self.pattern = pattern # urlconf_name is the dotted Python path to the module defining # urlpatterns. It may also be an object with an urlpatterns attribute # or urlpatterns itself. self.urlconf_name = urlconf_name self.callback = None self.default_kwargs = default_kwargs or {} self.namespace = namespace self.app_name = app_name self._reverse_dict = {} self._namespace_dict = {} self._app_dict = {} # set of dotted paths to all functions and classes that are used in # urlpatterns self._callback_strs = set() self._populated = False self._local = Local() def __repr__(self): if isinstance(self.urlconf_name, list) and self.urlconf_name: # Don't bother to output the whole list, it can be huge urlconf_repr = "<%s list>" % self.urlconf_name[0].__class__.__name__ else: urlconf_repr = repr(self.urlconf_name) return "<%s %s (%s:%s) %s>" % ( self.__class__.__name__, urlconf_repr, self.app_name, self.namespace, self.pattern.describe(), ) def check(self): messages = [] for pattern in self.url_patterns: messages.extend(check_resolver(pattern)) messages.extend(self._check_custom_error_handlers()) return messages or self.pattern.check() def _check_custom_error_handlers(self): messages = [] # All handlers take (request, exception) arguments except handler500 # which takes (request). for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]: try: handler = self.resolve_error_handler(status_code) except (ImportError, ViewDoesNotExist) as e: path = getattr(self.urlconf_module, "handler%s" % status_code) msg = ( "The custom handler{status_code} view '{path}' could not be " "imported." ).format(status_code=status_code, path=path) messages.append(Error(msg, hint=str(e), id="urls.E008")) continue signature = inspect.signature(handler) args = [None] * num_parameters try: signature.bind(*args) except TypeError: msg = ( "The custom handler{status_code} view '{path}' does not " "take the correct number of arguments ({args})." ).format( status_code=status_code, path=handler.__module__ + "." + handler.__qualname__, args="request, exception" if num_parameters == 2 else "request", ) messages.append(Error(msg, id="urls.E007")) return messages def _populate(self): # Short-circuit if called recursively in this thread to prevent # infinite recursion. Concurrent threads may call this at the same # time and will need to continue, so set 'populating' on a # thread-local variable. if getattr(self._local, "populating", False): return try: self._local.populating = True lookups = MultiValueDict() namespaces = {} apps = {} language_code = get_language() for url_pattern in reversed(self.url_patterns): p_pattern = url_pattern.pattern.regex.pattern p_pattern = p_pattern.removeprefix("^") if isinstance(url_pattern, URLPattern): self._callback_strs.add(url_pattern.lookup_str) bits = normalize(url_pattern.pattern.regex.pattern) lookups.appendlist( url_pattern.callback, ( bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters, ), ) if url_pattern.name is not None: lookups.appendlist( url_pattern.name, ( bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters, ), ) else: # url_pattern is a URLResolver. url_pattern._populate() if url_pattern.app_name: apps.setdefault(url_pattern.app_name, []).append( url_pattern.namespace ) namespaces[url_pattern.namespace] = (p_pattern, url_pattern) else: for name in url_pattern.reverse_dict: for ( matches, pat, defaults, converters, ) in url_pattern.reverse_dict.getlist(name): new_matches = normalize(p_pattern + pat) lookups.appendlist( name, ( new_matches, p_pattern + pat, {**defaults, **url_pattern.default_kwargs}, { **self.pattern.converters, **url_pattern.pattern.converters, **converters, }, ), ) for namespace, ( prefix, sub_pattern, ) in url_pattern.namespace_dict.items(): current_converters = url_pattern.pattern.converters sub_pattern.pattern.converters.update(current_converters) namespaces[namespace] = (p_pattern + prefix, sub_pattern) for app_name, namespace_list in url_pattern.app_dict.items(): apps.setdefault(app_name, []).extend(namespace_list) self._callback_strs.update(url_pattern._callback_strs) self._namespace_dict[language_code] = namespaces self._app_dict[language_code] = apps self._reverse_dict[language_code] = lookups self._populated = True finally: self._local.populating = False @property def reverse_dict(self): language_code = get_language() if language_code not in self._reverse_dict: self._populate() return self._reverse_dict[language_code] @property def namespace_dict(self): language_code = get_language() if language_code not in self._namespace_dict: self._populate() return self._namespace_dict[language_code] @property def app_dict(self): language_code = get_language() if language_code not in self._app_dict: self._populate() return self._app_dict[language_code] @staticmethod def _extend_tried(tried, pattern, sub_tried=None): if sub_tried is None: tried.append([pattern]) else: tried.extend([pattern, *t] for t in sub_tried) @staticmethod def _join_route(route1, route2): """Join two routes, without the starting ^ in the second route.""" if not route1: return route2 route2 = route2.removeprefix("^") return route1 + route2 def _is_callback(self, name): if not self._populated: self._populate() return name in self._callback_strs def resolve(self, path): path = str(path) # path may be a reverse_lazy object tried = [] match = self.pattern.match(path) if match: new_path, args, kwargs = match for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: self._extend_tried(tried, pattern, e.args[0].get("tried")) else: if sub_match: # Merge captured arguments in match with submatch sub_match_dict = {**kwargs, **self.default_kwargs} # Update the sub_match_dict with the kwargs from the sub_match. sub_match_dict.update(sub_match.kwargs) # If there are *any* named groups, ignore all non-named groups. # Otherwise, pass all non-named arguments as positional # arguments. sub_match_args = sub_match.args if not sub_match_dict: sub_match_args = args + sub_match.args current_route = ( "" if isinstance(pattern, URLPattern) else str(pattern.pattern) ) self._extend_tried(tried, pattern, sub_match.tried) return ResolverMatch( sub_match.func, sub_match_args, sub_match_dict, sub_match.url_name, [self.app_name] + sub_match.app_names, [self.namespace] + sub_match.namespaces, self._join_route(current_route, sub_match.route), tried, captured_kwargs=sub_match.captured_kwargs, extra_kwargs={ **self.default_kwargs, **sub_match.extra_kwargs, }, ) tried.append([pattern]) raise Resolver404({"tried": tried, "path": new_path}) raise Resolver404({"path": path}) @cached_property def urlconf_module(self): if isinstance(self.urlconf_name, str): return import_module(self.urlconf_name) else: return self.urlconf_name @cached_property def url_patterns(self): # urlconf_module might be a valid set of patterns, so we default to it patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except TypeError as e: msg = ( "The included URLconf '{name}' does not appear to have " "any patterns in it. If you see the 'urlpatterns' variable " "with valid patterns in the file then the issue is probably " "caused by a circular import." ) raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e return patterns def resolve_error_handler(self, view_type): callback = getattr(self.urlconf_module, "handler%s" % view_type, None) if not callback: # No handler specified in file; use lazy import, since # django.conf.urls imports this file. from django.conf import urls callback = getattr(urls, "handler%s" % view_type) return get_callable(callback) def reverse(self, lookup_view, *args, **kwargs): return self._reverse_with_prefix(lookup_view, "", *args, **kwargs) def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") if not self._populated: self._populate() possibilities = self.reverse_dict.getlist(lookup_view) for possibility, pattern, defaults, converters in possibilities: for result, params in possibility: if args: if len(args) != len(params): continue candidate_subs = dict(zip(params, args)) else: if set(kwargs).symmetric_difference(params).difference(defaults): continue matches = True for k, v in defaults.items(): if k in params: continue if kwargs.get(k, v) != v: matches = False break if not matches: continue candidate_subs = kwargs # Convert the candidate subs to text using Converter.to_url(). text_candidate_subs = {} match = True for k, v in candidate_subs.items(): if k in converters: try: text_candidate_subs[k] = converters[k].to_url(v) except ValueError: match = False break else: text_candidate_subs[k] = str(v) if not match: continue # WSGI provides decoded URLs, without %xx escapes, and the URL # resolver operates on such URLs. First substitute arguments # without quoting to build a decoded URL and look for a match. # Then, if we have a match, redo the substitution with quoted # arguments in order to return a properly encoded URL. candidate_pat = _prefix.replace("%", "%%") + result if re.search( "^%s%s" % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs, ): # safe characters from `pchar` definition of RFC 3986 url = quote( candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + "/~:@", ) # Don't allow construction of scheme relative urls. return escape_leading_slashes(url) # lookup_view can be URL name or callable, but callables are not # friendly in error messages. m = getattr(lookup_view, "__module__", None) n = getattr(lookup_view, "__name__", None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view patterns = [pattern for (_, pattern, _, _) in possibilities] if patterns: if args: arg_msg = "arguments '%s'" % (args,) elif kwargs: arg_msg = "keyword arguments '%s'" % kwargs else: arg_msg = "no arguments" msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % ( lookup_view_s, arg_msg, len(patterns), patterns, ) else: msg = ( "Reverse for '%(view)s' not found. '%(view)s' is not " "a valid view function or pattern name." % {"view": lookup_view_s} ) raise NoReverseMatch(msg)
0625c580bb543f760887b70018a05543d023036df03f61c2e7315942f5803855
""" Internationalization support. """ from contextlib import ContextDecorator from decimal import ROUND_UP, Decimal from django.utils.autoreload import autoreload_started, file_changed from django.utils.functional import lazy from django.utils.regex_helper import _lazy_re_compile __all__ = [ "activate", "deactivate", "override", "deactivate_all", "get_language", "get_language_from_request", "get_language_info", "get_language_bidi", "get_supported_language_variant", "check_for_language", "to_language", "to_locale", "templatize", "gettext", "gettext_lazy", "gettext_noop", "ngettext", "ngettext_lazy", "pgettext", "pgettext_lazy", "npgettext", "npgettext_lazy", ] class TranslatorCommentWarning(SyntaxWarning): pass # Here be dragons, so a short explanation of the logic won't hurt: # We are trying to solve two problems: (1) access settings, in particular # settings.USE_I18N, as late as possible, so that modules can be imported # without having to first configure Django, and (2) if some other code creates # a reference to one of these functions, don't break that reference when we # replace the functions with their real counterparts (once we do access the # settings). class Trans: """ The purpose of this class is to store the actual translation function upon receiving the first call to that function. After this is done, changes to USE_I18N will have no effect to which function is served upon request. If your tests rely on changing USE_I18N, you can delete all the functions from _trans.__dict__. Note that storing the function with setattr will have a noticeable performance effect, as access to the function goes the normal path, instead of using __getattr__. """ def __getattr__(self, real_name): from django.conf import settings if settings.USE_I18N: from django.utils.translation import trans_real as trans from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) autoreload_started.connect( watch_for_translation_changes, dispatch_uid="translation_file_changed" ) file_changed.connect( translation_file_changed, dispatch_uid="translation_file_changed" ) else: from django.utils.translation import trans_null as trans setattr(self, real_name, getattr(trans, real_name)) return getattr(trans, real_name) _trans = Trans() # The Trans class is no more needed, so remove it from the namespace. del Trans def gettext_noop(message): return _trans.gettext_noop(message) def gettext(message): return _trans.gettext(message) def ngettext(singular, plural, number): return _trans.ngettext(singular, plural, number) def pgettext(context, message): return _trans.pgettext(context, message) def npgettext(context, singular, plural, number): return _trans.npgettext(context, singular, plural, number) gettext_lazy = lazy(gettext, str) pgettext_lazy = lazy(pgettext, str) def lazy_number(func, resultclass, number=None, **kwargs): if isinstance(number, int): kwargs["number"] = number proxy = lazy(func, resultclass)(**kwargs) else: original_kwargs = kwargs.copy() class NumberAwareString(resultclass): def __bool__(self): return bool(kwargs["singular"]) def _get_number_value(self, values): try: return values[number] except KeyError: raise KeyError( "Your dictionary lacks key '%s'. Please provide " "it, because it is required to determine whether " "string is singular or plural." % number ) def _translate(self, number_value): kwargs["number"] = number_value return func(**kwargs) def format(self, *args, **kwargs): number_value = ( self._get_number_value(kwargs) if kwargs and number else args[0] ) return self._translate(number_value).format(*args, **kwargs) def __mod__(self, rhs): if isinstance(rhs, dict) and number: number_value = self._get_number_value(rhs) else: number_value = rhs translated = self._translate(number_value) try: translated %= rhs except TypeError: # String doesn't contain a placeholder for the number. pass return translated proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) proxy.__reduce__ = lambda: ( _lazy_number_unpickle, (func, resultclass, number, original_kwargs), ) return proxy def _lazy_number_unpickle(func, resultclass, number, kwargs): return lazy_number(func, resultclass, number=number, **kwargs) def ngettext_lazy(singular, plural, number=None): return lazy_number(ngettext, str, singular=singular, plural=plural, number=number) def npgettext_lazy(context, singular, plural, number=None): return lazy_number( npgettext, str, context=context, singular=singular, plural=plural, number=number ) def activate(language): return _trans.activate(language) def deactivate(): return _trans.deactivate() class override(ContextDecorator): def __init__(self, language, deactivate=False): self.language = language self.deactivate = deactivate def __enter__(self): self.old_language = get_language() if self.language is not None: activate(self.language) else: deactivate_all() def __exit__(self, exc_type, exc_value, traceback): if self.old_language is None: deactivate_all() elif self.deactivate: deactivate() else: activate(self.old_language) def get_language(): return _trans.get_language() def get_language_bidi(): return _trans.get_language_bidi() def check_for_language(lang_code): return _trans.check_for_language(lang_code) def to_language(locale): """Turn a locale name (en_US) into a language name (en-us).""" p = locale.find("_") if p >= 0: return locale[:p].lower() + "-" + locale[p + 1 :].lower() else: return locale.lower() def to_locale(language): """Turn a language name (en-us) into a locale name (en_US).""" lang, _, country = language.lower().partition("-") if not country: return language[:3].lower() + language[3:] # A language with > 2 characters after the dash only has its first # character after the dash capitalized; e.g. sr-latn becomes sr_Latn. # A language with 2 characters after the dash has both characters # capitalized; e.g. en-us becomes en_US. country, _, tail = country.partition("-") country = country.title() if len(country) > 2 else country.upper() if tail: country += "-" + tail return lang + "_" + country def get_language_from_request(request, check_path=False): return _trans.get_language_from_request(request, check_path) def get_language_from_path(path): return _trans.get_language_from_path(path) def get_supported_language_variant(lang_code, *, strict=False): return _trans.get_supported_language_variant(lang_code, strict) def templatize(src, **kwargs): from .template import templatize return templatize(src, **kwargs) def deactivate_all(): return _trans.deactivate_all() def get_language_info(lang_code): from django.conf.locale import LANG_INFO try: lang_info = LANG_INFO[lang_code] if "fallback" in lang_info and "name" not in lang_info: info = get_language_info(lang_info["fallback"][0]) else: info = lang_info except KeyError: if "-" not in lang_code: raise KeyError("Unknown language code %s." % lang_code) generic_lang_code = lang_code.split("-")[0] try: info = LANG_INFO[generic_lang_code] except KeyError: raise KeyError( "Unknown language code %s and %s." % (lang_code, generic_lang_code) ) if info: info["name_translated"] = gettext_lazy(info["name"]) return info trim_whitespace_re = _lazy_re_compile(r"\s*\n\s*") def trim_whitespace(s): return trim_whitespace_re.sub(" ", s.strip()) def round_away_from_one(value): return int(Decimal(value - 1).quantize(Decimal("0"), rounding=ROUND_UP)) + 1
c9be9a16481fe371f3ef7f29ec0330671e94ff93dc287ceae443b78e6b1053d9
import collections from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Combinable from django.forms.models import BaseModelForm, BaseModelFormSet, _get_foreign_key from django.template import engines from django.template.backends.django import DjangoTemplates from django.utils.module_loading import import_string def _issubclass(cls, classinfo): """ issubclass() variant that doesn't raise an exception if cls isn't a class. """ try: return issubclass(cls, classinfo) except TypeError: return False def _contains_subclass(class_path, candidate_paths): """ Return whether or not a dotted class path (or a subclass of that class) is found in a list of candidate paths. """ cls = import_string(class_path) for path in candidate_paths: try: candidate_cls = import_string(path) except ImportError: # ImportErrors are raised elsewhere. continue if _issubclass(candidate_cls, cls): return True return False def check_admin_app(app_configs, **kwargs): from django.contrib.admin.sites import all_sites errors = [] for site in all_sites: errors.extend(site.check(app_configs)) return errors def check_dependencies(**kwargs): """ Check that the admin's dependencies are correctly installed. """ from django.contrib.admin.sites import all_sites if not apps.is_installed("django.contrib.admin"): return [] errors = [] app_dependencies = ( ("django.contrib.contenttypes", 401), ("django.contrib.auth", 405), ("django.contrib.messages", 406), ) for app_name, error_code in app_dependencies: if not apps.is_installed(app_name): errors.append( checks.Error( "'%s' must be in INSTALLED_APPS in order to use the admin " "application." % app_name, id="admin.E%d" % error_code, ) ) for engine in engines.all(): if isinstance(engine, DjangoTemplates): django_templates_instance = engine.engine break else: django_templates_instance = None if not django_templates_instance: errors.append( checks.Error( "A 'django.template.backends.django.DjangoTemplates' instance " "must be configured in TEMPLATES in order to use the admin " "application.", id="admin.E403", ) ) else: if ( "django.contrib.auth.context_processors.auth" not in django_templates_instance.context_processors and _contains_subclass( "django.contrib.auth.backends.ModelBackend", settings.AUTHENTICATION_BACKENDS, ) ): errors.append( checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id="admin.E402", ) ) if ( "django.contrib.messages.context_processors.messages" not in django_templates_instance.context_processors ): errors.append( checks.Error( "'django.contrib.messages.context_processors.messages' must " "be enabled in DjangoTemplates (TEMPLATES) in order to use " "the admin application.", id="admin.E404", ) ) sidebar_enabled = any(site.enable_nav_sidebar for site in all_sites) if ( sidebar_enabled and "django.template.context_processors.request" not in django_templates_instance.context_processors ): errors.append( checks.Warning( "'django.template.context_processors.request' must be enabled " "in DjangoTemplates (TEMPLATES) in order to use the admin " "navigation sidebar.", id="admin.W411", ) ) if not _contains_subclass( "django.contrib.auth.middleware.AuthenticationMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.auth.middleware.AuthenticationMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", id="admin.E408", ) ) if not _contains_subclass( "django.contrib.messages.middleware.MessageMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.messages.middleware.MessageMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", id="admin.E409", ) ) if not _contains_subclass( "django.contrib.sessions.middleware.SessionMiddleware", settings.MIDDLEWARE ): errors.append( checks.Error( "'django.contrib.sessions.middleware.SessionMiddleware' must " "be in MIDDLEWARE in order to use the admin application.", hint=( "Insert " "'django.contrib.sessions.middleware.SessionMiddleware' " "before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ), id="admin.E410", ) ) return errors class BaseModelAdminChecks: def check(self, admin_obj, **kwargs): return [ *self._check_autocomplete_fields(admin_obj), *self._check_raw_id_fields(admin_obj), *self._check_fields(admin_obj), *self._check_fieldsets(admin_obj), *self._check_exclude(admin_obj), *self._check_form(admin_obj), *self._check_filter_vertical(admin_obj), *self._check_filter_horizontal(admin_obj), *self._check_radio_fields(admin_obj), *self._check_prepopulated_fields(admin_obj), *self._check_view_on_site_url(admin_obj), *self._check_ordering(admin_obj), *self._check_readonly_fields(admin_obj), ] def _check_autocomplete_fields(self, obj): """ Check that `autocomplete_fields` is a list or tuple of model fields. """ if not isinstance(obj.autocomplete_fields, (list, tuple)): return must_be( "a list or tuple", option="autocomplete_fields", obj=obj, id="admin.E036", ) else: return list( chain.from_iterable( [ self._check_autocomplete_fields_item( obj, field_name, "autocomplete_fields[%d]" % index ) for index, field_name in enumerate(obj.autocomplete_fields) ] ) ) def _check_autocomplete_fields_item(self, obj, field_name, label): """ Check that an item in `autocomplete_fields` is a ForeignKey or a ManyToManyField and that the item has a related ModelAdmin with search_fields defined. """ try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E037" ) else: if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be( "a foreign key or a many-to-many field", option=label, obj=obj, id="admin.E038", ) related_admin = obj.admin_site._registry.get(field.remote_field.model) if related_admin is None: return [ checks.Error( 'An admin for model "%s" has to be registered ' "to be referenced by %s.autocomplete_fields." % ( field.remote_field.model.__name__, type(obj).__name__, ), obj=obj.__class__, id="admin.E039", ) ] elif not related_admin.search_fields: return [ checks.Error( '%s must define "search_fields", because it\'s ' "referenced by %s.autocomplete_fields." % ( related_admin.__class__.__name__, type(obj).__name__, ), obj=obj.__class__, id="admin.E040", ) ] return [] def _check_raw_id_fields(self, obj): """Check that `raw_id_fields` only contains field names that are listed on the model.""" if not isinstance(obj.raw_id_fields, (list, tuple)): return must_be( "a list or tuple", option="raw_id_fields", obj=obj, id="admin.E001" ) else: return list( chain.from_iterable( self._check_raw_id_fields_item( obj, field_name, "raw_id_fields[%d]" % index ) for index, field_name in enumerate(obj.raw_id_fields) ) ) def _check_raw_id_fields_item(self, obj, field_name, label): """Check an item of `raw_id_fields`, i.e. check that field named `field_name` exists in model `model` and is a ForeignKey or a ManyToManyField.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E002" ) else: # Using attname is not supported. if field.name != field_name: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E002", ) if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be( "a foreign key or a many-to-many field", option=label, obj=obj, id="admin.E003", ) else: return [] def _check_fields(self, obj): """Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if obj.fields is None: return [] elif not isinstance(obj.fields, (list, tuple)): return must_be("a list or tuple", option="fields", obj=obj, id="admin.E004") elif obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", obj=obj.__class__, id="admin.E005", ) ] fields = flatten(obj.fields) if len(fields) != len(set(fields)): return [ checks.Error( "The value of 'fields' contains duplicate field(s).", obj=obj.__class__, id="admin.E006", ) ] return list( chain.from_iterable( self._check_field_spec(obj, field_name, "fields") for field_name in obj.fields ) ) def _check_fieldsets(self, obj): """Check that fieldsets is properly formatted and doesn't contain duplicates.""" if obj.fieldsets is None: return [] elif not isinstance(obj.fieldsets, (list, tuple)): return must_be( "a list or tuple", option="fieldsets", obj=obj, id="admin.E007" ) else: seen_fields = [] return list( chain.from_iterable( self._check_fieldsets_item( obj, fieldset, "fieldsets[%d]" % index, seen_fields ) for index, fieldset in enumerate(obj.fieldsets) ) ) def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): """Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key.""" if not isinstance(fieldset, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E008") elif len(fieldset) != 2: return must_be("of length 2", option=label, obj=obj, id="admin.E009") elif not isinstance(fieldset[1], dict): return must_be( "a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010" ) elif "fields" not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id="admin.E011", ) ] elif not isinstance(fieldset[1]["fields"], (list, tuple)): return must_be( "a list or tuple", option="%s[1]['fields']" % label, obj=obj, id="admin.E008", ) seen_fields.extend(flatten(fieldset[1]["fields"])) if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id="admin.E012", ) ] return list( chain.from_iterable( self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]["fields"] ) ) def _check_field_spec(self, obj, fields, label): """`fields` should be an item of `fields` or an item of fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a field name or a tuple of field names.""" if isinstance(fields, tuple): return list( chain.from_iterable( self._check_field_spec_item( obj, field_name, "%s[%d]" % (label, index) ) for index, field_name in enumerate(fields) ) ) else: return self._check_field_spec_item(obj, fields, label) def _check_field_spec_item(self, obj, field_name, label): if field_name in obj.readonly_fields: # Stuff can be put in fields that isn't actually a model field if # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] else: try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: # If we can't find a field on the model that matches, it could # be an extra field on the form. return [] else: if ( isinstance(field, models.ManyToManyField) and not field.remote_field.through._meta.auto_created ): return [ checks.Error( "The value of '%s' cannot include the ManyToManyField " "'%s', because that field manually specifies a " "relationship model." % (label, field_name), obj=obj.__class__, id="admin.E013", ) ] else: return [] def _check_exclude(self, obj): """Check that exclude is a sequence without duplicates.""" if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be( "a list or tuple", option="exclude", obj=obj, id="admin.E014" ) elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=obj.__class__, id="admin.E015", ) ] else: return [] def _check_form(self, obj): """Check that form subclasses BaseModelForm.""" if not _issubclass(obj.form, BaseModelForm): return must_inherit_from( parent="BaseModelForm", option="form", obj=obj, id="admin.E016" ) else: return [] def _check_filter_vertical(self, obj): """Check that filter_vertical is a sequence of field names.""" if not isinstance(obj.filter_vertical, (list, tuple)): return must_be( "a list or tuple", option="filter_vertical", obj=obj, id="admin.E017" ) else: return list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_vertical[%d]" % index ) for index, field_name in enumerate(obj.filter_vertical) ) ) def _check_filter_horizontal(self, obj): """Check that filter_horizontal is a sequence of field names.""" if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be( "a list or tuple", option="filter_horizontal", obj=obj, id="admin.E018" ) else: return list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_horizontal[%d]" % index ) for index, field_name in enumerate(obj.filter_horizontal) ) ) def _check_filter_item(self, obj, field_name, label): """Check one item of `filter_vertical` or `filter_horizontal`, i.e. check that given field exists and is a ManyToManyField.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E019" ) else: if not field.many_to_many: return must_be( "a many-to-many field", option=label, obj=obj, id="admin.E020" ) else: return [] def _check_radio_fields(self, obj): """Check that `radio_fields` is a dictionary.""" if not isinstance(obj.radio_fields, dict): return must_be( "a dictionary", option="radio_fields", obj=obj, id="admin.E021" ) else: return list( chain.from_iterable( self._check_radio_fields_key(obj, field_name, "radio_fields") + self._check_radio_fields_value( obj, val, 'radio_fields["%s"]' % field_name ) for field_name, val in obj.radio_fields.items() ) ) def _check_radio_fields_key(self, obj, field_name, label): """Check that a key of `radio_fields` dictionary is name of existing field and that the field is a ForeignKey or has `choices` defined.""" try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E022" ) else: if not (isinstance(field, models.ForeignKey) or field.choices): return [ checks.Error( "The value of '%s' refers to '%s', which is not an " "instance of ForeignKey, and does not have a 'choices' " "definition." % (label, field_name), obj=obj.__class__, id="admin.E023", ) ] else: return [] def _check_radio_fields_value(self, obj, val, label): """Check type of a value of `radio_fields` dictionary.""" from django.contrib.admin.options import HORIZONTAL, VERTICAL if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( "The value of '%s' must be either admin.HORIZONTAL or " "admin.VERTICAL." % label, obj=obj.__class__, id="admin.E024", ) ] else: return [] def _check_view_on_site_url(self, obj): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): return [ checks.Error( "The value of 'view_on_site' must be a callable or a boolean " "value.", obj=obj.__class__, id="admin.E025", ) ] else: return [] def _check_prepopulated_fields(self, obj): """Check that `prepopulated_fields` is a dictionary containing allowed field types.""" if not isinstance(obj.prepopulated_fields, dict): return must_be( "a dictionary", option="prepopulated_fields", obj=obj, id="admin.E026" ) else: return list( chain.from_iterable( self._check_prepopulated_fields_key( obj, field_name, "prepopulated_fields" ) + self._check_prepopulated_fields_value( obj, val, 'prepopulated_fields["%s"]' % field_name ) for field_name, val in obj.prepopulated_fields.items() ) ) def _check_prepopulated_fields_key(self, obj, field_name, label): """Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E027" ) else: if isinstance( field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField) ): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a " "DateTimeField, a ForeignKey, a OneToOneField, or a " "ManyToManyField." % (label, field_name), obj=obj.__class__, id="admin.E028", ) ] else: return [] def _check_prepopulated_fields_value(self, obj, val, label): """Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields.""" if not isinstance(val, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E029") else: return list( chain.from_iterable( self._check_prepopulated_fields_value_item( obj, subfield_name, "%s[%r]" % (label, index) ) for index, subfield_name in enumerate(val) ) ) def _check_prepopulated_fields_value_item(self, obj, field_name, label): """For `prepopulated_fields` equal to {"slug": ("title",)}, `field_name` is "title".""" try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E030" ) else: return [] def _check_ordering(self, obj): """Check that ordering refers to existing fields or is random.""" # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.ordering, (list, tuple)): return must_be( "a list or tuple", option="ordering", obj=obj, id="admin.E031" ) else: return list( chain.from_iterable( self._check_ordering_item(obj, field_name, "ordering[%d]" % index) for index, field_name in enumerate(obj.ordering) ) ) def _check_ordering_item(self, obj, field_name, label): """Check that `ordering` refers to existing fields.""" if isinstance(field_name, (Combinable, models.OrderBy)): if not isinstance(field_name, models.OrderBy): field_name = field_name.asc() if isinstance(field_name.expression, models.F): field_name = field_name.expression.name else: return [] if field_name == "?" and len(obj.ordering) != 1: return [ checks.Error( "The value of 'ordering' has the random ordering marker '?', " "but contains other fields as well.", hint='Either remove the "?", or remove the other fields.', obj=obj.__class__, id="admin.E032", ) ] elif field_name == "?": return [] elif LOOKUP_SEP in field_name: # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). return [] else: field_name = field_name.removeprefix("-") if field_name == "pk": return [] try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E033" ) else: return [] def _check_readonly_fields(self, obj): """Check that readonly_fields refers to proper attribute or field.""" if obj.readonly_fields == (): return [] elif not isinstance(obj.readonly_fields, (list, tuple)): return must_be( "a list or tuple", option="readonly_fields", obj=obj, id="admin.E034" ) else: return list( chain.from_iterable( self._check_readonly_fields_item( obj, field_name, "readonly_fields[%d]" % index ) for index, field_name in enumerate(obj.readonly_fields) ) ) def _check_readonly_fields_item(self, obj, field_name, label): if callable(field_name): return [] elif hasattr(obj, field_name): return [] elif hasattr(obj.model, field_name): return [] else: try: obj.model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "The value of '%s' is not a callable, an attribute of " "'%s', or an attribute of '%s'." % ( label, obj.__class__.__name__, obj.model._meta.label, ), obj=obj.__class__, id="admin.E035", ) ] else: return [] class ModelAdminChecks(BaseModelAdminChecks): def check(self, admin_obj, **kwargs): return [ *super().check(admin_obj), *self._check_save_as(admin_obj), *self._check_save_on_top(admin_obj), *self._check_inlines(admin_obj), *self._check_list_display(admin_obj), *self._check_list_display_links(admin_obj), *self._check_list_filter(admin_obj), *self._check_list_select_related(admin_obj), *self._check_list_per_page(admin_obj), *self._check_list_max_show_all(admin_obj), *self._check_list_editable(admin_obj), *self._check_search_fields(admin_obj), *self._check_date_hierarchy(admin_obj), *self._check_action_permission_methods(admin_obj), *self._check_actions_uniqueness(admin_obj), ] def _check_save_as(self, obj): """Check save_as is a boolean.""" if not isinstance(obj.save_as, bool): return must_be("a boolean", option="save_as", obj=obj, id="admin.E101") else: return [] def _check_save_on_top(self, obj): """Check save_on_top is a boolean.""" if not isinstance(obj.save_on_top, bool): return must_be("a boolean", option="save_on_top", obj=obj, id="admin.E102") else: return [] def _check_inlines(self, obj): """Check all inline model admin classes.""" if not isinstance(obj.inlines, (list, tuple)): return must_be( "a list or tuple", option="inlines", obj=obj, id="admin.E103" ) else: return list( chain.from_iterable( self._check_inlines_item(obj, item, "inlines[%d]" % index) for index, item in enumerate(obj.inlines) ) ) def _check_inlines_item(self, obj, inline, label): """Check one inline model admin.""" try: inline_label = inline.__module__ + "." + inline.__name__ except AttributeError: return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % obj, obj=obj.__class__, id="admin.E104", ) ] from django.contrib.admin.options import InlineModelAdmin if not _issubclass(inline, InlineModelAdmin): return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % inline_label, obj=obj.__class__, id="admin.E104", ) ] elif not inline.model: return [ checks.Error( "'%s' must have a 'model' attribute." % inline_label, obj=obj.__class__, id="admin.E105", ) ] elif not _issubclass(inline.model, models.Model): return must_be( "a Model", option="%s.model" % inline_label, obj=obj, id="admin.E106" ) else: return inline(obj.model, obj.admin_site).check() def _check_list_display(self, obj): """Check that list_display only contains fields or usable attributes.""" if not isinstance(obj.list_display, (list, tuple)): return must_be( "a list or tuple", option="list_display", obj=obj, id="admin.E107" ) else: return list( chain.from_iterable( self._check_list_display_item(obj, item, "list_display[%d]" % index) for index, item in enumerate(obj.list_display) ) ) def _check_list_display_item(self, obj, item, label): if callable(item): return [] elif hasattr(obj, item): return [] try: field = obj.model._meta.get_field(item) except FieldDoesNotExist: try: field = getattr(obj.model, item) except AttributeError: return [ checks.Error( "The value of '%s' refers to '%s', which is not a " "callable, an attribute of '%s', or an attribute or " "method on '%s'." % ( label, item, obj.__class__.__name__, obj.model._meta.label, ), obj=obj.__class__, id="admin.E108", ) ] if isinstance(field, models.ManyToManyField) or ( getattr(field, "rel", None) and field.rel.field.many_to_one ): return [ checks.Error( f"The value of '{label}' must not be a many-to-many field or a " f"reverse foreign key.", obj=obj.__class__, id="admin.E109", ) ] return [] def _check_list_display_links(self, obj): """Check that list_display_links is a unique subset of list_display.""" from django.contrib.admin.options import ModelAdmin if obj.list_display_links is None: return [] elif not isinstance(obj.list_display_links, (list, tuple)): return must_be( "a list, a tuple, or None", option="list_display_links", obj=obj, id="admin.E110", ) # Check only if ModelAdmin.get_list_display() isn't overridden. elif obj.get_list_display.__func__ is ModelAdmin.get_list_display: return list( chain.from_iterable( self._check_list_display_links_item( obj, field_name, "list_display_links[%d]" % index ) for index, field_name in enumerate(obj.list_display_links) ) ) return [] def _check_list_display_links_item(self, obj, field_name, label): if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not defined in " "'list_display'." % (label, field_name), obj=obj.__class__, id="admin.E111", ) ] else: return [] def _check_list_filter(self, obj): if not isinstance(obj.list_filter, (list, tuple)): return must_be( "a list or tuple", option="list_filter", obj=obj, id="admin.E112" ) else: return list( chain.from_iterable( self._check_list_filter_item(obj, item, "list_filter[%d]" % index) for index, item in enumerate(obj.list_filter) ) ) def _check_list_filter_item(self, obj, item, label): """ Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ from django.contrib.admin import FieldListFilter, ListFilter if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not _issubclass(item, ListFilter): return must_inherit_from( parent="ListFilter", option=label, obj=obj, id="admin.E113" ) # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, obj=obj.__class__, id="admin.E114", ) ] else: return [] elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not _issubclass(list_filter_class, FieldListFilter): return must_inherit_from( parent="FieldListFilter", option="%s[1]" % label, obj=obj, id="admin.E115", ) else: return [] else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(obj.model, field) except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of '%s' refers to '%s', which does not refer to a " "Field." % (label, field), obj=obj.__class__, id="admin.E116", ) ] else: return [] def _check_list_select_related(self, obj): """Check that list_select_related is a boolean, a list or a tuple.""" if not isinstance(obj.list_select_related, (bool, list, tuple)): return must_be( "a boolean, tuple or list", option="list_select_related", obj=obj, id="admin.E117", ) else: return [] def _check_list_per_page(self, obj): """Check that list_per_page is an integer.""" if not isinstance(obj.list_per_page, int): return must_be( "an integer", option="list_per_page", obj=obj, id="admin.E118" ) else: return [] def _check_list_max_show_all(self, obj): """Check that list_max_show_all is an integer.""" if not isinstance(obj.list_max_show_all, int): return must_be( "an integer", option="list_max_show_all", obj=obj, id="admin.E119" ) else: return [] def _check_list_editable(self, obj): """Check that list_editable is a sequence of editable fields from list_display without first element.""" if not isinstance(obj.list_editable, (list, tuple)): return must_be( "a list or tuple", option="list_editable", obj=obj, id="admin.E120" ) else: return list( chain.from_iterable( self._check_list_editable_item( obj, item, "list_editable[%d]" % index ) for index, item in enumerate(obj.list_editable) ) ) def _check_list_editable_item(self, obj, field_name, label): try: field = obj.model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field( field=field_name, option=label, obj=obj, id="admin.E121" ) else: if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not " "contained in 'list_display'." % (label, field_name), obj=obj.__class__, id="admin.E122", ) ] elif obj.list_display_links and field_name in obj.list_display_links: return [ checks.Error( "The value of '%s' cannot be in both 'list_editable' and " "'list_display_links'." % field_name, obj=obj.__class__, id="admin.E123", ) ] # If list_display[0] is in list_editable, check that # list_display_links is set. See #22792 and #26229 for use cases. elif ( obj.list_display[0] == field_name and not obj.list_display_links and obj.list_display_links is not None ): return [ checks.Error( "The value of '%s' refers to the first field in 'list_display' " "('%s'), which cannot be used unless 'list_display_links' is " "set." % (label, obj.list_display[0]), obj=obj.__class__, id="admin.E124", ) ] elif not field.editable or field.primary_key: return [ checks.Error( "The value of '%s' refers to '%s', which is not editable " "through the admin." % (label, field_name), obj=obj.__class__, id="admin.E125", ) ] else: return [] def _check_search_fields(self, obj): """Check search_fields is a sequence.""" if not isinstance(obj.search_fields, (list, tuple)): return must_be( "a list or tuple", option="search_fields", obj=obj, id="admin.E126" ) else: return [] def _check_date_hierarchy(self, obj): """Check that date_hierarchy refers to DateField or DateTimeField.""" if obj.date_hierarchy is None: return [] else: try: field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of 'date_hierarchy' refers to '%s', which " "does not refer to a Field." % obj.date_hierarchy, obj=obj.__class__, id="admin.E127", ) ] else: if not isinstance(field, (models.DateField, models.DateTimeField)): return must_be( "a DateField or DateTimeField", option="date_hierarchy", obj=obj, id="admin.E128", ) else: return [] def _check_action_permission_methods(self, obj): """ Actions with an allowed_permission attribute require the ModelAdmin to implement a has_<perm>_permission() method for each permission. """ actions = obj._get_base_actions() errors = [] for func, name, _ in actions: if not hasattr(func, "allowed_permissions"): continue for permission in func.allowed_permissions: method_name = "has_%s_permission" % permission if not hasattr(obj, method_name): errors.append( checks.Error( "%s must define a %s() method for the %s action." % ( obj.__class__.__name__, method_name, func.__name__, ), obj=obj.__class__, id="admin.E129", ) ) return errors def _check_actions_uniqueness(self, obj): """Check that every action has a unique __name__.""" errors = [] names = collections.Counter(name for _, name, _ in obj._get_base_actions()) for name, count in names.items(): if count > 1: errors.append( checks.Error( "__name__ attributes of actions defined in %s must be " "unique. Name %r is not unique." % ( obj.__class__.__name__, name, ), obj=obj.__class__, id="admin.E130", ) ) return errors class InlineModelAdminChecks(BaseModelAdminChecks): def check(self, inline_obj, **kwargs): parent_model = inline_obj.parent_model return [ *super().check(inline_obj), *self._check_relation(inline_obj, parent_model), *self._check_exclude_of_parent_model(inline_obj, parent_model), *self._check_extra(inline_obj), *self._check_max_num(inline_obj), *self._check_min_num(inline_obj), *self._check_formset(inline_obj), ] def _check_exclude_of_parent_model(self, obj, parent_model): # Do not perform more specific checks if the base checks result in an # error. errors = super()._check_exclude(obj) if errors: return [] # Skip if `fk_name` is invalid. if self._check_relation(obj, parent_model): return [] if obj.exclude is None: return [] fk = _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) if fk.name in obj.exclude: return [ checks.Error( "Cannot exclude the field '%s', because it is the foreign key " "to the parent model '%s'." % ( fk.name, parent_model._meta.label, ), obj=obj.__class__, id="admin.E201", ) ] else: return [] def _check_relation(self, obj, parent_model): try: _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) except ValueError as e: return [checks.Error(e.args[0], obj=obj.__class__, id="admin.E202")] else: return [] def _check_extra(self, obj): """Check that extra is an integer.""" if not isinstance(obj.extra, int): return must_be("an integer", option="extra", obj=obj, id="admin.E203") else: return [] def _check_max_num(self, obj): """Check that max_num is an integer.""" if obj.max_num is None: return [] elif not isinstance(obj.max_num, int): return must_be("an integer", option="max_num", obj=obj, id="admin.E204") else: return [] def _check_min_num(self, obj): """Check that min_num is an integer.""" if obj.min_num is None: return [] elif not isinstance(obj.min_num, int): return must_be("an integer", option="min_num", obj=obj, id="admin.E205") else: return [] def _check_formset(self, obj): """Check formset is a subclass of BaseModelFormSet.""" if not _issubclass(obj.formset, BaseModelFormSet): return must_inherit_from( parent="BaseModelFormSet", option="formset", obj=obj, id="admin.E206" ) else: return [] def must_be(type, option, obj, id): return [ checks.Error( "The value of '%s' must be %s." % (option, type), obj=obj.__class__, id=id, ), ] def must_inherit_from(parent, option, obj, id): return [ checks.Error( "The value of '%s' must inherit from '%s'." % (option, parent), obj=obj.__class__, id=id, ), ] def refer_to_missing_field(field, option, obj, id): return [ checks.Error( "The value of '%s' refers to '%s', which is not a field of '%s'." % (option, field, obj.model._meta.label), obj=obj.__class__, id=id, ), ]
6632989ba798aff107edd3399f3275f1c3fda5de78db9433ac0a79ef281a5964
from django import forms from django.contrib import admin from django.contrib.admin import BooleanFieldListFilter, SimpleListFilter from django.contrib.admin.options import VERTICAL, ModelAdmin, TabularInline from django.contrib.admin.sites import AdminSite from django.core.checks import Error from django.db.models import CASCADE, F, Field, ForeignKey, Model from django.db.models.functions import Upper from django.forms.models import BaseModelFormSet from django.test import SimpleTestCase from .models import Band, Song, User, ValidationTestInlineModel, ValidationTestModel class CheckTestCase(SimpleTestCase): def assertIsInvalid( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None, admin_site=None, ): if admin_site is None: admin_site = AdminSite() invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, admin_site) self.assertEqual( admin_obj.check(), [Error(msg, hint=hint, obj=invalid_obj, id=id)] ) def assertIsInvalidRegexp( self, model_admin, model, msg, id=None, hint=None, invalid_obj=None ): """ Same as assertIsInvalid but treats the given msg as a regexp. """ invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.hint, hint) self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.id, id) self.assertRegex(error.msg, msg) def assertIsValid(self, model_admin, model, admin_site=None): if admin_site is None: admin_site = AdminSite() admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), []) class RawIdCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): raw_id_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields' must be a list or tuple.", "admin.E001", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' must be a foreign key or a " "many-to-many field.", "admin.E003", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_field_attname(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ["band_id"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'band_id', which is " "not a field of 'modeladmin.ValidationTestModel'.", "admin.E002", ) class FieldsetsCheckTests(CheckTestCase): def test_valid_case(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_not_iterable(self): class TestModelAdmin(ModelAdmin): fieldsets = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets' must be a list or tuple.", "admin.E007", ) def test_non_iterable_item(self): class TestModelAdmin(ModelAdmin): fieldsets = ({},) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be a list or tuple.", "admin.E008", ) def test_item_not_a_pair(self): class TestModelAdmin(ModelAdmin): fieldsets = ((),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be of length 2.", "admin.E009", ) def test_second_element_of_item_not_a_dict(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", ()),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must be a dictionary.", "admin.E010", ) def test_missing_fields_key(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {}),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must contain the key 'fields'.", "admin.E011", ) class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_specified_both_fields_and_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = (("General", {"fields": ("name",)}),) fields = ["name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "Both 'fieldsets' and 'fields' are specified.", "admin.E005", ) def test_duplicate_fields(self): class TestModelAdmin(ModelAdmin): fieldsets = [(None, {"fields": ["name", "name"]})] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[0][1]'.", "admin.E012", ) def test_duplicate_fields_in_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = [ (None, {"fields": ["name"]}), (None, {"fields": ["name"]}), ] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[1][1]'.", "admin.E012", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) class FieldsCheckTests(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ["name", "name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", "admin.E006", ) def test_inline(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fields = 10 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' must be a list or tuple.", "admin.E004", invalid_obj=ValidationTestInline, ) class FormCheckTests(CheckTestCase): def test_invalid_type(self): class FakeForm: pass class TestModelAdmin(ModelAdmin): form = FakeForm class TestModelAdminWithNoForm(ModelAdmin): form = "not a form" for model_admin in (TestModelAdmin, TestModelAdminWithNoForm): with self.subTest(model_admin): self.assertIsInvalid( model_admin, ValidationTestModel, "The value of 'form' must inherit from 'BaseModelForm'.", "admin.E016", ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (("Band", {"fields": ("name",)}),) self.assertIsValid(BandAdmin, Band) def test_valid_case(self): class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm fieldsets = (("Band", {"fields": ("name", "bio", "sign_date", "delete")}),) self.assertIsValid(BandAdmin, Band) class FilterVerticalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", "admin.E017", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' must be a many-to-many field.", "admin.E020", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_vertical = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FilterHorizontalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_horizontal = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal' must be a list or tuple.", "admin.E018", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E019", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' must be a many-to-many field.", "admin.E020", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ("users",) self.assertIsValid(TestModelAdmin, ValidationTestModel) class RadioFieldsCheckTests(CheckTestCase): def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): radio_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' must be a dictionary.", "admin.E021", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): radio_fields = {"non_existent_field": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E022", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): radio_fields = {"name": VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'name', which is not an instance " "of ForeignKey, and does not have a 'choices' definition.", "admin.E023", ) def test_invalid_value(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": None} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or " "admin.VERTICAL.", "admin.E024", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): radio_fields = {"state": VERTICAL} self.assertIsValid(TestModelAdmin, ValidationTestModel) class PrepopulatedFieldsCheckTests(CheckTestCase): def test_not_list_or_tuple(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": "test"} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"]' must be a list or tuple.", "admin.E029", ) def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' must be a dictionary.", "admin.E026", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"non_existent_field": ("slug",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E027", ) def test_missing_field_again(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("non_existent_field",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"][0]' refers to " "'non_existent_field', which is not a field of " "'modeladmin.ValidationTestModel'.", "admin.E030", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"users": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'users', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", "admin.E028", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"slug": ("name",)} self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_one_to_one_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {"best_friend": ("name",)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'best_friend', which must " "not be a DateTimeField, a ForeignKey, a OneToOneField, or a " "ManyToManyField.", "admin.E028", ) class ListDisplayTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display' must be a list or tuple.", "admin.E107", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'non_existent_field', " "which is not a callable, an attribute of 'TestModelAdmin', " "or an attribute or method on 'modeladmin.ValidationTestModel'.", "admin.E108", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): list_display = ("users",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_invalid_reverse_related_field(self): class TestModelAdmin(ModelAdmin): list_display = ["song_set"] self.assertIsInvalid( TestModelAdmin, Band, "The value of 'list_display[0]' must not be a many-to-many field or a " "reverse foreign key.", "admin.E109", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_field_accessible_via_instance(self): class PositionField(Field): """Custom field accessible only via instance.""" def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, self) def __get__(self, instance, owner): if instance is None: raise AttributeError() class TestModel(Model): field = PositionField() class TestModelAdmin(ModelAdmin): list_display = ("field",) self.assertIsValid(TestModelAdmin, TestModel) class ListDisplayLinksCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display_links = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display_links = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, ( "The value of 'list_display_links[0]' refers to " "'non_existent_field', which is not defined in 'list_display'." ), "admin.E111", ) def test_missing_in_list_display(self): class TestModelAdmin(ModelAdmin): list_display_links = ("name",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links[0]' refers to 'name', which is not " "defined in 'list_display'.", "admin.E111", ) def test_valid_case(self): @admin.display def a_callable(obj): pass class TestModelAdmin(ModelAdmin): @admin.display def a_method(self, obj): pass list_display = ("name", "decade_published_in", "a_method", a_callable) list_display_links = ("name", "decade_published_in", "a_method", a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_None_is_valid_case(self): class TestModelAdmin(ModelAdmin): list_display_links = None self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_links_check_skipped_if_get_list_display_overridden(self): """ list_display_links check is skipped if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = ["name", "subtitle"] def get_list_display(self, request): pass self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_link_checked_for_list_tuple_if_get_list_display_overridden( self, ): """ list_display_links is checked for list/tuple/None even if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = "non-list/tuple" def get_list_display(self, request): pass self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", "admin.E110", ) class ListFilterTests(CheckTestCase): def test_list_filter_validation(self): class TestModelAdmin(ModelAdmin): list_filter = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter' must be a list or tuple.", "admin.E112", ) def test_not_list_filter_class(self): class TestModelAdmin(ModelAdmin): list_filter = ["RandomClass"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'RandomClass', which " "does not refer to a Field.", "admin.E116", ) def test_callable(self): def random_callable(): pass class TestModelAdmin(ModelAdmin): list_filter = [random_callable] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_callable(self): class TestModelAdmin(ModelAdmin): list_filter = [[42, 42]] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_filter = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E116", ) def test_not_filter(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (RandomClass,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_filter_again(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (("is_active", RandomClass),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_not_filter_again_again(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = (("is_active", AwesomeFilter),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", "admin.E115", ) def test_list_filter_is_func(self): def get_filter(): pass class TestModelAdmin(ModelAdmin): list_filter = [get_filter] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", "admin.E113", ) def test_not_associated_with_field_name(self): class TestModelAdmin(ModelAdmin): list_filter = (BooleanFieldListFilter,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.", "admin.E114", ) def test_valid_case(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return "awesomeness" def get_choices(self, request): return (("bit", "A bit awesome"), ("very", "Very awesome")) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = ( "is_active", AwesomeFilter, ("is_active", BooleanFieldListFilter), "no", ) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListPerPageCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_per_page = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_per_page' must be an integer.", "admin.E118", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_per_page = 100 self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListMaxShowAllCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_max_show_all = "hello" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_max_show_all' must be an integer.", "admin.E119", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 200 self.assertIsValid(TestModelAdmin, ValidationTestModel) class SearchFieldsCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): search_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'search_fields' must be a list or tuple.", "admin.E126", ) class DateHierarchyCheckTests(CheckTestCase): def test_missing_field(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "non_existent_field" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' refers to 'non_existent_field', " "which does not refer to a Field.", "admin.E127", ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "name" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", "admin.E128", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "pub_date" self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "band__sign_date" self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = "band__name" self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", "admin.E128", ) class OrderingCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): ordering = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' must be a list or tuple.", "admin.E031", ) class TestModelAdmin(ModelAdmin): ordering = ("non_existent_field",) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'non_existent_field', " "which is not a field of 'modeladmin.ValidationTestModel'.", "admin.E033", ) def test_random_marker_not_alone(self): class TestModelAdmin(ModelAdmin): ordering = ("?", "name") self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' has the random ordering marker '?', but contains " "other fields as well.", "admin.E032", hint='Either remove the "?", or remove the other fields.', ) def test_valid_random_marker_case(self): class TestModelAdmin(ModelAdmin): ordering = ("?",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_complex_case(self): class TestModelAdmin(ModelAdmin): ordering = ("band__name",) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_case(self): class TestModelAdmin(ModelAdmin): ordering = ("name", "pk") self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_invalid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (F("nonexistent"),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'nonexistent', which is not " "a field of 'modeladmin.ValidationTestModel'.", "admin.E033", ) def test_valid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (Upper("name"), Upper("band__name").desc()) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListSelectRelatedCheckTests(CheckTestCase): def test_invalid_type(self): class TestModelAdmin(ModelAdmin): list_select_related = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_select_related' must be a boolean, tuple or list.", "admin.E117", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_select_related = False self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveAsCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_as = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_as' must be a boolean.", "admin.E101", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_as = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveOnTopCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_on_top = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_on_top' must be a boolean.", "admin.E102", ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_on_top = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class InlinesCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): inlines = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'inlines' must be a list or tuple.", "admin.E103", ) def test_not_correct_inline_field(self): class TestModelAdmin(ModelAdmin): inlines = [42] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.TestModelAdmin' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_not_model_admin(self): class ValidationTestInline: pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_missing_model_field(self): class ValidationTestInline(TabularInline): pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must have a 'model' attribute\.", "admin.E105", ) def test_invalid_model_type(self): class SomethingBad: pass class ValidationTestInline(TabularInline): model = SomethingBad class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", "admin.E106", ) def test_invalid_model(self): class ValidationTestInline(TabularInline): model = "Not a class" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", "admin.E106", ) def test_invalid_callable(self): def random_obj(): pass class TestModelAdmin(ModelAdmin): inlines = [random_obj] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.random_obj' must inherit from 'InlineModelAdmin'\.", "admin.E104", ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FkNameCheckTests(CheckTestCase): def test_missing_field(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = "non_existent_field" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "'modeladmin.ValidationTestInlineModel' has no field named " "'non_existent_field'.", "admin.E202", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = "parent" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_proxy_model_parent(self): class Parent(Model): pass class ProxyChild(Parent): class Meta: proxy = True class ProxyProxyChild(ProxyChild): class Meta: proxy = True class Related(Model): proxy_child = ForeignKey(ProxyChild, on_delete=CASCADE) class InlineFkName(admin.TabularInline): model = Related fk_name = "proxy_child" class InlineNoFkName(admin.TabularInline): model = Related class ProxyProxyChildAdminFkName(admin.ModelAdmin): inlines = [InlineFkName, InlineNoFkName] self.assertIsValid(ProxyProxyChildAdminFkName, ProxyProxyChild) class ExtraCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'extra' must be an integer.", "admin.E203", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MaxNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'max_num' must be an integer.", "admin.E204", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MinNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = "hello" class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'min_num' must be an integer.", "admin.E205", invalid_obj=ValidationTestInline, ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FormsetCheckTests(CheckTestCase): def test_invalid_type(self): class FakeFormSet: pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = FakeFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", "admin.E206", invalid_obj=ValidationTestInline, ) def test_inline_without_formset_class(self): class ValidationTestInlineWithoutFormsetClass(TabularInline): model = ValidationTestInlineModel formset = "Not a FormSet Class" class TestModelAdminWithoutFormsetClass(ModelAdmin): inlines = [ValidationTestInlineWithoutFormsetClass] self.assertIsInvalid( TestModelAdminWithoutFormsetClass, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", "admin.E206", invalid_obj=ValidationTestInlineWithoutFormsetClass, ) def test_valid_case(self): class RealModelFormSet(BaseModelFormSet): pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = RealModelFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListDisplayEditableTests(CheckTestCase): def test_list_display_links_is_none(self): """ list_display and list_editable can contain the same values when list_display_links is None """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = list_display list_display_links = None self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_first_item(self): """ The first item in list_display can be the same as the first in list_editable. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["name", "slug"] list_display_links = ["pub_date"] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_in_list_editable(self): """ The first item in list_display can be in list_editable as long as list_display_links is defined. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["slug", "name"] list_display_links = ["pub_date"] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_no_list_display_links(self): """ The first item in list_display cannot be the same as the first item in list_editable if list_display_links is not defined. """ class ProductAdmin(ModelAdmin): list_display = ["name"] list_editable = ["name"] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[0]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id="admin.E124", ) def test_list_display_first_item_in_list_editable_no_list_display_links(self): """ The first item in list_display cannot be in list_editable if list_display_links isn't defined. """ class ProductAdmin(ModelAdmin): list_display = ["name", "slug", "pub_date"] list_editable = ["slug", "name"] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[1]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id="admin.E124", ) def test_both_list_editable_and_list_display_links(self): class ProductAdmin(ModelAdmin): list_editable = ("name",) list_display = ("name",) list_display_links = ("name",) self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'name' cannot be in both 'list_editable' and " "'list_display_links'.", id="admin.E123", ) class AutocompleteFieldsTests(CheckTestCase): def test_autocomplete_e036(self): class Admin(ModelAdmin): autocomplete_fields = "name" self.assertIsInvalid( Admin, Band, msg="The value of 'autocomplete_fields' must be a list or tuple.", id="admin.E036", invalid_obj=Admin, ) def test_autocomplete_e037(self): class Admin(ModelAdmin): autocomplete_fields = ("nonexistent",) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' refers to 'nonexistent', " "which is not a field of 'modeladmin.ValidationTestModel'." ), id="admin.E037", invalid_obj=Admin, ) def test_autocomplete_e38(self): class Admin(ModelAdmin): autocomplete_fields = ("name",) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' must be a foreign " "key or a many-to-many field." ), id="admin.E038", invalid_obj=Admin, ) def test_autocomplete_e039(self): class Admin(ModelAdmin): autocomplete_fields = ("band",) self.assertIsInvalid( Admin, Song, msg=( 'An admin for model "Band" has to be registered ' "to be referenced by Admin.autocomplete_fields." ), id="admin.E039", invalid_obj=Admin, ) def test_autocomplete_e040(self): class NoSearchFieldsAdmin(ModelAdmin): pass class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ("featuring",) site = AdminSite() site.register(Band, NoSearchFieldsAdmin) self.assertIsInvalid( AutocompleteAdmin, Song, msg=( 'NoSearchFieldsAdmin must define "search_fields", because ' "it's referenced by AutocompleteAdmin.autocomplete_fields." ), id="admin.E040", invalid_obj=AutocompleteAdmin, admin_site=site, ) def test_autocomplete_is_valid(self): class SearchFieldsAdmin(ModelAdmin): search_fields = "name" class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ("featuring",) site = AdminSite() site.register(Band, SearchFieldsAdmin) self.assertIsValid(AutocompleteAdmin, Song, admin_site=site) def test_autocomplete_is_onetoone(self): class UserAdmin(ModelAdmin): search_fields = ("name",) class Admin(ModelAdmin): autocomplete_fields = ("best_friend",) site = AdminSite() site.register(User, UserAdmin) self.assertIsValid(Admin, ValidationTestModel, admin_site=site) class ActionsCheckTests(CheckTestCase): def test_custom_permissions_require_matching_has_method(self): @admin.action(permissions=["custom"]) def custom_permission_action(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (custom_permission_action,) self.assertIsInvalid( BandAdmin, Band, "BandAdmin must define a has_custom_permission() method for the " "custom_permission_action action.", id="admin.E129", ) def test_actions_not_unique(self): @admin.action def action(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action, action) self.assertIsInvalid( BandAdmin, Band, "__name__ attributes of actions defined in BandAdmin must be " "unique. Name 'action' is not unique.", id="admin.E130", ) def test_actions_unique(self): @admin.action def action1(modeladmin, request, queryset): pass @admin.action def action2(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action1, action2) self.assertIsValid(BandAdmin, Band)
a9f2cc70b8eda07787961e72fdad8e7c2f16c3a45e95a3fb3625d699541fcb1d
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.utils import translation from django.utils.formats import ( date_format, get_format, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, sanitize_strftime_format, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, "other", "locale"), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override("fr") def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual( ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 année", ) self.assertEqual( ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 années", ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" ) def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") @override_settings(LOCALE_PATHS=extended_locale_paths) @translation.override("fr") def test_multiple_plurals_per_language(self): """ Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po has a different plural equation with 3 plurals, this tests if those plural are honored. """ self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") french = trans_real.catalog() # Internal _catalog can query subcatalogs (from different po files). self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") def test_override(self): activate("de") try: with translation.override("pl"): self.assertEqual(get_language(), "pl") self.assertEqual(get_language(), "de") with translation.override(None): self.assertIsNone(get_language()) with translation.override("pl"): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), "de") finally: deactivate() def test_override_decorator(self): @translation.override("pl") def func_pl(): self.assertEqual(get_language(), "pl") @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate("de") func_pl() self.assertEqual(get_language(), "de") func_none() self.assertEqual(get_language(), "de") finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate("fr") @translation.override("pl") def func_pl(): pass deactivate() try: activate("en") func_pl() self.assertEqual(get_language(), "en") finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy("Add %(name)s") d = {"name": "Ringo"} self.assertEqual("Add Ringo", s % d) with translation.override("de", deactivate=True): self.assertEqual("Ringo hinzuf\xfcgen", s % d) with translation.override("pl"): self.assertEqual("Dodaj Ringo", s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy("Add %(name)s") self.assertEqual(s, s1) s2 = gettext_lazy("Add %(name)s") s3 = gettext_lazy("Add %(name)s") self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy("Some other string") self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy("%d good result", "%d good results") simple_context_with_format = npgettext_lazy( "Exclamation", "%d good result", "%d good results" ) simple_without_format = ngettext_lazy("good result", "good results") with translation.override("de"): self.assertEqual(simple_with_format % 1, "1 gutes Resultat") self.assertEqual(simple_with_format % 4, "4 guten Resultate") self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") self.assertEqual(simple_without_format % 1, "gutes Resultat") self.assertEqual(simple_without_format % 4, "guten Resultate") complex_nonlazy = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 ) complex_deferred = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy % {"num": 4, "name": "Jim"}, "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 1}, "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 5}, "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred % {"name": "Jim"} self.assertEqual( complex_context_nonlazy % {"num": 4, "name": "Jim"}, "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 1}, "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 5}, "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred % {"name": "Jim"} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy("{} good result", "{} good results") simple_context_with_format = npgettext_lazy( "Exclamation", "{} good result", "{} good results" ) with translation.override("de"): self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") self.assertEqual(simple_with_format.format(4), "4 guten Resultate") self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") complex_nonlazy = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 ) complex_deferred = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy.format(num=4, name="Jim"), "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred.format(name="Jim", num=1), "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred.format(name="Jim", num=5), "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred.format(name="Jim") self.assertEqual( complex_context_nonlazy.format(num=4, name="Jim"), "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=1), "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=5), "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred.format(name="Jim") def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy("%d good result", "%d good results")) self.assertFalse(ngettext_lazy("", "")) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy("%d good result", "%d good results") self.assertEqual(s1 % 1, "1 good result") self.assertEqual(s1 % 8, "8 good results") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, "1 good result") self.assertEqual(s2 % 8, "8 good results") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override("de"): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual( npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" ) def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override("de"): self.assertEqual("", gettext("")) s = mark_safe("") self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe("Password") s2 = mark_safe("May") with translation.override("de", deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext("month name", s2)), SafeString) self.assertEqual("aPassword", SafeString("a") + s1) self.assertEqual("Passworda", s1 + SafeString("a")) self.assertEqual("Passworda", s1 + mark_safe("a")) self.assertEqual("aPassword", mark_safe("a") + s1) self.assertEqual("as", mark_safe("a") + mark_safe("s")) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation("ca") ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" with translation.override("ca", deactivate=True): self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) def test_to_locale(self): tests = ( ("en", "en"), ("EN", "en"), ("en-us", "en_US"), ("EN-US", "en_US"), ("en_US", "en_US"), # With > 2 characters after the dash. ("sr-latn", "sr_Latn"), ("sr-LATN", "sr_Latn"), ("sr_Latn", "sr_Latn"), # 3-char language codes. ("ber-MA", "ber_MA"), ("BER-MA", "ber_MA"), ("BER_MA", "ber_MA"), ("ber_MA", "ber_MA"), # With private use subtag (x-informal). ("nl-nl-x-informal", "nl_NL-x-informal"), ("NL-NL-X-INFORMAL", "nl_NL-x-informal"), ("sr-latn-x-informal", "sr_Latn-x-informal"), ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat") def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE="he"): self.assertIs(get_language_bidi(), True) class TranslationLoadingTests(SimpleTestCase): def setUp(self): """Clear translation state.""" self._old_language = get_language() self._old_translations = trans_real._translations deactivate() trans_real._translations = {} def tearDown(self): trans_real._translations = self._old_translations activate(self._old_language) @override_settings( USE_I18N=True, LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("en-ca", "English (Canada)"), ("en-nz", "English (New Zealand)"), ("en-au", "English (Australia)"), ], LOCALE_PATHS=[os.path.join(here, "loading")], INSTALLED_APPS=["i18n.loading_app"], ) def test_translation_loading(self): """ "loading_app" does not have translations for all languages provided by "loading". Catalogs are merged correctly. """ tests = [ ("en", "local country person"), ("en_AU", "aussie"), ("en_NZ", "kiwi"), ("en_CA", "canuck"), ] # Load all relevant translations. for language, _ in tests: activate(language) # Catalogs are merged correctly. for language, nickname in tests: with self.subTest(language=language): activate(language) self.assertEqual(gettext("local country person"), nickname) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations["en-YY"] = None return res trans_real._translations = {sideeffect_str("en-XX"): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate("pl") # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal("66666.666") self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context( { "n": self.n, "t": self.t, "d": self.d, "dt": self.dt, "f": self.f, "l": self.long, } ) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn( "2017", date_format(some_date) ) # Uses DATE_FORMAT by default self.assertIn( "23", time_format(some_datetime) ) # Uses TIME_FORMAT by default self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT")) self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT")) self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT")) self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT")) self.assertIn( "2017", date_format(some_datetime, "SHORT_DATETIME_FORMAT"), ) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual( "66666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "66666A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "66666", nformat( self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" ), ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( "66,666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "6B6B6B6B6A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10,00,00,000.00", nformat( 100000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, 0), thousand_sep=",", ), ) self.assertEqual( "1,0,00,000,0000.00", nformat( 10000000000.00, decimal_sep=".", decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=",", ), ) self.assertEqual( "10000,00,000.00", nformat( 1000000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, -1), thousand_sep=",", ), ) # This unusual grouping/force_grouping combination may be triggered # by the intcomma filter. self.assertEqual( "10000", nformat( self.long, decimal_sep=".", decimal_pos=0, grouping=0, force_grouping=True, ), ) # date filter self.assertEqual( "31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), ) self.assertEqual( "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) ) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override("fr"): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) # Even a second time (after the format has been cached)... self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override("ca", deactivate=True): self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15", time_format(self.t)) self.assertEqual("31 desembre de 2009", date_format(self.d)) self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1))) self.assertEqual( "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") ) self.assertEqual( "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", localize(self.n)) self.assertEqual("99.999,999", localize(self.f)) self.assertEqual("10.000", localize(self.long)) self.assertEqual("True", localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", localize(self.n)) self.assertEqual("99999,999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("31 desembre de 2009", localize(self.d)) self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm( { "decimal_field": "66.666,666", "float_field": "99.999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertTrue(form3.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form3.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form3.cleaned_data["time_field"] ) self.assertEqual(1234, form3.cleaned_data["integer_field"]) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual( "31 desembre de 2009", Template("{{ d }}").render(self.ctxt) ) self.assertEqual( "31 desembre de 2009 a les 20:50", Template("{{ dt }}").render(self.ctxt), ) self.assertEqual( "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000,0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66.666,67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100.000,0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "31/12/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "31/12/2009 20:50", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) self.assertEqual( date_format(datetime.datetime.now()), Template('{% now "DATE_FORMAT" %}').render(self.ctxt), ) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form4.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form4.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form4.cleaned_data["time_field"] ) self.assertEqual(1234, form4.cleaned_data["integer_field"]) form5 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form5.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # Russian locale (with E as month) with translation.override("ru", deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' "</option>" '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' "</option>" "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # English locale with translation.override("en", deactivate=True): self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("Dec. 31, 2009", date_format(self.d)) self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", localize(self.n)) self.assertEqual("99,999.999", localize(self.f)) self.assertEqual("10,000", localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Dec. 31, 2009", localize(self.d)) self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000.0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66,666.67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100,000.0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form5 = I18nForm( { "decimal_field": "66666.666", "float_field": "99999.999", "date_field": "12/31/2009", "datetime_field": "12/31/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form5.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form5.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data["datetime_field"], ) self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) self.assertEqual(1234, form5.cleaned_data["integer_field"]) form6 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form6.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de-at", deactivate=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) with translation.override("es-us", deactivate=True): self.assertEqual("31 de diciembre de 2009", date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): form6 = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" ' ' maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" ' ' id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' " required></li>" '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" ' ' id="id_products_delivered" required>' "</li>", ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00", ) self.assertEqual( datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"], ) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul(), ) def test_localized_input_func(self): tests = ( (True, "True"), (datetime.date(1, 1, 1), "0001-01-01"), (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_strftime_format(self): for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%C", "%02d" % (year // 100)), ("%F", "%04d-01-01" % year), ("%G", "%04d" % year), ("%Y", "%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_strftime_format_with_escaped_percent(self): dt = datetime.date(1, 1, 1) for fmt, expected in [ ("%%C", "%C"), ("%%F", "%F"), ("%%G", "%G"), ("%%Y", "%Y"), ("%%%%C", "%%C"), ("%%%%F", "%%F"), ("%%%%G", "%%G"), ("%%%%Y", "%%Y"), ]: with self.subTest(fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%%%C", "%%%02d" % (year // 100)), ("%%%F", "%%%04d-01-01" % year), ("%%%G", "%%%04d" % year), ("%%%Y", "%%%04d" % year), ("%%%%%C", "%%%%%02d" % (year // 100)), ("%%%%%F", "%%%%%04d-01-01" % year), ("%%%%%G", "%%%%%04d" % year), ("%%%%%Y", "%%%%%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override("ru", deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") self.assertEqual(sanitize_separators("12 345"), "12345") self.assertEqual(sanitize_separators("77 777,777"), "77777.777") with translation.override(None): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats( get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," ): self.assertEqual(sanitize_separators("10.234"), "10234") # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators("10.10"), "10.10") with translation.override(None): with self.settings(DECIMAL_SEPARATOR=","): self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") with self.settings( DECIMAL_SEPARATOR=",", THOUSAND_SEPARATOR=".", USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(sanitize_separators("1.001,10"), "1001.10") self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") # Invalid output. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module("django.conf.locale.de.formats") test_mod = import_module("i18n.other.locale.de.formats") test_mod2 = import_module("i18n.other2.locale.de.formats") with translation.override("de-at", deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules("de")), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules("de", "i18n.other.locale")), [test_mod, default_mod], ) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list( iter_format_modules( "de", ["i18n.other.locale", "i18n.other2.locale"] ) ), [test_mod, test_mod2, default_mod], ) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module("django.conf.locale.en.formats") en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") self.assertEqual( list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] ) def test_get_format_modules_lang(self): with translation.override("de", deactivate=True): self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) def test_get_format_lazy_format(self): self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context( {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} ) template1 = Template( "{% load l10n %}{% localize %}" "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" ) template2 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " "{{ int }}/{{ float }}/{{ date }}" ) template3 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" ) expected_localized = "1.455/3,14/31. Dezember 2016" expected_unlocalized = "1455/3.14/Dez. 31, 2016" output1 = "; ".join([expected_localized, expected_localized]) output2 = "; ".join( [expected_localized, expected_unlocalized, expected_localized] ) output3 = "; ".join([expected_localized, expected_unlocalized]) with translation.override("de", deactivate=True): with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_off_numbers(self): """A string representation is returned for unlocalized numbers.""" template = Template( "{% load l10n %}{% localize off %}" "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" ) context = Context( {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} ) with self.settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") def test_localized_as_text_as_hidden_input(self): """ Form input with 'as_hidden' or 'as_text' is correctly localized. """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): template = Template( "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" ) template_as_text = Template( "{% load l10n %}" "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" ) template_as_hidden = Template( "{% load l10n %}" "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" ) form = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) context = Context({"form": form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" ' 'value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" ' 'value="59,47">', ) def test_format_arbitrary_settings(self): self.assertEqual(get_format("DEBUG"), "DEBUG") def test_get_custom_format(self): reset_format_cache() with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): with translation.override("fr", deactivate=True): self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile("%([^BcdHImMpSwxXyY%])") for language_code, language_name in settings.LANGUAGES: for format_name in ( "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name), ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE="de") def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override("en"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-us"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-ca"): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ("de", [("de", 1.0)]), ("en-AU", [("en-au", 1.0)]), ("es-419", [("es-419", 1.0)]), ("*;q=1.00", [("*", 1.0)]), ("en-AU;q=0.123", [("en-au", 0.123)]), ("en-au;q=0.5", [("en-au", 0.5)]), ("en-au;q=1.0", [("en-au", 1.0)]), ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), ("en-au-xx", [("en-au-xx", 1.0)]), ( "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", [ ("de", 1.0), ("en-au", 0.75), ("en-us", 0.5), ("en", 0.25), ("es", 0.125), ("fa", 0.125), ], ), ("*", [("*", 1.0)]), ("de;q=0.", [("de", 0.0)]), ("en; q=1,", [("en", 1.0)]), ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), ( "en" + "-x" * 20, [("en-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x", 1.0)], ), ( ", ".join(["en; q=1.0"] * 20), [("en", 1.0)] * 20, ), # Bad headers ("en-gb;q=1.0000", []), ("en;q=0.1234", []), ("en;q=.2", []), ("abcdefghi-au", []), ("**", []), ("en,,gb", []), ("en-au;q=0.1.0", []), (("X" * 97) + "Z,en", []), ("da, en-gb;q=0.8, en;q=0.7,#", []), ("de;q=2.0", []), ("de;q=0.a", []), ("12-345", []), ("", []), ("en;q=1e0", []), ("en-au;q=1.0", []), # Invalid as language-range value too long. ("xxxxxxxx" + "-xxxxxxxx" * 500, []), # Header value too long, only parse up to limit. (", ".join(["en; q=1.0"] * 500), [("en", 1.0)] * 45), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual( trans_real.parse_accept_lang_header(value), tuple(expected) ) def test_parse_literal_http_header(self): tests = [ ("pt-br", "pt-br"), ("pt", "pt"), ("es,de", "es"), ("es-a,de", "es"), # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the # preferred language, the main 'es' translation should be selected # instead. ("es-us", "es"), # There isn't a main language (zh) translation of Django but there # is a translation to variation (zh-hans) the user sets zh-hans as # the preferred language, it should be selected without falling # back nor ignoring it. ("zh-hans,de", "zh-hans"), ("NL", "nl"), ("fy", "fy"), ("ia", "ia"), ("sr-latn", "sr-latn"), ("zh-hans", "zh-hans"), ("zh-hant", "zh-hant"), ] for header, expected in tests: with self.subTest(header=header): request = self.rf.get("/", headers={"accept-language": header}) self.assertEqual(get_language_from_request(request), expected) @override_settings( LANGUAGES=[ ("en", "English"), ("zh-hans", "Simplified Chinese"), ("zh-hant", "Traditional Chinese"), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "zh-cn,en"}) self.assertEqual(g(request), "zh-hans") request = self.rf.get("/", headers={"accept-language": "zh-tw,en"}) self.assertEqual(g(request), "zh-hant") def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ request = self.rf.get("/", headers={"accept-language": "zh-my,en"}) self.assertEqual(get_language_from_request(request), "zh-hans") def test_subsequent_code_fallback_language(self): """ Subsequent language codes should be used when the language code is not supported. """ tests = [ ("zh-Hans-CN", "zh-hans"), ("zh-hans-mo", "zh-hans"), ("zh-hans-HK", "zh-hans"), ("zh-Hant-HK", "zh-hant"), ("zh-hant-tw", "zh-hant"), ("zh-hant-SG", "zh-hant"), ] for value, expected in tests: with self.subTest(value=value): request = self.rf.get("/", headers={"accept-language": f"{value},en"}) self.assertEqual(get_language_from_request(request), expected) def test_parse_language_cookie(self): g = get_language_from_request request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br" self.assertEqual("pt-br", g(request)) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt" self.assertEqual("pt", g(request)) request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es" self.assertEqual("es", g(request)) # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the preferred # language, the main 'es' translation should be selected instead. request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us" self.assertEqual(g(request), "es") # There isn't a main language (zh) translation of Django but there is a # translation to variation (zh-hans) the user sets zh-hans as the # preferred language, it should be selected without falling back nor # ignoring it. request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans" self.assertEqual(g(request), "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("ar-dz", "Algerian Arabic"), ("de", "German"), ("de-at", "Austrian German"), ("pt-BR", "Portuguese (Brazil)"), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g("en"), "en") self.assertEqual(g("en-gb"), "en") self.assertEqual(g("de"), "de") self.assertEqual(g("de-at"), "de-at") self.assertEqual(g("de-ch"), "de") self.assertEqual(g("pt-br"), "pt-br") self.assertEqual(g("pt-BR"), "pt-BR") self.assertEqual(g("pt"), "pt-br") self.assertEqual(g("pt-pt"), "pt-br") self.assertEqual(g("ar-dz"), "ar-dz") self.assertEqual(g("ar-DZ"), "ar-DZ") with self.assertRaises(LookupError): g("pt", strict=True) with self.assertRaises(LookupError): g("pt-pt", strict=True) with self.assertRaises(LookupError): g("xyz") with self.assertRaises(LookupError): g("xy-zz") def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g("pt") with self.assertRaises(LookupError): g("de") with self.assertRaises(LookupError): g("de-at") with self.assertRaises(LookupError): g("de", strict=True) with self.assertRaises(LookupError): g("de-at", strict=True) with self.assertRaises(LookupError): g("xyz") @override_settings( LANGUAGES=[ ("en", "English"), ("en-latn-us", "Latin English"), ("de", "German"), ("de-1996", "German, orthography of 1996"), ("de-at", "Austrian German"), ("de-ch-1901", "German, Swiss variant, traditional orthography"), ("i-mingo", "Mingo"), ("kl-tunumiit", "Tunumiisiut"), ("nan-hani-tw", "Hanji"), ("pl", "Polish"), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path tests = [ ("/pl/", "pl"), ("/pl", "pl"), ("/xyz/", None), ("/en/", "en"), ("/en-gb/", "en"), ("/en-latn-us/", "en-latn-us"), ("/en-Latn-US/", "en-Latn-US"), ("/de/", "de"), ("/de-1996/", "de-1996"), ("/de-at/", "de-at"), ("/de-AT/", "de-AT"), ("/de-ch/", "de"), ("/de-ch-1901/", "de-ch-1901"), ("/de-simple-page-test/", None), ("/i-mingo/", "i-mingo"), ("/kl-tunumiit/", "kl-tunumiit"), ("/nan-hani-tw/", "nan-hani-tw"), ] for path, language in tests: with self.subTest(path=path): self.assertEqual(g(path), language) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g("/pl/")) self.assertIsNone(g("/pl")) self.assertIsNone(g("/xyz/")) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "pt-br"}) self.assertEqual("pt-br", g(request)) with self.settings(LANGUAGES=[("en", "English")]): self.assertNotEqual("pt-br", g(request)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate("de") def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is " "'%s'." % (msgstr, msgid, result), ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE="de") def test_app_translation(self): # Original translation. self.assertGettext("Date/time", "Datum/Zeit") # Different translation. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): # Force refreshing translations. activate("de") # Doesn't work because it's added later in the list. self.assertGettext("Date/time", "Datum/Zeit") with self.modify_settings( INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} ): # Force refreshing translations. activate("de") # Unless the original is removed from the list. self.assertGettext("Date/time", "Datum/Zeit (APP)") @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS") class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext("Date/time"), "Datum/Zeit") @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override("de-de"): self.assertGettext("Test 1 (en)", "(de-de)") self.assertGettext("Test 2 (en)", "(de)") class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString("Iñtërnâtiônàlizætiøn1") c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info("de") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info("xx") with translation.override("xx"): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info("de-xx") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info("xx-xx") def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info("zh-my") self.assertEqual(li["code"], "zh-hans") li = get_language_info("zh-hans") self.assertEqual(li["code"], "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get("/fr/streaming/") self.assertContains(response, "Oui/Non") response = self.client.get("/en/streaming/") self.assertContains(response, "Yes/No") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="en", ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") @override_settings(LANGUAGE_CODE="en-us") def test_default_lang_fallback_without_prefix(self): response = self.client.get("/simple/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"Yes") def test_other_lang_with_prefix(self): response = self.client.get("/fr/simple/") self.assertEqual(response.content, b"Oui") def test_unprefixed_language_with_accept_language(self): """'Accept-Language' is respected.""" response = self.client.get("/simple/", headers={"accept-language": "fr"}) self.assertRedirects(response, "/fr/simple/") def test_unprefixed_language_with_cookie_language(self): """A language set in the cookies is respected.""" self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fr"}) response = self.client.get("/simple/") self.assertRedirects(response, "/fr/simple/") def test_unprefixed_language_with_non_valid_language(self): response = self.client.get("/simple/", headers={"accept-language": "fi"}) self.assertEqual(response.content, b"Yes") self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fi"}) response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get("/de-simple-page-test/") self.assertEqual(response.content, b"Yes") def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get("/group1/group2/") self.assertEqual(response.status_code, 200) response = self.client.get("/nonexistent/") self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ("bg", "Bulgarian"), ("en-us", "English"), ("pt-br", "Portuguese (Brazil)"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language("en")) self.assertTrue(check_for_language("en-us")) self.assertTrue(check_for_language("en-US")) self.assertFalse(check_for_language("en_US")) self.assertTrue(check_for_language("be")) self.assertTrue(check_for_language("be@latin")) self.assertTrue(check_for_language("sr-RS@latin")) self.assertTrue(check_for_language("sr-RS@12345")) self.assertFalse(check_for_language("en-ü")) self.assertFalse(check_for_language("en\x00")) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language("be@ ")) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language("tr-TR.UTF-8")) self.assertFalse(check_for_language("tr-TR.UTF8")) self.assertFalse(check_for_language("de-DE.utf-8")) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language("en"), True) def test_get_language_from_request(self): # issue 19919 request = self.rf.get( "/", headers={"accept-language": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("en-us", lang) request = self.rf.get( "/", headers={"accept-language": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("bg", lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, None) def test_specific_language_codes(self): # issue 11915 request = self.rf.get( "/", headers={"accept-language": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) request = self.rf.get( "/", headers={"accept-language": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate("en") class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), ("xxx", "Somelanguage"), ], LANGUAGE_CODE="xxx", LOCALE_PATHS=[os.path.join(here, "commands", "locale")], ) def test_non_django_language(self): self.assertEqual(get_language(), "xxx") self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) open( os.path.join( app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" ), "w", ).close() app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) with mock.patch( "django.apps.apps.get_app_configs", return_value=[app_config] ): self.assertIs(check_for_language("dummy-lang"), True) @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), # xyz language has no locale files ("xyz", "XYZ"), ], ) @translation.override("xyz") def test_plural_non_django_language(self): self.assertEqual(get_language(), "xyz") self.assertEqual(ngettext("year", "years", 2), "years") @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {"foo": "bar"} path = Path("test.py") self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {"foo": "bar"}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {"foo": "bar"} trans_real._translations = {"foo": "bar"} trans_real._default = 1 trans_real._active = False path = Path("test.mo") self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0.0, 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1.0, 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0.0, 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1.0, -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
2f1589d360b1106f9ee859ca112a38a3eefdf4aa06be9a2d9d7addb3a727c0cd
from pathlib import Path from django.conf import settings from django.http import HttpResponseForbidden from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.translation import gettext as _ from django.utils.version import get_docs_version CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER c = { "title": _("Forbidden"), "main": _("CSRF verification failed. Request aborted."), "reason": reason, "no_referer": reason == REASON_NO_REFERER, "no_referer1": _( "You are seeing this message because this HTTPS site requires a " "“Referer header” to be sent by your web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties." ), "no_referer2": _( "If you have configured your browser to disable “Referer” headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for “same-origin” requests." ), "no_referer3": _( 'If you are using the <meta name="referrer" ' 'content="no-referrer"> tag or including the “Referrer-Policy: ' "no-referrer” header, please remove them. The CSRF protection " "requires the “Referer” header to do strict referer checking. If " "you’re concerned about privacy, use alternatives like " '<a rel="noreferrer" …> for links to third-party sites.' ), "no_cookie": reason == REASON_NO_CSRF_COOKIE, "no_cookie1": _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties." ), "no_cookie2": _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for “same-origin” " "requests." ), "DEBUG": settings.DEBUG, "docs_version": get_docs_version(), "more": _("More information is available with DEBUG=True."), } try: t = loader.get_template(template_name) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the fallback template. with builtin_template_path("csrf_403.html").open(encoding="utf-8") as fh: t = Engine().from_string(fh.read()) c = Context(c) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(t.render(c))
c86bbb50ebad1a0cccffad1198d42114be42b6e868ebf22e20cd6c23310d82b7
import posixpath from collections import defaultdict from django.utils.safestring import mark_safe from .base import Node, Template, TemplateSyntaxError, TextNode, Variable, token_kwargs from .library import Library register = Library() BLOCK_CONTEXT_KEY = "block_context" class BlockContext: def __init__(self): # Dictionary of FIFO queues. self.blocks = defaultdict(list) def __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] 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__(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: context["block"] = self result = self.nodelist.render(context) else: push = block = block_context.pop(self.name) if block is None: block = self # Create new block so we can store context without thread-safety issues. block = type(self)(block.name, block.nodelist) block.context = context context["block"] = block result = block.nodelist.render(context) if push is not None: block_context.push(self.name, push) return result def super(self): if not hasattr(self, "context"): raise TemplateSyntaxError( "'%s' object has no attribute 'context'. Did you use " "{{ block.super }} in a base template?" % self.__class__.__name__ ) render_context = self.context.render_context if ( BLOCK_CONTEXT_KEY in render_context and render_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None ): return mark_safe(self.render(self.context)) return "" class ExtendsNode(Node): must_be_first = True context_key = "extends_context" def __init__(self, nodelist, parent_name, template_dirs=None): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNode)} def __repr__(self): return "<%s: extends %s>" % (self.__class__.__name__, self.parent_name.token) def find_template(self, template_name, context): """ This is a wrapper around engine.find_template(). A history is kept in the render_context attribute between successive extends calls and passed as the skip argument. This enables extends to work recursively without extending the same template twice. """ history = context.render_context.setdefault( self.context_key, [self.origin], ) template, origin = context.template.engine.find_template( template_name, skip=history, ) history.append(origin) return template def get_parent(self, context): parent = self.parent_name.resolve(context) if not parent: error_msg = "Invalid template name in 'extends' tag: %r." % parent if self.parent_name.filters or isinstance(self.parent_name.var, Variable): error_msg += ( " Got this from the '%s' variable." % self.parent_name.token ) raise TemplateSyntaxError(error_msg) if isinstance(parent, Template): # parent is a django.template.Template return parent if isinstance(getattr(parent, "template", None), Template): # parent is a django.template.backends.django.Template return parent.template return self.find_template(parent, context) def render(self, context): compiled_parent = self.get_parent(context) if BLOCK_CONTEXT_KEY not in context.render_context: context.render_context[BLOCK_CONTEXT_KEY] = BlockContext() block_context = context.render_context[BLOCK_CONTEXT_KEY] # Add the block nodes from this node to the block context block_context.add_blocks(self.blocks) # If this block's parent doesn't have an extends node it is the root, # and its block nodes also need to be added to the block context. for node in compiled_parent.nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if not isinstance(node, ExtendsNode): blocks = { n.name: n for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode) } block_context.add_blocks(blocks) break # Call Template._render explicitly so the parser context stays # the same. with context.render_context.push_state(compiled_parent, isolated_context=False): return compiled_parent._render(context) class IncludeNode(Node): context_key = "__include_context" def __init__( self, template, *args, extra_context=None, isolated_context=False, **kwargs ): self.template = template self.extra_context = extra_context or {} self.isolated_context = isolated_context super().__init__(*args, **kwargs) def __repr__(self): return f"<{self.__class__.__qualname__}: template={self.template!r}>" def render(self, context): """ Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop. """ template = self.template.resolve(context) # Does this quack like a Template? if not callable(getattr(template, "render", None)): # If not, try the cache and select_template(). template_name = template or () if isinstance(template_name, str): template_name = ( construct_relative_path( self.origin.template_name, template_name, ), ) else: template_name = tuple(template_name) cache = context.render_context.dicts[0].setdefault(self, {}) template = cache.get(template_name) if template is None: template = context.template.engine.select_template(template_name) cache[template_name] = template # Use the base.Template of a backends.django.Template. elif hasattr(template, "template"): template = template.template values = { name: var.resolve(context) for name, var in self.extra_context.items() } if self.isolated_context: return template.render(context.new(values)) with context.push(**values): return template.render(context) @register.tag("block") def do_block(parser, token): """ Define a block that can be overridden by child templates. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) block_name = bits[1] # Keep track of the names of BlockNodes found in this template, so we can # check for duplication. try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError( "'%s' tag with name '%s' appears more than once" % (bits[0], block_name) ) parser.__loaded_blocks.append(block_name) except AttributeError: # parser.__loaded_blocks isn't a list yet parser.__loaded_blocks = [block_name] nodelist = parser.parse(("endblock",)) # This check is kept for backwards-compatibility. See #3100. endblock = parser.next_token() acceptable_endblocks = ("endblock", "endblock %s" % block_name) if endblock.contents not in acceptable_endblocks: parser.invalid_block_tag(endblock, "endblock", acceptable_endblocks) return BlockNode(block_name, nodelist) def construct_relative_path(current_template_name, relative_name): """ Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name. """ new_name = relative_name.strip("'\"") if not new_name.startswith(("./", "../")): # relative_name is a variable or a literal that doesn't contain a # relative path. return relative_name new_name = posixpath.normpath( posixpath.join( posixpath.dirname(current_template_name.lstrip("/")), new_name, ) ) if new_name.startswith("../"): raise TemplateSyntaxError( "The relative path '%s' points outside the file hierarchy that " "template '%s' is in." % (relative_name, current_template_name) ) if current_template_name.lstrip("/") == new_name: raise TemplateSyntaxError( "The relative path '%s' was translated to template name '%s', the " "same template in which the tag appears." % (relative_name, current_template_name) ) has_quotes = ( relative_name.startswith(('"', "'")) and relative_name[0] == relative_name[-1] ) return f'"{new_name}"' if has_quotes else new_name @register.tag("extends") def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent template to extend (if it evaluates to a string) or as the parent template itself (if it evaluates to a Template object). """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) bits[1] = construct_relative_path(parser.origin.template_name, bits[1]) parent_name = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError( "'%s' cannot appear more than once in the same template" % bits[0] ) return ExtendsNode(nodelist, parent_name) @register.tag("include") def do_include(parser, token): """ Load a template and render it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to exclude the current context when rendering the included template:: {% include "foo/some_include" only %} {% include "foo/some_include" with bar="1" only %} """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError( "%r tag takes at least one argument: the name of the template to " "be included." % bits[0] ) options = {} remaining_bits = bits[2:] while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError( "The %r option was specified more than once." % option ) if option == "with": value = token_kwargs(remaining_bits, parser, support_legacy=False) if not value: raise TemplateSyntaxError( '"with" in %r tag needs at least one keyword argument.' % bits[0] ) elif option == "only": value = True else: raise TemplateSyntaxError( "Unknown argument for %r tag: %r." % (bits[0], option) ) options[option] = value isolated_context = options.get("only", False) namemap = options.get("with", {}) bits[1] = construct_relative_path(parser.origin.template_name, bits[1]) return IncludeNode( parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context, )
5694c1750d335c766f1f6b1ffcc0fbb2b8e7e2f9506fd2b64a8dc5dc06c3886b
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of a ForNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = 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) '<html></html>' """ import inspect import logging import re from enum import Enum from django.template.context import BaseContext from django.utils.formats import localize from django.utils.html import conditional_escape, escape from django.utils.regex_helper import _lazy_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 gettext_lazy, pgettext_lazy from .exceptions import TemplateSyntaxError # template syntax constants FILTER_SEPARATOR = "|" FILTER_ARGUMENT_SEPARATOR = ":" VARIABLE_ATTRIBUTE_SEPARATOR = "." BLOCK_TAG_START = "{%" BLOCK_TAG_END = "%}" VARIABLE_TAG_START = "{{" VARIABLE_TAG_END = "}}" COMMENT_TAG_START = "{#" COMMENT_TAG_END = "#}" SINGLE_BRACE_START = "{" SINGLE_BRACE_END = "}" # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = "<unknown source>" # Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the # entire tag, including start/end delimiters. Using re.compile() is faster # than instantiating SimpleLazyObject with _lazy_re_compile(). tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})") logger = logging.getLogger("django.template") class TokenType(Enum): TEXT = 0 VAR = 1 BLOCK = 2 COMMENT = 3 class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __repr__(self): return "<%s name=%r>" % (self.__class__.__qualname__, self.name) def __eq__(self, other): return ( isinstance(other, Origin) and self.name == other.name and self.loader == other.loader ) @property def loader_name(self): if self.loader: return "%s.%s" % ( self.loader.__module__, self.loader.__class__.__name__, ) class Template: def __init__(self, template_string, origin=None, name=None, engine=None): # If Template is instantiated directly rather than from an Engine and # exactly one Django template engine is configured, use that engine. # This is required to preserve backwards-compatibility for direct use # e.g. Template('...').render(Context({...})) if engine is None: from .engine import Engine engine = Engine.get_default() if origin is None: origin = Origin(UNKNOWN_SOURCE) self.name = name self.origin = origin self.engine = engine self.source = str(template_string) # May be lazy. self.nodelist = self.compile_nodelist() def __repr__(self): return '<%s template_string="%s...">' % ( self.__class__.__qualname__, self.source[:20].replace("\n", ""), ) def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def compile_nodelist(self): """ Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is annotated with contextual line information where it occurred in the template source. """ if self.engine.debug: lexer = DebugLexer(self.source) else: lexer = Lexer(self.source) tokens = lexer.tokenize() parser = Parser( tokens, self.engine.template_libraries, self.engine.template_builtins, self.origin, ) try: return parser.parse() except Exception as e: if self.engine.debug: e.template_debug = self.get_exception_info(e, e.token) raise def get_exception_info(self, exception, token): """ Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """ start, end = token.position context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(self.source)): if start >= upto and end <= next: line = num before = escape(self.source[upto:start]) during = escape(self.source[start:end]) after = escape(self.source[end:next]) source_lines.append((num, escape(self.source[upto:next]))) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases exc_value.args can be empty or an invalid # string. try: message = str(exception.args[0]) except (IndexError, UnicodeDecodeError): message = "(Could not get exception message)" return { "message": message, "source_lines": source_lines[top:bottom], "before": before, "during": during, "after": after, "top": top, "bottom": bottom, "total": total, "line": line, "name": self.origin.name, "start": start, "end": end, } def linebreak_iter(template_source): yield 0 p = template_source.find("\n") while p >= 0: yield p + 1 p = template_source.find("\n", p + 1) yield len(template_source) + 1 class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """ self.token_type = token_type self.contents = contents self.lineno = lineno self.position = position def __repr__(self): token_name = self.token_type.name.capitalize() return '<%s token: "%s...">' % ( token_name, self.contents[:20].replace("\n", ""), ) def split_contents(self): split = [] bits = smart_split(self.contents) for bit in bits: # Handle translation-marked template pieces if bit.startswith(('_("', "_('")): sentinel = bit[2] + ")" trans_bit = [bit] while not bit.endswith(sentinel): bit = next(bits) trans_bit.append(bit) bit = " ".join(trans_bit) split.append(bit) return split class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def __repr__(self): return '<%s template_string="%s...", verbatim=%s>' % ( self.__class__.__qualname__, self.template_string[:20].replace("\n", ""), self.verbatim, ) def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for token_string in tag_re.split(self.template_string): if token_string: result.append(self.create_token(token_string, None, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result def create_token(self, token_string, position, lineno, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: # The [0:2] and [2:-2] ranges below strip off *_TAG_START and # *_TAG_END. The 2's are hard-coded for performance. Using # len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be # different, but it's not likely that the TAG_START values will # change anytime soon. token_start = token_string[0:2] if token_start == BLOCK_TAG_START: content = token_string[2:-2].strip() if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) # Otherwise, the current verbatim block is ending. self.verbatim = False elif content[:9] in ("verbatim", "verbatim "): # Then a verbatim block is starting. self.verbatim = "end%s" % content return Token(TokenType.BLOCK, content, position, lineno) if not self.verbatim: content = token_string[2:-2].strip() if token_start == VARIABLE_TAG_START: return Token(TokenType.VAR, content, position, lineno) # BLOCK_TAG_START was handled above. assert token_start == COMMENT_TAG_START return Token(TokenType.COMMENT, content, position, lineno) return Token(TokenType.TEXT, token_string, position, lineno) class DebugLexer(Lexer): def _tag_re_split_positions(self): last = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() yield last, start yield start, end last = end yield last, len(self.template_string) # This parallels the use of tag_re.split() in Lexer.tokenize(). def _tag_re_split(self): for position in self._tag_re_split_positions(): yield self.template_string[slice(*position)], position def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ # For maintainability, it is helpful if the implementation below can # continue to closely parallel Lexer.tokenize()'s implementation. in_tag = False lineno = 1 result = [] for token_string, position in self._tag_re_split(): if token_string: result.append(self.create_token(token_string, position, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): # Reverse the tokens so delete_first_token(), prepend_token(), and # next_token() can operate at the end of the list in constant time. self.tokens = list(reversed(tokens)) self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def __repr__(self): return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens) def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance boost. token_type = token.token_type.value if token_type == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token_type == 1: # TokenType.VAR if not token.contents: raise self.error( token, "Empty variable tag on line %d" % token.lineno ) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token_type == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, "Empty block tag on line %d" % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: raise self.error( token, "%r must be the first tag in the template." % node, ) if not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, "token"): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], "or"), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command), ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ", ".join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop() def prepend_token(self, token): self.tokens.append(token) def delete_first_token(self): del self.tokens[-1] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string "i18n_open": re.escape("_("), "i18n_close": re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )""" % { "constant": constant_string, "num": r"[-+\.]?\d[\d\.e]*", "var_chars": r"\w\.", "filter_sep": re.escape(FILTER_SEPARATOR), "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE) class FilterExpression: """ Parse a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """ __slots__ = ("token", "filters", "var", "is_var") def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError( "Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:]) ) if var_obj is None: if constant := match["constant"]: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif (var := match["var"]) is None: raise TemplateSyntaxError( "Could not find variable at start of %s." % token ) else: var_obj = Variable(var) else: filter_name = match["filter_name"] args = [] if constant_arg := match["constant_arg"]: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg := match["var_arg"]: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError( "Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token) ) self.filters = filters self.var = var_obj self.is_var = isinstance(var_obj, Variable) def resolve(self, context, ignore_failures=False): if self.is_var: try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: string_if_invalid = context.template.engine.string_if_invalid if string_if_invalid: if "%s" in string_if_invalid: return string_if_invalid % self.var else: return string_if_invalid else: obj = string_if_invalid else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, "expects_localtime", False): obj = template_localtime(obj, context.use_tz) if getattr(func, "needs_autoescape", False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, "is_safe", False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. func = inspect.unwrap(func) args, _, _, defaults, _, _, _ = inspect.getfullargspec(func) alen = len(args) dlen = len(defaults or []) # Not enough OR Too many if plen < (alen - dlen) or plen > alen: raise TemplateSyntaxError( "%s requires %d arguments, %d provided" % (name, alen - dlen, plen) ) return True args_check = staticmethod(args_check) def __str__(self): return self.token def __repr__(self): return "<%s %r>" % (self.__class__.__qualname__, self.token) class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ __slots__ = ("var", "literal", "lookups", "translate", "message_context") def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False self.message_context = None if not isinstance(var, str): raise TypeError("Variable must be a string or number, got %s" % type(var)) try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. # Try to interpret values containing a period or an 'e'/'E' # (possibly scientific notation) as a float; otherwise, try int. if "." in var or "e" in var.lower(): self.literal = float(var) # "2." is invalid if var[-1] == ".": raise ValueError else: self.literal = int(var) except ValueError: # A ValueError means that the variable isn't a number. if var[0:2] == "_(" and var[-1] == ")": # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_": raise TemplateSyntaxError( "Variables and attributes may " "not begin with underscores: '%s'" % var ) self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR)) def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already been "resolved" value = self.literal if self.translate: is_safe = isinstance(value, SafeData) msgid = value.replace("%", "%%") msgid = mark_safe(msgid) if is_safe else msgid if self.message_context: return pgettext_lazy(self.message_context, msgid) else: return gettext_lazy(msgid) return value def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.var) def __str__(self): return self.var def _resolve_lookup(self, context): """ Perform resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context try: # catch-all for silent variable failures for bit in self.lookups: try: # dictionary lookup current = current[bit] # ValueError/IndexError are for numpy.array lookup on # numpy < 1.9 and 1.9+ respectively except (TypeError, AttributeError, KeyError, ValueError, IndexError): try: # attribute lookup # Don't return class attributes if the class is the context: if isinstance(current, BaseContext) and getattr( type(current), bit ): raise AttributeError current = getattr(current, bit) except (TypeError, AttributeError): # Reraise if the exception was raised by a @property if not isinstance(current, BaseContext) and bit in dir(current): raise try: # list-index lookup current = current[int(bit)] except ( IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError, ): # unsubscriptable object raise VariableDoesNotExist( "Failed lookup for key [%s] in %r", (bit, current), ) # missing attribute if callable(current): if getattr(current, "do_not_call_in_templates", False): pass elif getattr(current, "alters_data", False): current = context.template.engine.string_if_invalid else: try: # method call (assuming no args required) current = current() except TypeError: try: signature = inspect.signature(current) except ValueError: # No signature found. current = context.template.engine.string_if_invalid else: try: signature.bind() except TypeError: # Arguments *were* required. # Invalid method call. current = context.template.engine.string_if_invalid else: raise except Exception as e: template_name = getattr(context, "template_name", None) or "unknown" logger.debug( "Exception while resolving variable '%s' in template '%s'.", bit, template_name, exc_info=True, ) if getattr(e, "silent_variable_failure", False): current = context.template.engine.string_if_invalid else: raise return current class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ("nodelist",) token = None def render(self, context): """ Return the node rendered as a string. """ pass def render_annotated(self, context): """ Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly. """ try: return self.render(context) except Exception as e: if context.template.engine.debug: # Store the actual node that caused the exception. if not hasattr(e, "_culprit_node"): e._culprit_node = self if ( not hasattr(e, "template_debug") and context.render_context.template.origin == e._culprit_node.origin ): e.template_debug = ( context.render_context.template.get_exception_info( e, e._culprit_node.token, ) ) raise def get_nodes_by_type(self, nodetype): """ Return a list of all nodes (within this node and its nodelist) of the given type """ nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): return SafeString("".join([node.render_annotated(context) for node in self])) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes class TextNode(Node): child_nodelists = () def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s def render_annotated(self, context): """ Return the given value. The default implementation of this method handles exceptions raised during rendering, which is not necessary for text nodes. """ return self.s def render_value_in_context(value, context): """ Convert any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) if context.autoescape: if not issubclass(type(value), str): value = str(value) return conditional_escape(value) else: return str(value) class VariableNode(Node): child_nodelists = () def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail # quietly. return "" return render_value_in_context(output, context) # Regex for token keyword arguments kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ Parse token keyword arguments and return a dictionary of the arguments retrieved from the ``bits`` token list. `bits` is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted. Otherwise, only the standard ``foo=1`` format is allowed. There is no requirement for all remaining token ``bits`` to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached. """ if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match[1] if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != "as": return {} kwargs = {} while bits: if kwarg_format: match = kwarg_re.match(bits[0]) if not match or not match[1]: return kwargs key, value = match.groups() del bits[:1] else: if len(bits) < 3 or bits[1] != "as": return kwargs key, value = bits[2], bits[0] del bits[:3] kwargs[key] = parser.compile_filter(value) if bits and not kwarg_format: if bits[0] != "and": return kwargs del bits[:1] return kwargs
d0159439c902f74ffaef324e0060fd6ecb979de143801fa330af241ab9f53ffe
"""Default tags used by the template system, available to all templates.""" import re import sys import warnings from collections import namedtuple from datetime import datetime from itertools import cycle as itertools_cycle from itertools import groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe from .base import ( BLOCK_TAG_END, BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START, FILTER_SEPARATOR, SINGLE_BRACE_END, SINGLE_BRACE_START, VARIABLE_ATTRIBUTE_SEPARATOR, VARIABLE_TAG_END, VARIABLE_TAG_START, Node, NodeList, TemplateSyntaxError, VariableDoesNotExist, kwarg_re, render_value_in_context, token_kwargs, ) from .context import Context from .defaultfilters import date from .library import Library from .smartif import IfParser, Literal register = Library() class AutoEscapeControlNode(Node): """Implement the actions of the autoescape tag.""" def __init__(self, setting, nodelist): self.setting = setting self.nodelist = nodelist def render(self, context): old_setting = context.autoescape context.autoescape = self.setting output = self.nodelist.render(context) context.autoescape = old_setting if self.setting: 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="csrfmiddlewaretoken" value="{}">', csrf_token, ) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning 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." ) return "" class CycleNode(Node): def __init__(self, cyclevars, variable_name=None, silent=False): self.cyclevars = cyclevars self.variable_name = variable_name self.silent = silent def render(self, context): if self not in context.render_context: # First time the node is rendered in template context.render_context[self] = itertools_cycle(self.cyclevars) cycle_iter = context.render_context[self] value = next(cycle_iter).resolve(context) if self.variable_name: context.set_upward(self.variable_name, value) if self.silent: return "" return render_value_in_context(value, context) def reset(self, context): """ Reset the cycle iteration back to the beginning. """ context.render_context[self] = itertools_cycle(self.cyclevars) class DebugNode(Node): def render(self, context): if not settings.DEBUG: return "" from pprint import pformat output = [escape(pformat(val)) for val in context] output.append("\n\n") output.append(escape(pformat(sys.modules))) return "".join(output) class FilterNode(Node): def __init__(self, filter_expr, nodelist): self.filter_expr = filter_expr self.nodelist = nodelist def render(self, context): output = self.nodelist.render(context) # Apply filters. with context.push(var=output): return self.filter_expr.resolve(context) class FirstOfNode(Node): def __init__(self, variables, asvar=None): self.vars = variables self.asvar = asvar def render(self, context): first = "" for var in self.vars: value = var.resolve(context, ignore_failures=True) if value: first = render_value_in_context(value, context) break if self.asvar: context[self.asvar] = first return "" return first class ForNode(Node): child_nodelists = ("nodelist_loop", "nodelist_empty") def __init__( self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None ): self.loopvars = loopvars self.sequence = sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty def __repr__(self): reversed_text = " reversed" if self.is_reversed else "" return "<%s: for %s in %s, tail_len: %d%s>" % ( self.__class__.__name__, ", ".join(self.loopvars), self.sequence, len(self.nodelist_loop), reversed_text, ) def render(self, context): if "forloop" in context: parentloop = context["forloop"] else: parentloop = {} with context.push(): values = self.sequence.resolve(context, ignore_failures=True) if values is None: values = [] if not hasattr(values, "__len__"): values = list(values) len_values = len(values) if len_values < 1: return self.nodelist_empty.render(context) nodelist = [] if self.is_reversed: values = reversed(values) num_loopvars = len(self.loopvars) unpack = num_loopvars > 1 # Create a forloop value in the context. We'll update counters on each # iteration just below. loop_dict = context["forloop"] = {"parentloop": parentloop} for i, item in enumerate(values): # Shortcuts for current loop iteration number. loop_dict["counter0"] = i loop_dict["counter"] = i + 1 # Reverse counter iteration numbers. loop_dict["revcounter"] = len_values - i loop_dict["revcounter0"] = len_values - i - 1 # Boolean values designating first and last times through loop. loop_dict["first"] = i == 0 loop_dict["last"] = i == len_values - 1 pop_context = False if unpack: # If there are multiple loop variables, unpack the item into # them. try: len_item = len(item) except TypeError: # not an iterable len_item = 1 # Check loop variable count before unpacking if num_loopvars != len_item: raise ValueError( "Need {} values to unpack in for loop; got {}. ".format( num_loopvars, len_item ), ) unpacked_vars = dict(zip(self.loopvars, item)) pop_context = True context.update(unpacked_vars) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render_annotated(context)) if pop_context: # Pop the loop variables pushed on to the context to avoid # the context ending up in an inconsistent state when other # tags (e.g., include and with) push data to context. context.pop() return mark_safe("".join(nodelist)) class IfChangedNode(Node): child_nodelists = ("nodelist_true", "nodelist_false") def __init__(self, nodelist_true, nodelist_false, *varlist): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false self._varlist = varlist def render(self, context): # Init state storage state_frame = self._get_context_stack_frame(context) state_frame.setdefault(self) nodelist_true_output = None if self._varlist: # Consider multiple parameters. This behaves like an OR evaluation # of the multiple variables. compare_to = [ var.resolve(context, ignore_failures=True) for var in self._varlist ] else: # The "{% ifchanged %}" syntax (without any variables) compares # the rendered output. compare_to = nodelist_true_output = self.nodelist_true.render(context) if compare_to != state_frame[self]: state_frame[self] = compare_to # render true block if not already rendered return nodelist_true_output or self.nodelist_true.render(context) elif self.nodelist_false: return self.nodelist_false.render(context) return "" def _get_context_stack_frame(self, context): # The Context object behaves like a stack where each template tag can # create a new scope. Find the place where to store the state to detect # changes. if "forloop" in context: # Ifchanged is bound to the local for loop. # When there is a loop-in-loop, the state is bound to the inner loop, # so it resets when the outer loop continues. return context["forloop"] else: # Using ifchanged outside loops. Effectively this is a no-op # because the state is associated with 'self'. return context.render_context class IfNode(Node): def __init__(self, conditions_nodelists): self.conditions_nodelists = conditions_nodelists def __repr__(self): return "<%s>" % self.__class__.__name__ def __iter__(self): for _, nodelist in self.conditions_nodelists: yield from nodelist @property def nodelist(self): return NodeList(self) def render(self, context): for condition, nodelist in self.conditions_nodelists: if condition is not None: # if / elif clause try: match = condition.eval(context) except VariableDoesNotExist: match = None else: # else clause match = True if match: return nodelist.render(context) return "" class LoremNode(Node): def __init__(self, count, method, common): self.count = count self.method = method self.common = common def render(self, context): try: count = int(self.count.resolve(context)) except (ValueError, TypeError): count = 1 if self.method == "w": return words(count, common=self.common) else: paras = paragraphs(count, common=self.common) if self.method == "p": paras = ["<p>%s</p>" % p for p in paras] return "\n\n".join(paras) GroupedResult = namedtuple("GroupedResult", ["grouper", "list"]) class RegroupNode(Node): def __init__(self, target, expression, var_name): self.target = target self.expression = expression self.var_name = var_name def resolve_expression(self, obj, context): # This method is called for each object in self.target. See regroup() # for the reason why we temporarily put the object in the context. context[self.var_name] = obj return self.expression.resolve(context, ignore_failures=True) def render(self, context): obj_list = self.target.resolve(context, ignore_failures=True) if obj_list is None: # target variable wasn't found in context; fail silently. context[self.var_name] = [] return "" # List of dictionaries in the format: # {'grouper': 'key', 'list': [list of contents]}. context[self.var_name] = [ GroupedResult(grouper=key, list=list(val)) for key, val in groupby( obj_list, lambda obj: self.resolve_expression(obj, context) ) ] return "" class LoadNode(Node): child_nodelists = () def render(self, context): return "" class NowNode(Node): def __init__(self, format_string, asvar=None): self.format_string = format_string self.asvar = asvar def render(self, context): tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None formatted = date(datetime.now(tz=tzinfo), self.format_string) if self.asvar: context[self.asvar] = formatted return "" else: return formatted class ResetCycleNode(Node): def __init__(self, node): self.node = node def render(self, context): self.node.reset(context) return "" class SpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): from django.utils.html import strip_spaces_between_tags return strip_spaces_between_tags(self.nodelist.render(context).strip()) class TemplateTagNode(Node): mapping = { "openblock": BLOCK_TAG_START, "closeblock": BLOCK_TAG_END, "openvariable": VARIABLE_TAG_START, "closevariable": VARIABLE_TAG_END, "openbrace": SINGLE_BRACE_START, "closebrace": SINGLE_BRACE_END, "opencomment": COMMENT_TAG_START, "closecomment": COMMENT_TAG_END, } def __init__(self, tagtype): self.tagtype = tagtype def render(self, context): return self.mapping.get(self.tagtype, "") class URLNode(Node): child_nodelists = () def __init__(self, view_name, args, kwargs, asvar): self.view_name = view_name self.args = args self.kwargs = kwargs self.asvar = asvar def __repr__(self): return "<%s view_name='%s' args=%s kwargs=%s as=%s>" % ( self.__class__.__qualname__, self.view_name, repr(self.args), repr(self.kwargs), repr(self.asvar), ) def render(self, context): from django.urls import NoReverseMatch, reverse args = [arg.resolve(context) for arg in self.args] kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} view_name = self.view_name.resolve(context) try: current_app = context.request.current_app except AttributeError: try: current_app = context.request.resolver_match.namespace except AttributeError: current_app = None # Try to look up the URL. If it fails, raise NoReverseMatch unless the # {% url ... as var %} construct is used, in which case return nothing. url = "" try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch: if self.asvar is None: raise if self.asvar: context[self.asvar] = url return "" else: if context.autoescape: url = conditional_escape(url) return url class VerbatimNode(Node): def __init__(self, content): self.content = content def render(self, context): return self.content class WidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width, asvar=None): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width self.asvar = asvar def render(self, context): try: value = self.val_expr.resolve(context) max_value = self.max_expr.resolve(context) max_width = int(self.max_width.resolve(context)) except VariableDoesNotExist: return "" except (ValueError, TypeError): raise TemplateSyntaxError("widthratio final argument must be a number") try: value = float(value) max_value = float(max_value) ratio = (value / max_value) * max_width result = str(round(ratio)) except ZeroDivisionError: result = "0" except (ValueError, TypeError, OverflowError): result = "" if self.asvar: context[self.asvar] = result return "" else: return result class WithNode(Node): def __init__(self, var, name, nodelist, extra_context=None): self.nodelist = nodelist # var and name are legacy attributes, being left in case they are used # by third-party subclasses of this Node. self.extra_context = extra_context or {} if name: self.extra_context[name] = var def __repr__(self): return "<%s>" % self.__class__.__name__ def render(self, context): values = {key: val.resolve(context) for key, val in self.extra_context.items()} with context.push(**values): return self.nodelist.render(context) @register.tag def autoescape(parser, token): """ Force autoescape behavior for this block. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") arg = args[1] if arg not in ("on", "off"): raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(("endautoescape",)) parser.delete_first_token() return AutoEscapeControlNode((arg == "on"), nodelist) @register.tag def comment(parser, token): """ Ignore everything between ``{% comment %}`` and ``{% endcomment %}``. """ parser.skip_past("endcomment") return CommentNode() @register.tag def cycle(parser, token): """ Cycle among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% for o in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr> {% endfor %} """ # Note: This returns the exact same node on each {% cycle name %} call; # that is, the node object returned from {% cycle a b c as name %} and the # one returned from {% cycle name %} are the exact same object. This # shouldn't cause problems (heh), but if it does, now you know. # # Ugly hack warning: This stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. # # It keeps the last node in the parser to be able to reset it with # {% resetcycle %}. args = token.split_contents() if len(args) < 2: raise TemplateSyntaxError("'cycle' tag requires at least two arguments") if len(args) == 2: # {% cycle foo %} case. name = args[1] if not hasattr(parser, "_named_cycle_nodes"): raise TemplateSyntaxError( "No named cycles in template. '%s' is not defined" % name ) if name not in parser._named_cycle_nodes: raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._named_cycle_nodes[name] as_form = False if len(args) > 4: # {% cycle ... as foo [silent] %} case. if args[-3] == "as": if args[-1] != "silent": raise TemplateSyntaxError( "Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1] ) as_form = True silent = True args = args[:-1] elif args[-2] == "as": as_form = True silent = False if as_form: name = args[-1] values = [parser.compile_filter(arg) for arg in args[1:-2]] node = CycleNode(values, name, silent=silent) if not hasattr(parser, "_named_cycle_nodes"): parser._named_cycle_nodes = {} parser._named_cycle_nodes[name] = node else: values = [parser.compile_filter(arg) for arg in args[1:]] node = CycleNode(values) parser._last_cycle_node = node return node @register.tag def csrf_token(parser, token): return CsrfTokenNode() @register.tag def debug(parser, token): """ Output a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ return DebugNode() @register.tag("filter") def do_filter(parser, token): """ Filter the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %} Note that the ``escape`` and ``safe`` filters are not acceptable arguments. Instead, use the ``autoescape`` tag to manage autoescaping for blocks of template code. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) for func, unused in filter_expr.filters: filter_name = getattr(func, "_filter_name", None) if filter_name in ("escape", "safe"): raise TemplateSyntaxError( '"filter %s" is not permitted. Use the "autoescape" tag instead.' % filter_name ) nodelist = parser.parse(("endfilter",)) parser.delete_first_token() return FilterNode(filter_expr, nodelist) @register.tag def firstof(parser, token): """ Output the first variable passed that is not False. Output nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 as myvar %} This is equivalent to:: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %} but much cleaner! You can also use a literal string as a fallback value in case all passed variables are False:: {% firstof var1 var2 var3 "fallback value" %} If you want to disable auto-escaping of variables you can use:: {% autoescape off %} {% firstof var1 var2 var3 "<strong>fallback value</strong>" %} {% autoescape %} Or if only some variables should be escaped, you can use:: {% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %} """ bits = token.split_contents()[1:] asvar = None if not bits: raise TemplateSyntaxError("'firstof' statement requires at least one argument") if len(bits) >= 2 and bits[-2] == "as": asvar = bits[-1] bits = bits[:-2] return FirstOfNode([parser.compile_filter(bit) for bit in bits], asvar) @register.tag("for") def do_for(parser, token): """ Loop over each item in an array. For example, to display a list of athletes given ``athlete_list``:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> You can loop over a list in reverse by using ``{% for obj in list reversed %}``. You can also unpack multiple values from a two-dimensional array:: {% for key,value in dict.items %} {{ key }}: {{ value }} {% endfor %} The ``for`` tag can take an optional ``{% empty %}`` clause that will be displayed if the given array is empty or could not be found:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} <ul> The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:: <ul> {% if athlete_list %} {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} {% else %} <li>Sorry, no athletes in this list.</li> {% endif %} </ul> The for loop sets a number of variables available within the loop: ========================== ================================================ Variable Description ========================== ================================================ ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop "above" the current one ========================== ================================================ """ bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "'for' statements should have at least four words: %s" % token.contents ) is_reversed = bits[-1] == "reversed" in_index = -3 if is_reversed else -2 if bits[in_index] != "in": raise TemplateSyntaxError( "'for' statements should use the format" " 'for x in y': %s" % token.contents ) invalid_chars = frozenset((" ", '"', "'", FILTER_SEPARATOR)) loopvars = re.split(r" *, *", " ".join(bits[1:in_index])) for var in loopvars: if not var or not invalid_chars.isdisjoint(var): raise TemplateSyntaxError( "'for' tag received an invalid argument: %s" % token.contents ) sequence = parser.compile_filter(bits[in_index + 1]) nodelist_loop = parser.parse( ( "empty", "endfor", ) ) token = parser.next_token() if token.contents == "empty": nodelist_empty = parser.parse(("endfor",)) parser.delete_first_token() else: nodelist_empty = None return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty) class TemplateLiteral(Literal): def __init__(self, value, text): self.value = value self.text = text # for better error messages def display(self): return self.text def eval(self, context): return self.value.resolve(context, ignore_failures=True) class TemplateIfParser(IfParser): error_class = TemplateSyntaxError def __init__(self, parser, *args, **kwargs): self.template_parser = parser super().__init__(*args, **kwargs) def create_var(self, value): return TemplateLiteral(self.template_parser.compile_filter(value), value) @register.tag("if") def do_if(parser, token): """ Evaluate a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), output the contents of the block: :: {% if athlete_list %} Number of athletes: {{ athlete_list|count }} {% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon! {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as an ``{% else %}`` clause that will be displayed if all previous conditions fail. These clauses are optional. ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of variables or to negate a given variable:: {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %} Comparison operators are also available, and the use of filters is also allowed, for example:: {% if articles|length >= 5 %}...{% endif %} Arguments and operators _must_ have a space between them, so ``{% if 1>2 %}`` is not a valid if tag. All supported operators are: ``or``, ``and``, ``in``, ``not in`` ``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``. Operator precedence follows Python. """ # {% if ... %} bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(("elif", "else", "endif")) conditions_nodelists = [(condition, nodelist)] token = parser.next_token() # {% elif ... %} (repeatable) while token.contents.startswith("elif"): bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(("elif", "else", "endif")) conditions_nodelists.append((condition, nodelist)) token = parser.next_token() # {% else %} (optional) if token.contents == "else": nodelist = parser.parse(("endif",)) conditions_nodelists.append((None, nodelist)) token = parser.next_token() # {% endif %} if token.contents != "endif": raise TemplateSyntaxError( 'Malformed template tag at line {}: "{}"'.format( token.lineno, token.contents ) ) return IfNode(conditions_nodelists) @register.tag def ifchanged(parser, token): """ Check if a value has changed from the last iteration of a loop. The ``{% ifchanged %}`` block tag is used within a loop. It has two possible uses. 1. Check its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:: <h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %} 2. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:: {% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %} """ bits = token.split_contents() nodelist_true = parser.parse(("else", "endifchanged")) token = parser.next_token() if token.contents == "else": nodelist_false = parser.parse(("endifchanged",)) parser.delete_first_token() else: nodelist_false = NodeList() values = [parser.compile_filter(bit) for bit in bits[1:]] return IfChangedNode(nodelist_true, nodelist_false, *values) def find_library(parser, name): try: return parser.libraries[name] except KeyError: raise TemplateSyntaxError( "'%s' is not a registered tag library. Must be one of:\n%s" % ( name, "\n".join(sorted(parser.libraries)), ), ) def load_from_library(library, label, names): """ Return a subset of tags and filters from a library. """ subset = Library() for name in names: found = False if name in library.tags: found = True subset.tags[name] = library.tags[name] if name in library.filters: found = True subset.filters[name] = library.filters[name] if found is False: raise TemplateSyntaxError( "'%s' is not a valid tag or filter in tag library '%s'" % ( name, label, ), ) return subset @register.tag def load(parser, token): """ Load a custom template tag library into the parser. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} Can also be used to load an individual tag/filter from a library:: {% load byline from news %} """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": # from syntax is used; load individual tags from the library name = bits[-1] lib = find_library(parser, name) subset = load_from_library(lib, name, bits[1:-2]) parser.add_library(subset) else: # one or more libraries are specified; load and add them to the parser for name in bits[1:]: lib = find_library(parser, name) parser.add_library(lib) return LoadNode() @register.tag def lorem(parser, token): """ Create random Latin text useful for providing test data in templates. Usage format:: {% lorem [count] [method] [random] %} ``count`` is a number (or variable) containing the number of paragraphs or words to generate (default is 1). ``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for plain-text paragraph blocks (default is ``b``). ``random`` is the word ``random``, which if given, does not use the common paragraph (starting "Lorem ipsum dolor sit amet, consectetuer..."). Examples: * ``{% lorem %}`` outputs the common "lorem ipsum" paragraph * ``{% lorem 3 p %}`` outputs the common "lorem ipsum" paragraph and two random paragraphs each wrapped in HTML ``<p>`` tags * ``{% lorem 2 w random %}`` outputs two random latin words """ bits = list(token.split_contents()) tagname = bits[0] # Random bit common = bits[-1] != "random" if not common: bits.pop() # Method bit if bits[-1] in ("w", "p", "b"): method = bits.pop() else: method = "b" # Count bit if len(bits) > 1: count = bits.pop() else: count = "1" count = parser.compile_filter(count) if len(bits) != 1: raise TemplateSyntaxError("Incorrect format for %r tag" % tagname) return LoremNode(count, method, common) @register.tag def now(parser, token): """ Display the date, formatted according to the given string. Use the same format as PHP's ``date()`` function; see https://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ bits = token.split_contents() asvar = None if len(bits) == 4 and bits[-2] == "as": asvar = bits[-1] bits = bits[:-2] if len(bits) != 2: raise TemplateSyntaxError("'now' statement takes one argument") format_string = bits[1][1:-1] return NowNode(format_string, asvar) @register.tag def regroup(parser, token): """ Regroup a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``musicians`` is a list of ``Musician`` objects that have ``name`` and ``instrument`` attributes, and you'd like to display a list that looks like: * Guitar: * Django Reinhardt * Emily Remler * Piano: * Lovie Austin * Bud Powell * Trumpet: * Duke Ellington The following snippet of template code would accomplish this dubious task:: {% regroup musicians by instrument as grouped %} <ul> {% for group in grouped %} <li>{{ group.grouper }} <ul> {% for musician in group.list %} <li>{{ musician.name }}</li> {% endfor %} </ul> {% endfor %} </ul> As you can see, ``{% regroup %}`` populates a variable with a list of objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the item that was grouped by; ``list`` contains the list of objects that share that ``grouper``. In this case, ``grouper`` would be ``Guitar``, ``Piano`` and ``Trumpet``, and ``list`` is the list of musicians who play this instrument. Note that ``{% regroup %}`` does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of musicians was not sorted by instrument, you'd need to make sure it is sorted before using it, i.e.:: {% regroup musicians|dictsort:"instrument" by instrument as grouped %} """ bits = token.split_contents() if len(bits) != 6: raise TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(bits[1]) if bits[2] != "by": raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") if bits[4] != "as": raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must be 'as'") var_name = bits[5] # RegroupNode will take each item in 'target', put it in the context under # 'var_name', evaluate 'var_name'.'expression' in the current context, and # group by the resulting value. After all items are processed, it will # save the final result in the context under 'var_name', thus clearing the # temporary values. This hack is necessary because the template engine # doesn't provide a context-aware equivalent of Python's getattr. expression = parser.compile_filter( var_name + VARIABLE_ATTRIBUTE_SEPARATOR + bits[3] ) return RegroupNode(target, expression, var_name) @register.tag def resetcycle(parser, token): """ Reset a cycle tag. If an argument is given, reset the last rendered cycle tag whose name matches the argument, else reset the last rendered cycle tag (named or unnamed). """ args = token.split_contents() if len(args) > 2: raise TemplateSyntaxError("%r tag accepts at most one argument." % args[0]) if len(args) == 2: name = args[1] try: return ResetCycleNode(parser._named_cycle_nodes[name]) except (AttributeError, KeyError): raise TemplateSyntaxError("Named cycle '%s' does not exist." % name) try: return ResetCycleNode(parser._last_cycle_node) except AttributeError: raise TemplateSyntaxError("No cycles in template.") @register.tag def spaceless(parser, token): """ Remove whitespace between HTML tags, including tab and newline characters. Example usage:: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example returns this HTML:: <p><a href="foo/">Foo</a></p> Only space between *tags* is normalized -- not space between tags and text. In this example, the space around ``Hello`` isn't stripped:: {% spaceless %} <strong> Hello </strong> {% endspaceless %} """ nodelist = parser.parse(("endspaceless",)) parser.delete_first_token() return SpacelessNode(nodelist) @register.tag def templatetag(parser, token): """ Output one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== ======= """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'templatetag' statement takes one argument") tag = bits[1] if tag not in TemplateTagNode.mapping: raise TemplateSyntaxError( "Invalid templatetag argument: '%s'." " Must be one of: %s" % (tag, list(TemplateTagNode.mapping)) ) return TemplateTagNode(tag) @register.tag def url(parser, token): r""" Return an absolute URL matching the given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url "url_name" arg1 arg2 %} or {% url "url_name" name1=value1 name2=value2 %} The first argument is a URL pattern name. Other arguments are space-separated values that will be filled in place of positional and keyword arguments in the URL. Don't mix positional and keyword arguments. All arguments for the URL must be present. For example, if you have a view ``app_name.views.client_details`` taking the client's id and the corresponding line in a URLconf looks like this:: path('client/<int:id>/', views.client_details, name='client-detail-view') and this app's URLconf is included into the project's URLconf under some path:: path('clients/', include('app_name.urls')) then in a template you can create a link for a certain client like this:: {% url "client-detail-view" client.id %} The URL will look like ``/clients/client/123/``. The first argument may also be the name of a template variable that will be evaluated to obtain the view name or the URL name, e.g.:: {% with url_name="client-detail-view" %} {% url url_name client.id %} {% endwith %} """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError( "'%s' takes at least one argument, a URL pattern name." % bits[0] ) viewname = parser.compile_filter(bits[1]) args = [] kwargs = {} asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == "as": asvar = bits[-1] bits = bits[:-2] for bit in bits: match = kwarg_re.match(bit) if not match: raise TemplateSyntaxError("Malformed arguments to url tag") name, value = match.groups() if name: kwargs[name] = parser.compile_filter(value) else: args.append(parser.compile_filter(value)) return URLNode(viewname, args, kwargs, asvar) @register.tag def verbatim(parser, token): """ Stop the template engine from rendering the contents of this block tag. Usage:: {% verbatim %} {% don't process this %} {% endverbatim %} You can also designate a specific closing tag block (allowing the unrendered use of ``{% endverbatim %}``):: {% verbatim myblock %} ... {% endverbatim myblock %} """ nodelist = parser.parse(("endverbatim",)) parser.delete_first_token() return VerbatimNode(nodelist.render(Context())) @register.tag def widthratio(parser, token): """ For creating bar charts and such. Calculate the ratio of a given value to a maximum value, and then apply that ratio to a constant. For example:: <img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value max_width %}"> If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). In some cases you might want to capture the result of widthratio in a variable. It can be useful for instance in a blocktranslate like this:: {% widthratio this_value max_value max_width as width %} {% blocktranslate %}The width is: {{ width }}{% endblocktranslate %} """ bits = token.split_contents() if len(bits) == 4: tag, this_value_expr, max_value_expr, max_width = bits asvar = None elif len(bits) == 6: tag, this_value_expr, max_value_expr, max_width, as_, asvar = bits if as_ != "as": raise TemplateSyntaxError( "Invalid syntax in widthratio tag. Expecting 'as' keyword" ) else: raise TemplateSyntaxError("widthratio takes at least three arguments") return WidthRatioNode( parser.compile_filter(this_value_expr), parser.compile_filter(max_value_expr), parser.compile_filter(max_width), asvar=asvar, ) @register.tag("with") def do_with(parser, token): """ Add one or more values to the context (inside of this block) for caching and easy access. For example:: {% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %} Multiple values can be added to the context:: {% with foo=1 bar=2 %} ... {% endwith %} The legacy format of ``{% with person.some_sql_method as total %}`` is still accepted. """ bits = token.split_contents() remaining_bits = bits[1:] extra_context = token_kwargs(remaining_bits, parser, support_legacy=True) if not extra_context: raise TemplateSyntaxError( "%r expected at least one variable assignment" % bits[0] ) if remaining_bits: raise TemplateSyntaxError( "%r received an invalid token: %r" % (bits[0], remaining_bits[0]) ) nodelist = parser.parse(("endwith",)) parser.delete_first_token() return WithNode(None, None, nodelist, extra_context=extra_context)
3967cfd54ce679490dc43ddabc10231347fefff7bc97974db239f4d4cd8e6cd8
"""Default variable filters.""" import random as random_module import re import types import warnings from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation, getcontext from functools import wraps from inspect import unwrap from operator import itemgetter from pprint import pformat from urllib.parse import quote from django.utils import formats from django.utils.dateformat import format, time_format from django.utils.deprecation import RemovedInDjango51Warning from django.utils.encoding import iri_to_uri from django.utils.html import avoid_wrapping, conditional_escape, escape, escapejs from django.utils.html import json_script as _json_script from django.utils.html import linebreaks, strip_tags from django.utils.html import urlize as _urlize from django.utils.safestring import SafeData, mark_safe from django.utils.text import Truncator, normalize_newlines, phone2numeric 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 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(unwrap(func), "is_safe", False): result = mark_safe(result) return result return _dec ################### # STRINGS # ################### @register.filter(is_safe=True) @stringfilter def addslashes(value): """ Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace("\\", "\\\\").replace('"', '\\"').replace("'", "\\'") @register.filter(is_safe=True) @stringfilter def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:] @register.filter("escapejs") @stringfilter def escapejs_filter(value): """Hex encode characters for use in JavaScript strings.""" return escapejs(value) @register.filter(is_safe=True) def json_script(value, element_id=None): """ Output value JSON-encoded, wrapped in a <script type="application/json"> tag (with an optional id). """ return _json_script(value, element_id) @register.filter(is_safe=True) def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If arg has the 'g' suffix, force the result to be grouped by the THOUSAND_SEPARATOR for the active locale. When the active locale is en (English): * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67" * {{ 10000|floatformat:"g" }} displays "10,000" If arg has the 'u' suffix, force the result to be unlocalized. When the active locale is pl (Polish): * {{ 66666.6666|floatformat:"2" }} displays "66666,67" * {{ 66666.6666|floatformat:"2u" }} displays "66666.67" If the input float is infinity or NaN, display the string representation of that value. """ force_grouping = False use_l10n = True if isinstance(arg, str): last_char = arg[-1] if arg[-2:] in {"gu", "ug"}: force_grouping = True use_l10n = False arg = arg[:-2] or -1 elif last_char == "g": force_grouping = True arg = arg[:-1] or -1 elif last_char == "u": use_l10n = False arg = arg[:-1] or -1 try: input_val = str(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return "" try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p <= 0: return mark_safe( formats.number_format( "%d" % (int(d)), 0, use_l10n=use_l10n, force_grouping=force_grouping, ) ) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 prec = max(getcontext().prec, prec) # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)) sign, digits, exponent = rounded_d.as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append("0") digits.insert(-exponent, ".") if sign and rounded_d: digits.append("-") number = "".join(reversed(digits)) return mark_safe( formats.number_format( number, abs(p), use_l10n=use_l10n, force_grouping=force_grouping, ) ) @register.filter(is_safe=True) @stringfilter def iriencode(value): """Escape an IRI value for use in a URL.""" return iri_to_uri(value) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linenumbers(value, autoescape=True): """Display text with line numbers.""" lines = value.split("\n") # Find the maximum width of the line count, for use with zero padding # string format command width = str(len(str(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return mark_safe("\n".join(lines)) @register.filter(is_safe=True) @stringfilter def lower(value): """Convert a string into all lowercase.""" return value.lower() @register.filter(is_safe=False) @stringfilter def make_list(value): """ Return the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) @register.filter(is_safe=True) @stringfilter def slugify(value): """ Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ return _slugify(value) @register.filter(is_safe=True) def stringformat(value, arg): """ Format the variable according to the arg, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading "%" is dropped. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting for documentation of Python string formatting. """ if isinstance(value, tuple): value = str(value) try: return ("%" + str(arg)) % value except (ValueError, TypeError): return "" @register.filter(is_safe=True) @stringfilter def title(value): """Convert a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m[0].lower(), value.title()) return re.sub(r"\d([A-Z])", lambda m: m[0].lower(), t) @register.filter(is_safe=True) @stringfilter def truncatechars(value, arg): """Truncate a string after `arg` number of characters.""" try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).chars(length) @register.filter(is_safe=True) @stringfilter def truncatechars_html(value, arg): """ Truncate HTML after `arg` number of chars. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).chars(length, html=True) @register.filter(is_safe=True) @stringfilter def truncatewords(value, arg): """ Truncate a string after `arg` number of words. Remove newlines within the string. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).words(length, truncate=" …") @register.filter(is_safe=True) @stringfilter def truncatewords_html(value, arg): """ Truncate HTML after `arg` number of words. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).words(length, html=True, truncate=" …") @register.filter(is_safe=False) @stringfilter def upper(value): """Convert a string into all uppercase.""" return value.upper() @register.filter(is_safe=False) @stringfilter def urlencode(value, safe=None): """ Escape a value for use in a URL. The ``safe`` parameter determines the characters which should not be escaped by Python's quote() function. If not provided, use the default safe characters (but an empty string can be provided when *all* characters should be escaped). """ kwargs = {} if safe is not None: kwargs["safe"] = safe return quote(value, **kwargs) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlize(value, autoescape=True): """Convert URLs in plain text into clickable links.""" return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlizetrunc(value, limit, autoescape=True): """ Convert URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe( _urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape) ) @register.filter(is_safe=False) @stringfilter def wordcount(value): """Return the number of words.""" return len(value.split()) @register.filter(is_safe=True) @stringfilter def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg)) @register.filter(is_safe=True) @stringfilter def ljust(value, arg): """Left-align the value in a field of a given width.""" return value.ljust(int(arg)) @register.filter(is_safe=True) @stringfilter def rjust(value, arg): """Right-align the value in a field of a given width.""" return value.rjust(int(arg)) @register.filter(is_safe=True) @stringfilter def center(value, arg): """Center the value in a field of a given width.""" return value.center(int(arg)) @register.filter @stringfilter def cut(value, arg): """Remove all values of arg from the given string.""" safe = isinstance(value, SafeData) value = value.replace(arg, "") if safe and arg != ";": return mark_safe(value) return value ################### # HTML STRINGS # ################### @register.filter("escape", is_safe=True) @stringfilter def escape_filter(value): """Mark the value as a string that should be auto-escaped.""" return conditional_escape(value) @register.filter(is_safe=True) @stringfilter def force_escape(value): """ Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value) @register.filter("linebreaks", is_safe=True, needs_autoescape=True) @stringfilter def linebreaks_filter(value, autoescape=True): """ Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linebreaksbr(value, autoescape=True): """ Convert all newlines in a piece of plain text to HTML line breaks (``<br>``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(value.replace("\n", "<br>")) @register.filter(is_safe=True) @stringfilter def safe(value): """Mark the value as a string that should not be auto-escaped.""" return mark_safe(value) @register.filter(is_safe=True) def safeseq(value): """ A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. """ return [mark_safe(obj) for obj in value] @register.filter(is_safe=True) @stringfilter def striptags(value): """Strip all [X]HTML tags.""" return strip_tags(value) ################### # LISTS # ################### def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14 """ try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in arg or arg[0] == "_": raise AttributeError("Access to private variables is forbidden.") parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): for part in parts: try: value = value[part] except (AttributeError, IndexError, KeyError, TypeError, ValueError): value = getattr(value, part) return value return resolve else: return itemgetter(arg) @register.filter(is_safe=False) def dictsort(value, arg): """ Given a list of dicts, return that list sorted by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def dictsortreversed(value, arg): """ Given a list of dicts, return that list sorted in reverse order by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def first(value): """Return the first item in a list.""" try: return value[0] except IndexError: return "" @register.filter(is_safe=True, needs_autoescape=True) def join(value, arg, autoescape=True): """Join a list with a string, like Python's ``str.join(list)``.""" try: if autoescape: data = conditional_escape(arg).join([conditional_escape(v) for v in value]) else: data = arg.join(value) except TypeError: # Fail silently if arg isn't iterable. return value return mark_safe(data) @register.filter(is_safe=True) def last(value): """Return the last item in a list.""" try: return value[-1] except IndexError: return "" @register.filter(is_safe=False) def length(value): """Return the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return 0 @register.filter(is_safe=False) def length_is(value, arg): """Return a boolean of whether the value's length is the argument.""" warnings.warn( "The length_is template filter is deprecated in favor of the length template " "filter and the == operator within an {% if %} tag.", RemovedInDjango51Warning, ) try: return len(value) == int(arg) except (ValueError, TypeError): return "" @register.filter(is_safe=True) def random(value): """Return a random item from the list.""" try: return random_module.choice(value) except IndexError: return "" @register.filter("slice", is_safe=True) def slice_filter(value, arg): """ Return a slice of the list using the same syntax as Python's list slicing. """ try: bits = [] for x in str(arg).split(":"): if not x: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. @register.filter(is_safe=True, needs_autoescape=True) def unordered_list(value, autoescape=True): """ Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` returns:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: escaper = conditional_escape else: def escaper(x): return x def walk_items(item_list): item_iterator = iter(item_list) try: item = next(item_iterator) while True: try: next_item = next(item_iterator) except StopIteration: yield item, None break if isinstance(next_item, (list, tuple, types.GeneratorType)): try: iter(next_item) except TypeError: pass else: yield item, next_item item = next(item_iterator) continue yield item, None item = next_item except StopIteration: pass def list_formatter(item_list, tabs=1): indent = "\t" * tabs output = [] for item, children in walk_items(item_list): sublist = "" if children: sublist = "\n%s<ul>\n%s\n%s</ul>\n%s" % ( indent, list_formatter(children, tabs + 1), indent, indent, ) output.append("%s<li>%s%s</li>" % (indent, escaper(item), sublist)) return "\n".join(output) return mark_safe(list_formatter(value)) ################### # INTEGERS # ################### @register.filter(is_safe=False) def add(value, arg): """Add the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except Exception: return "" @register.filter(is_safe=False) def get_digit(value, arg): """ Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 ################### # DATES # ################### @register.filter(expects_localtime=True, is_safe=False) def date(value, arg=None): """Format a date according to the given format.""" if value in (None, ""): return "" try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return "" @register.filter(expects_localtime=True, is_safe=False) def time(value, arg=None): """Format a time according to the given format.""" if value in (None, ""): return "" try: return formats.time_format(value, arg) except (AttributeError, TypeError): try: return time_format(value, arg) except (AttributeError, TypeError): return "" @register.filter("timesince", is_safe=False) def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return "" try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return "" @register.filter("timeuntil", is_safe=False) def timeuntil_filter(value, arg=None): """Format a date as the time until that date (i.e. "4 days, 6 hours").""" if not value: return "" try: return timeuntil(value, arg) except (ValueError, TypeError): return "" ################### # LOGIC # ################### @register.filter(is_safe=False) def default(value, arg): """If value is unavailable, use given default.""" return value or arg @register.filter(is_safe=False) def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value @register.filter(is_safe=False) def divisibleby(value, arg): """Return True if the value is divisible by the argument.""" return int(value) % int(arg) == 0 @register.filter(is_safe=False) def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: # Translators: Please do not add spaces around commas. arg = gettext("yes,no,maybe") bits = arg.split(",") if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ################### @register.filter(is_safe=True) def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = int(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {"size": bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value) @register.filter(is_safe=False) def pluralize(value, arg="s"): """ Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value|pluralize }} display "votes". If an argument is provided, use that string instead: * If value is 0, class{{ value|pluralize:"es" }} display "classes". * If value is 1, class{{ value|pluralize:"es" }} display "class". * If value is 2, class{{ value|pluralize:"es" }} display "classes". If the provided argument contains a comma, use the text before the comma for the singular case and the text after the comma for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies". """ if "," not in arg: arg = "," + arg bits = arg.split(",") if len(bits) > 2: return "" singular_suffix, plural_suffix = bits[:2] try: return singular_suffix if float(value) == 1 else plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: return singular_suffix if len(value) == 1 else plural_suffix except TypeError: # len() of unsized object. pass return "" @register.filter("phone2numeric", is_safe=True) def phone2numeric_filter(value): """Take a phone number and converts it in to its numerical equivalent.""" return phone2numeric(value) @register.filter(is_safe=True) def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) except Exception as e: return "Error in formatting: %s: %s" % (e.__class__.__name__, e)
3c0c57b1ed882e05f757466756dc7220f45f7e50ef29fde1b59062049bd2ba22
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from graphlib import CycleError, TopologicalSorter from itertools import chain from django.forms.utils import to_current_timezone from django.templatetags.static import static from django.utils import formats from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.html import format_html, html_safe from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): css = defaultdict(list) for css_list in self._css_lists: for medium, sublist in css_list.items(): css[medium].append(sublist) return {medium: self.merge(*lists) for medium, lists in css.items()} @property def _js(self): return self.merge(*self._js_lists) def render(self): return mark_safe( "\n".join( chain.from_iterable( getattr(self, "render_" + name)() for name in MEDIA_TYPES ) ) ) def render_js(self): return [ path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ Merge lists while trying to keep the relative order of the elements. Warn if the lists have the same elements in a different relative order. For static assets it can be important to have them included in the DOM in a certain order. In JavaScript you may not be able to reference a global or in CSS you might want to override a style. """ ts = TopologicalSorter() for head, *tail in filter(None, lists): ts.add(head) # Ensure that the first items are included. for item in tail: if head != item: # Avoid circular dependency to self. ts.add(item, head) head = item try: return list(ts.static_order()) except CycleError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(dict.fromkeys(chain.from_iterable(filter(None, lists)))) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m += base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): allow_multiple_selected = False input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def __init__(self, attrs=None): if ( attrs is not None and not self.allow_multiple_selected and attrs.get("multiple", False) ): raise ValueError( "%s doesn't support uploading multiple files." % self.__class__.__qualname__ ) if self.allow_multiple_selected: if attrs is None: attrs = {"multiple": True} else: attrs.setdefault("multiple", True) super().__init__(attrs) def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" getter = files.get if self.allow_multiple_selected: try: getter = files.getlist except AttributeError: pass return getter(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" checked = False def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) context["widget"]["attrs"].setdefault("disabled", False) context["widget"]["attrs"]["checked"] = self.checked return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) self.checked = self.clear_checkbox_name(name) in data if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """ Return a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError("Subclasses must implement this method.") def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = Media() for w in self.widgets: media += w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @property def needs_multipart_form(self): return any(w.needs_multipart_form for w in self.widgets) class SplitDateTimeWidget(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A widget that splits datetime input into two <input type="hidden"> inputs. """ template_name = "django/forms/widgets/splithiddendatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): super().__init__(attrs, date_format, time_format, date_attrs, time_attrs) for widget in self.widgets: widget.input_type = "hidden" class SelectDateWidget(Widget): """ A widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = ("", "---") month_field = "%s_month" day_field = "%s_day" year_field = "%s_year" template_name = "django/forms/widgets/select_date.html" input_type = "select" select_widget = Select date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$") use_fieldset = True def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError("empty_label list/tuple must have 3 elements.") self.year_none_value = ("", empty_label[0]) self.month_none_value = ("", empty_label[1]) self.day_none_value = ("", empty_label[2]) else: if empty_label is not None: self.none_value = ("", empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, str(i)) for i in self.years] if not self.is_required: year_choices.insert(0, self.year_none_value) year_name = self.year_field % name date_context["year"] = self.select_widget( attrs, choices=year_choices ).get_context( name=year_name, value=context["widget"]["value"]["year"], attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name}, ) month_choices = list(self.months.items()) if not self.is_required: month_choices.insert(0, self.month_none_value) month_name = self.month_field % name date_context["month"] = self.select_widget( attrs, choices=month_choices ).get_context( name=month_name, value=context["widget"]["value"]["month"], attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name}, ) day_choices = [(i, i) for i in range(1, 32)] if not self.is_required: day_choices.insert(0, self.day_none_value) day_name = self.day_field % name date_context["day"] = self.select_widget( attrs, choices=day_choices, ).get_context( name=day_name, value=context["widget"]["value"]["day"], attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name}, ) subwidgets = [] for field in self._parse_date_fmt(): subwidgets.append(date_context[field]["widget"]) context["widget"]["subwidgets"] = subwidgets return context def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, str): match = self.date_re.match(value) if match: # Convert any zeros in the date to empty strings to match the # empty option value. year, month, day = [int(val) or "" for val in match.groups()] else: input_format = get_format("DATE_INPUT_FORMATS")[0] try: d = datetime.datetime.strptime(value, input_format) except ValueError: pass else: year, month, day = d.year, d.month, d.day return {"year": year, "month": month, "day": day} @staticmethod def _parse_date_fmt(): fmt = get_format("DATE_FORMAT") escaped = False for char in fmt: if escaped: escaped = False elif char == "\\": escaped = True elif char in "Yy": yield "year" elif char in "bEFMmNn": yield "month" elif char in "dj": yield "day" def id_for_label(self, id_): for first_select in self._parse_date_fmt(): return "%s_%s" % (id_, first_select) return "%s_month" % id_ def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "": return None if y is not None and m is not None and d is not None: input_format = get_format("DATE_INPUT_FORMATS")[0] input_format = formats.sanitize_strftime_format(input_format) try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: # Return pseudo-ISO dates with zeros for any unselected values, # e.g. '2017-0-23'. return "%s-%s-%s" % (y or 0, m or 0, d or 0) except OverflowError: return "0-0-0" return date_value.strftime(input_format) return data.get(name) def value_omitted_from_data(self, data, files, name): return not any( ("{}_{}".format(name, interval) in data) for interval in ("year", "month", "day") )
e3c5da85ed6c578f53557fc0dda2b066a31b1a00bb8ddd0b919d455f6be053f9
import functools import warnings from pathlib import Path from django.conf import settings from django.template.backends.django import DjangoTemplates from django.template.loader import get_template from django.utils.deprecation import RemovedInDjango60Warning 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" field_template_name = "django/forms/field.html" def get_template(self, template_name): raise NotImplementedError("subclasses must implement get_template()") def render(self, template_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(template_name) @cached_property def engine(self): return self.backend( { "APP_DIRS": True, "DIRS": [Path(__file__).parent / self.backend.app_dirname], "NAME": "djangoforms", "OPTIONS": {}, } ) class DjangoTemplates(EngineMixin, BaseRenderer): """ Load Django templates from the built-in widget templates in django/forms/templates and from apps' 'templates' directory. """ backend = DjangoTemplates class Jinja2(EngineMixin, BaseRenderer): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ @cached_property def backend(self): from django.template.backends.jinja2 import Jinja2 return Jinja2 # RemovedInDjango60Warning. class DjangoDivFormRenderer(DjangoTemplates): """ Load Django templates from django/forms/templates and from apps' 'templates' directory and use the 'div.html' template to render forms and formsets. """ def __init__(self, *args, **kwargs): warnings.warn( "The DjangoDivFormRenderer transitional form renderer is deprecated. Use " "DjangoTemplates instead.", RemovedInDjango60Warning, ) super().__init__(*args, **kwargs) # RemovedInDjango60Warning. class Jinja2DivFormRenderer(Jinja2): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ def __init__(self, *args, **kwargs): warnings.warn( "The Jinja2DivFormRenderer transitional form renderer is deprecated. Use " "Jinja2 instead.", RemovedInDjango60Warning, ) super().__init__(*args, **kwargs) class TemplatesSetting(BaseRenderer): """ Load templates using template.loader.get_template() which is configured based on settings.TEMPLATES. """ def get_template(self, template_name): return get_template(template_name)
df0f1d8de0e84142baeee0df2338bd8dd95db3f65d7a4c0330857620cf0d0569
from functools import wraps from asgiref.sync import iscoroutinefunction def xframe_options_deny(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. Usage: @xframe_options_deny def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "DENY" return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "DENY" return response return wraps(view_func)(_view_wrapper) def xframe_options_sameorigin(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set. Usage: @xframe_options_sameorigin def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "SAMEORIGIN" return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "SAMEORIGIN" return response return wraps(view_func)(_view_wrapper) def xframe_options_exempt(view_func): """ Modify a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. Usage: @xframe_options_exempt def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) response.xframe_options_exempt = True return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) response.xframe_options_exempt = True return response return wraps(view_func)(_view_wrapper)
061eb15d86e196c693f82ff3ed90f8ea6fb2c094a1ffb49634f2197d0dd48343
import functools import re from collections import defaultdict from graphlib import TopologicalSorter from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOptions from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.utils import ( COMPILED_REGEX_TYPE, RegexObject, resolve_relation, ) class MigrationAutodetector: """ Take a pair of ProjectStates and compare them to see what the first would need doing to make it match the second (the second usually being the project's current state). Note that this naturally operates on entire projects at a time, as it's likely that changes interact (for example, you can't add a ForeignKey without having a migration to add the table it depends on first). A user interface may offer single-app usage if it wishes, with the caveat that it may not always be possible. """ def __init__(self, from_state, to_state, questioner=None): self.from_state = from_state self.to_state = to_state self.questioner = questioner or MigrationQuestioner() self.existing_apps = {app for app, model in from_state.models} def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes = self._detect_changes(convert_apps, graph) changes = self.arrange_for_graph(changes, graph, migration_name) if trim_to_apps: changes = self._trim_to_apps(changes, trim_to_apps) return changes def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return {key: self.deep_deconstruct(value) for key, value in obj.items()} elif isinstance(obj, functools.partial): return ( obj.func, self.deep_deconstruct(obj.args), 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): # we have a field which also returns a name deconstructed = deconstructed[1:] path, args, kwargs = deconstructed return ( path, [self.deep_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): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as the related fields change during renames). """ fields_def = [] for name, field in sorted(fields.items()): deconstruction = self.deep_deconstruct(field) if field.remote_field and field.remote_field.model: deconstruction[2].pop("to", None) fields_def.append(deconstruction) return fields_def def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. convert_apps is the list of apps to convert to use migrations (i.e. to make initial migrations for, in the usual case) graph is an optional argument that, if provided, can help improve dependency generation and avoid potential circular dependencies. """ # The first phase is generating all the operations for each app # and gathering them into a big per-app list. # Then go through that list, order it, and split into migrations to # resolve dependencies caused by M2Ms and FKs. self.generated_operations = {} self.altered_indexes = {} self.altered_constraints = {} self.renamed_fields = {} # Prepare some old/new state and model lists, separating # proxy models and ignoring unmigrated apps. self.old_model_keys = set() self.old_proxy_keys = set() self.old_unmanaged_keys = set() self.new_model_keys = set() self.new_proxy_keys = set() self.new_unmanaged_keys = set() for (app_label, model_name), model_state in self.from_state.models.items(): if not model_state.options.get("managed", True): self.old_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps: if model_state.options.get("proxy"): self.old_proxy_keys.add((app_label, model_name)) else: self.old_model_keys.add((app_label, model_name)) for (app_label, model_name), model_state in self.to_state.models.items(): if not model_state.options.get("managed", True): self.new_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps or ( convert_apps and app_label in convert_apps ): if model_state.options.get("proxy"): self.new_proxy_keys.add((app_label, model_name)) else: self.new_model_keys.add((app_label, model_name)) self.from_state.resolve_fields_and_relations() self.to_state.resolve_fields_and_relations() # Renames have to come first self.generate_renamed_models() # Prepare lists of fields and generate through model map self._prepare_field_lists() self._generate_through_model_map() # Generate non-rename model operations self.generate_deleted_models() self.generate_created_models() self.generate_deleted_proxies() self.generate_created_proxies() self.generate_altered_options() self.generate_altered_managers() self.generate_altered_db_table_comment() # Create the renamed fields and store them in self.renamed_fields. # They are used by create_altered_indexes(), generate_altered_fields(), # generate_removed_altered_index/unique_together(), and # generate_altered_index/unique_together(). self.create_renamed_fields() # Create the altered indexes and store them in self.altered_indexes. # This avoids the same computation in generate_removed_indexes() # and generate_added_indexes(). self.create_altered_indexes() self.create_altered_constraints() # Generate index removal operations before field is removed self.generate_removed_constraints() self.generate_removed_indexes() # Generate field renaming operations. self.generate_renamed_fields() self.generate_renamed_indexes() # Generate removal of foo together. self.generate_removed_altered_unique_together() self.generate_removed_altered_index_together() # RemovedInDjango51Warning. # Generate field operations. self.generate_removed_fields() self.generate_added_fields() self.generate_altered_fields() self.generate_altered_order_with_respect_to() self.generate_altered_unique_together() self.generate_altered_index_together() # RemovedInDjango51Warning. self.generate_added_indexes() self.generate_added_constraints() self.generate_altered_db_table() self._sort_migrations() self._build_migration_list(graph) self._optimize_migrations() return self.migrations def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_model_keys self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys self.through_users = {} self.old_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.from_state.models[ app_label, self.renamed_models.get((app_label, model_name), model_name) ].fields } self.new_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.to_state.models[app_label, model_name].fields } def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] for field_name, field in old_model_state.fields.items(): if hasattr(field, "remote_field") and getattr( field.remote_field, "through", None ): through_key = resolve_relation( field.remote_field.through, app_label, model_name ) self.through_users[through_key] = ( app_label, old_model_name, field_name, ) @staticmethod def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != "__setting__": return dependency, False resolved_app_label, resolved_object_name = getattr( settings, dependency[1] ).split(".") return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off the operations before it into a migration and move onto the next app. If the loops completes without doing anything, there's a circular dependency (which _should_ be impossible as the operations are all split at this point so they can't depend and be depended on). """ self.migrations = {} num_ops = sum(len(x) for x in self.generated_operations.values()) chop_mode = False while num_ops: # On every iteration, we step through all the apps and see if there # is a completed set of operations. # If we find that a subset of the operations are complete we can # try to chop it off from the rest and continue, but we only # do this if we've already been through the list once before # without any chopping and nothing has changed. for app_label in sorted(self.generated_operations): chopped = [] dependencies = set() for operation in list(self.generated_operations[app_label]): deps_satisfied = True operation_dependencies = set() for dep in operation._auto_deps: # Temporarily resolve the swappable dependency to # prevent circular references. While keeping the # dependency checks on the resolved model, add the # swappable dependencies. original_dep = dep dep, is_swappable_dep = self._resolve_dependency(dep) if dep[0] != app_label: # External app dependency. See if it's not yet # satisfied. for other_operation in self.generated_operations.get( dep[0], [] ): if self.check_dependency(other_operation, dep): deps_satisfied = False break if not deps_satisfied: break else: if is_swappable_dep: operation_dependencies.add( (original_dep[0], original_dep[1]) ) elif dep[0] in self.migrations: operation_dependencies.add( (dep[0], self.migrations[dep[0]][-1].name) ) else: # If we can't find the other app, we add a # first/last dependency, but only if we've # already been through once and checked # everything. if chop_mode: # If the app already exists, we add a # dependency on the last migration, as # we don't know which migration # contains the target field. If it's # not yet migrated or has no # migrations, we use __first__. if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add( graph.leaf_nodes(dep[0])[0] ) else: operation_dependencies.add( (dep[0], "__first__") ) else: deps_satisfied = False if deps_satisfied: chopped.append(operation) dependencies.update(operation_dependencies) del self.generated_operations[app_label][0] else: break # Make a migration! Well, only if there's stuff to put in it if dependencies or chopped: if not self.generated_operations[app_label] or chop_mode: subclass = type( "Migration", (Migration,), {"operations": [], "dependencies": []}, ) instance = subclass( "auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label, ) instance.dependencies = list(dependencies) instance.operations = chopped instance.initial = app_label not in self.existing_apps self.migrations.setdefault(app_label, []).append(instance) chop_mode = False else: self.generated_operations[app_label] = ( chopped + self.generated_operations[app_label] ) new_num_ops = sum(len(x) for x in self.generated_operations.values()) if new_num_ops == num_ops: if not chop_mode: chop_mode = True else: raise ValueError( "Cannot resolve operation dependencies: %r" % self.generated_operations ) num_ops = new_num_ops def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): ts = TopologicalSorter() for op in ops: ts.add(op) for dep in op._auto_deps: # Resolve intra-app dependencies to handle circular # references involving a swappable model. dep = self._resolve_dependency(dep)[0] if dep[0] != app_label: continue ts.add(op, *(x for x in ops if self.check_dependency(x, dep))) self.generated_operations[app_label] = list(ts.static_order()) def _optimize_migrations(self): # Add in internal dependencies among the migrations for app_label, migrations in self.migrations.items(): for m1, m2 in zip(migrations, migrations[1:]): m2.dependencies.append((app_label, m1.name)) # De-dupe dependencies for migrations in self.migrations.values(): for migration in migrations: migration.dependencies = list(set(migration.dependencies)) # Optimize migrations for app_label, migrations in self.migrations.items(): for migration in migrations: migration.operations = MigrationOptimizer().optimize( migration.operations, app_label ) def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() ) # Created field elif dependency[2] is not None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() and any(dependency[2] == x for x, y in operation.fields) ) or ( isinstance(operation, operations.AddField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed field elif dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model elif dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered elif dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field elif dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together elif dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance( operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether), ) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. else: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are # (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) else: self.generated_operations.setdefault(app_label, []).append(operation) def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model_state = self.to_state.models[item] base_names = { base if isinstance(base, str) else base.__name__ for base in model_state.bases } string_version = "%s.%s" % (item[0], item[1]) if ( model_state.options.get("swappable") or "AbstractUser" in base_names or "AbstractBaseUser" in base_names or settings.AUTH_USER_MODEL.lower() == string_version.lower() ): return ("___" + item[0], "___" + item[1]) except LookupError: pass return item def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} added_models = self.new_model_keys - self.old_model_keys for app_label, model_name in sorted(added_models): model_state = self.to_state.models[app_label, model_name] model_fields_def = self.only_relation_agnostic_fields(model_state.fields) removed_models = self.old_model_keys - self.new_model_keys for rem_app_label, rem_model_name in removed_models: if rem_app_label == app_label: rem_model_state = self.from_state.models[ rem_app_label, rem_model_name ] rem_model_fields_def = self.only_relation_agnostic_fields( rem_model_state.fields ) if model_fields_def == rem_model_fields_def: if self.questioner.ask_rename_model( rem_model_state, model_state ): dependencies = [] fields = list(model_state.fields.values()) + [ field.remote_field for relations in self.to_state.relations[ app_label, model_name ].values() for field in relations.values() ] for field in fields: if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) self.add_operation( app_label, operations.RenameModel( old_name=rem_model_state.name, new_name=model_state.name, ), dependencies=dependencies, ) self.renamed_models[app_label, model_name] = rem_model_name renamed_models_rel_key = "%s.%s" % ( rem_model_state.app_label, rem_model_state.name_lower, ) self.renamed_models_rel[ renamed_models_rel_key ] = "%s.%s" % ( model_state.app_label, model_state.name_lower, ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) break def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might be deferred (e.g. unique_together, index_together). """ old_keys = self.old_model_keys | self.old_unmanaged_keys added_models = self.new_model_keys - old_keys added_unmanaged_models = self.new_unmanaged_keys - old_keys all_added_models = chain( sorted(added_models, key=self.swappable_first_key, reverse=True), sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True), ) for app_label, model_name in all_added_models: model_state = self.to_state.models[app_label, model_name] # Gather related fields related_fields = {} primary_key_rel = None for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: if field.primary_key: primary_key_rel = field.remote_field.model elif not field.remote_field.parent_link: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Are there indexes/unique|index_together to defer? indexes = model_state.options.pop("indexes") constraints = model_state.options.pop("constraints") unique_together = model_state.options.pop("unique_together", None) # RemovedInDjango51Warning. index_together = model_state.options.pop("index_together", None) order_with_respect_to = model_state.options.pop( "order_with_respect_to", None ) # Depend on the deletion of any possible proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Depend on the removal of base fields if the new model has # a field with the same name. old_base_model_state = self.from_state.models.get( (base_app_label, base_name) ) new_base_model_state = self.to_state.models.get( (base_app_label, base_name) ) if old_base_model_state and new_base_model_state: removed_base_fields = ( set(old_base_model_state.fields) .difference( new_base_model_state.fields, ) .intersection(model_state.fields) ) for removed_base_field in removed_base_fields: dependencies.append( (base_app_label, base_name, removed_base_field, False) ) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append( resolve_relation( primary_key_rel, app_label, model_name, ) + (None, True) ) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[ d for d in model_state.fields.items() if d[0] not in related_fields ], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), dependencies=dependencies, beginning=True, ) # Don't add operations which modify the database for unmanaged models if not model_state.options.get("managed", True): continue # Generate operations for each related field for name, field in sorted(related_fields.items()): dependencies = self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) # Depend on our own model being created dependencies.append((app_label, model_name, None, True)) # Make operation self.add_operation( app_label, operations.AddField( model_name=model_name, name=name, field=field, ), dependencies=list(set(dependencies)), ) # Generate other opns if order_with_respect_to: self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=order_with_respect_to, ), dependencies=[ (app_label, model_name, order_with_respect_to, True), (app_label, model_name, None, True), ], ) related_dependencies = [ (app_label, model_name, name, True) for name in sorted(related_fields) ] related_dependencies.append((app_label, model_name, None, True)) for index in indexes: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=related_dependencies, ) for constraint in constraints: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=related_dependencies, ) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=unique_together, ), dependencies=related_dependencies, ) # RemovedInDjango51Warning. if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=index_together, ), dependencies=related_dependencies, ) # Fix relationships if the model changed from a proxy model to a # concrete model. relations = self.to_state.relations if (app_label, model_name) in self.old_proxy_keys: for related_model_key, related_fields in relations[ app_label, model_name ].items(): related_model_state = self.to_state.models[related_model_key] for related_field_name, related_field in related_fields.items(): self.add_operation( related_model_state.app_label, operations.AlterField( model_name=related_model_state.name, name=related_field_name, field=related_field, ), dependencies=[(app_label, model_name, None, True)], ) def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but for proxy models it's safe to skip all the pointless field stuff and chuck out an operation. """ added = self.new_proxy_keys - self.old_proxy_keys for app_label, model_name in sorted(added): model_state = self.to_state.models[app_label, model_name] assert model_state.options.get("proxy") # Depend on the deletion of any possible non-proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), # Depend on the deletion of any possible non-proxy version of us dependencies=dependencies, ) def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to collections of fields - the inverse of generate_created_models(). """ new_keys = self.new_model_keys | self.new_unmanaged_keys deleted_models = self.old_model_keys - new_keys deleted_unmanaged_models = self.old_unmanaged_keys - new_keys all_deleted_models = chain( sorted(deleted_models), sorted(deleted_unmanaged_models) ) for app_label, model_name in all_deleted_models: model_state = self.from_state.models[app_label, model_name] # Gather related fields related_fields = {} for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Generate option removal first unique_together = model_state.options.pop("unique_together", None) # RemovedInDjango51Warning. index_together = model_state.options.pop("index_together", None) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=None, ), ) # RemovedInDjango51Warning. if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=None, ), ) # Then remove each related field for name in sorted(related_fields): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=name, ), ) # Finally, remove the model. # This depends on both the removal/alteration of all incoming fields # and the removal of all its own related fields, and if it's # a through model the field that references it. dependencies = [] relations = self.from_state.relations for ( related_object_app_label, object_name, ), relation_related_fields in relations[app_label, model_name].items(): for field_name, field in relation_related_fields.items(): dependencies.append( (related_object_app_label, object_name, field_name, False), ) if not field.many_to_many: dependencies.append( ( related_object_app_label, object_name, field_name, "alter", ), ) for name in sorted(related_fields): dependencies.append((app_label, model_name, name, False)) # We're referenced in another field's through= through_user = self.through_users.get((app_label, model_state.name_lower)) if through_user: dependencies.append( (through_user[0], through_user[1], through_user[2], False) ) # Finally, make the operation, deduping any dependencies self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), dependencies=list(set(dependencies)), ) def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.get("proxy") self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), ) def create_renamed_fields(self): """Work out renamed fields.""" self.renamed_operations = [] old_field_keys = self.old_field_keys.copy() for app_label, model_name, field_name in sorted( self.new_field_keys - old_field_keys ): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] field = new_model_state.get_field(field_name) # Scan to see if this is actually a rename! field_dec = self.deep_deconstruct(field) for rem_app_label, rem_model_name, rem_field_name in sorted( old_field_keys - self.new_field_keys ): if rem_app_label == app_label and rem_model_name == model_name: old_field = old_model_state.get_field(rem_field_name) old_field_dec = self.deep_deconstruct(old_field) if ( field.remote_field and field.remote_field.model and "to" in old_field_dec[2] ): old_rel_to = old_field_dec[2]["to"] if old_rel_to in self.renamed_models_rel: old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to] old_field.set_attributes_from_name(rem_field_name) old_db_column = old_field.get_attname_column()[1] if old_field_dec == field_dec or ( # Was the field renamed and db_column equal to the # old field's column added? old_field_dec[0:2] == field_dec[0:2] and dict(old_field_dec[2], db_column=old_db_column) == field_dec[2] ): if self.questioner.ask_rename( model_name, rem_field_name, field_name, field ): self.renamed_operations.append( ( rem_app_label, rem_model_name, old_field.db_column, rem_field_name, app_label, model_name, field, field_name, ) ) old_field_keys.remove( (rem_app_label, rem_model_name, rem_field_name) ) old_field_keys.add((app_label, model_name, field_name)) self.renamed_fields[ app_label, model_name, field_name ] = rem_field_name break def generate_renamed_fields(self): """Generate RenameField operations.""" for ( rem_app_label, rem_model_name, rem_db_column, rem_field_name, app_label, model_name, field, field_name, ) in self.renamed_operations: # A db_column mismatch requires a prior noop AlterField for the # subsequent RenameField to be a noop on attempts at preserving the # old name. if rem_db_column != field.db_column: altered_field = field.clone() altered_field.name = rem_field_name self.add_operation( app_label, operations.AlterField( model_name=model_name, name=rem_field_name, field=altered_field, ), ) self.add_operation( app_label, operations.RenameField( model_name=model_name, old_name=rem_field_name, new_name=field_name, ), ) self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name)) self.old_field_keys.add((app_label, model_name, field_name)) def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted( self.new_field_keys - self.old_field_keys ): self._generate_added_field(app_label, model_name, field_name) def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) # Adding a field always depends at least on its removal. dependencies = [(app_label, model_name, field_name, False)] # Fields that are foreignkeys/m2ms depend on stuff. if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) # You can't just add NOT NULL fields with no default or fields # which don't allow empty strings as default. time_fields = (models.DateField, models.DateTimeField, models.TimeField) preserve_default = ( field.null or field.has_default() or field.db_default is not models.NOT_PROVIDED or field.many_to_many or (field.blank and field.empty_strings_allowed) or (isinstance(field, time_fields) and field.auto_now) ) if not preserve_default: field = field.clone() if isinstance(field, time_fields) and field.auto_now_add: field.default = self.questioner.ask_auto_now_add_addition( field_name, model_name ) else: field.default = self.questioner.ask_not_null_addition( field_name, model_name ) if ( field.unique and field.default is not models.NOT_PROVIDED and callable(field.default) ): self.questioner.ask_unique_callable_default_addition(field_name, model_name) self.add_operation( app_label, operations.AddField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted( self.old_field_keys - self.new_field_keys ): self._generate_removed_field(app_label, model_name, field_name) def _generate_removed_field(self, app_label, model_name, field_name): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=field_name, ), # We might need to depend on the removal of an # order_with_respect_to or index/unique_together operation; # this is safely ignored if there isn't one dependencies=[ (app_label, model_name, field_name, "order_wrt_unset"), (app_label, model_name, field_name, "foo_together_change"), ], ) def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn't possible. """ for app_label, model_name, field_name in sorted( self.old_field_keys & self.new_field_keys ): # Did the field change? old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_field_name = self.renamed_fields.get( (app_label, model_name, field_name), field_name ) old_field = self.from_state.models[app_label, old_model_name].get_field( old_field_name ) new_field = self.to_state.models[app_label, model_name].get_field( field_name ) dependencies = [] # Implement any model renames on relations; these are handled by RenameModel # so we need to exclude them from the comparison if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "model", None ): rename_key = resolve_relation( new_field.remote_field.model, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.model = old_field.remote_field.model # Handle ForeignKey which can only have a single to_field. remote_field_name = getattr(new_field.remote_field, "field_name", None) if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: # Repoint both model and field name because to_field # inclusion in ForeignKey.deconstruct() is based on # both. new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = ( old_field.remote_field.field_name ) # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, "from_fields", None) if from_fields: from_rename_key = (app_label, model_name) new_field.from_fields = tuple( [ self.renamed_fields.get( from_rename_key + (from_field,), from_field ) for from_field in from_fields ] ) new_field.to_fields = tuple( [ self.renamed_fields.get(rename_key + (to_field,), to_field) for to_field in new_field.to_fields ] ) dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, new_field, self.to_state, ) ) if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "through", None ): rename_key = resolve_relation( new_field.remote_field.through, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.through = old_field.remote_field.through old_field_dec = self.deep_deconstruct(old_field) new_field_dec = self.deep_deconstruct(new_field) # If the field was confirmed to be renamed it means that only # db_column was allowed to change which generate_renamed_fields() # already accounts for by adding an AlterField operation. if old_field_dec != new_field_dec and old_field_name == field_name: both_m2m = old_field.many_to_many and new_field.many_to_many neither_m2m = not old_field.many_to_many and not new_field.many_to_many if both_m2m or neither_m2m: # Either both fields are m2m or neither is preserve_default = True if ( old_field.null and not new_field.null and not new_field.has_default() and new_field.db_default is models.NOT_PROVIDED and not new_field.many_to_many ): field = new_field.clone() new_default = self.questioner.ask_not_null_alteration( field_name, model_name ) if new_default is not models.NOT_PROVIDED: field.default = new_default preserve_default = False else: field = new_field self.add_operation( app_label, operations.AlterField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) else: # We cannot alter between m2m and concrete fields self._generate_removed_field(app_label, model_name, field_name) self._generate_added_field(app_label, model_name, field_name) def create_altered_indexes(self): option_name = operations.AddIndex.option_name self.renamed_index_together_values = defaultdict(list) for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_indexes = old_model_state.options[option_name] new_indexes = new_model_state.options[option_name] added_indexes = [idx for idx in new_indexes if idx not in old_indexes] removed_indexes = [idx for idx in old_indexes if idx not in new_indexes] renamed_indexes = [] # Find renamed indexes. remove_from_added = [] remove_from_removed = [] for new_index in added_indexes: new_index_dec = new_index.deconstruct() new_index_name = new_index_dec[2].pop("name") for old_index in removed_indexes: old_index_dec = old_index.deconstruct() old_index_name = old_index_dec[2].pop("name") # Indexes are the same except for the names. if ( new_index_dec == old_index_dec and new_index_name != old_index_name ): renamed_indexes.append((old_index_name, new_index_name, None)) remove_from_added.append(new_index) remove_from_removed.append(old_index) # Find index_together changed to indexes. for ( old_value, new_value, index_together_app_label, index_together_model_name, dependencies, ) in self._get_altered_foo_together_operations( operations.AlterIndexTogether.option_name ): if ( app_label != index_together_app_label or model_name != index_together_model_name ): continue removed_values = old_value.difference(new_value) for removed_index_together in removed_values: renamed_index_together_indexes = [] for new_index in added_indexes: _, args, kwargs = new_index.deconstruct() # Ensure only 'fields' are defined in the Index. if ( not args and new_index.fields == list(removed_index_together) and set(kwargs) == {"name", "fields"} ): renamed_index_together_indexes.append(new_index) if len(renamed_index_together_indexes) == 1: renamed_index = renamed_index_together_indexes[0] remove_from_added.append(renamed_index) renamed_indexes.append( (None, renamed_index.name, removed_index_together) ) self.renamed_index_together_values[ index_together_app_label, index_together_model_name ].append(removed_index_together) # Remove renamed indexes from the lists of added and removed # indexes. added_indexes = [ idx for idx in added_indexes if idx not in remove_from_added ] removed_indexes = [ idx for idx in removed_indexes if idx not in remove_from_removed ] self.altered_indexes.update( { (app_label, model_name): { "added_indexes": added_indexes, "removed_indexes": removed_indexes, "renamed_indexes": renamed_indexes, } } ) def generate_added_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): dependencies = self._get_dependencies_for_model(app_label, model_name) for index in alt_indexes["added_indexes"]: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=dependencies, ) def generate_removed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["removed_indexes"]: self.add_operation( app_label, operations.RemoveIndex( model_name=model_name, name=index.name, ), ) def generate_renamed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for old_index_name, new_index_name, old_fields in alt_indexes[ "renamed_indexes" ]: self.add_operation( app_label, operations.RenameIndex( model_name=model_name, new_name=new_index_name, old_name=old_index_name, old_fields=old_fields, ), ) def create_altered_constraints(self): option_name = operations.AddConstraint.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_constraints = old_model_state.options[option_name] new_constraints = new_model_state.options[option_name] add_constraints = [c for c in new_constraints if c not in old_constraints] rem_constraints = [c for c in old_constraints if c not in new_constraints] self.altered_constraints.update( { (app_label, model_name): { "added_constraints": add_constraints, "removed_constraints": rem_constraints, } } ) def generate_added_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): dependencies = self._get_dependencies_for_model(app_label, model_name) for constraint in alt_constraints["added_constraints"]: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=dependencies, ) def generate_removed_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["removed_constraints"]: self.add_operation( app_label, operations.RemoveConstraint( model_name=model_name, name=constraint.name, ), ) @staticmethod def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state): remote_field_model = None if hasattr(field.remote_field, "model"): remote_field_model = field.remote_field.model else: relations = project_state.relations[app_label, model_name] for (remote_app_label, remote_model_name), fields in relations.items(): if any( field == related_field.remote_field for related_field in fields.values() ): remote_field_model = f"{remote_app_label}.{remote_model_name}" break # Account for FKs to swappable models swappable_setting = getattr(field, "swappable_setting", None) if swappable_setting is not None: dep_app_label = "__setting__" dep_object_name = swappable_setting else: dep_app_label, dep_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies = [(dep_app_label, dep_object_name, None, True)] if getattr(field.remote_field, "through", None): through_app_label, through_object_name = resolve_relation( field.remote_field.through, app_label, model_name, ) dependencies.append((through_app_label, through_object_name, None, True)) return dependencies def _get_dependencies_for_model(self, app_label, model_name): """Return foreign key dependencies of the given model.""" dependencies = [] model_state = self.to_state.models[app_label, model_name] for field in model_state.fields.values(): if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) return dependencies def _get_altered_foo_together_operations(self, option_name): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] # We run the old version through the field renames to account for those old_value = old_model_state.options.get(option_name) old_value = ( { tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique ) for unique in old_value } if old_value else set() ) new_value = new_model_state.options.get(option_name) new_value = set(new_value) if new_value else set() if old_value != new_value: dependencies = [] for foo_togethers in new_value: for field_name in foo_togethers: field = new_model_state.get_field(field_name) if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) yield ( old_value, new_value, app_label, model_name, dependencies, ) def _generate_removed_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): if operation == operations.AlterIndexTogether: old_value = { value for value in old_value if value not in self.renamed_index_together_values[app_label, model_name] } removal_value = new_value.intersection(old_value) if removal_value or old_value: self.add_operation( app_label, operation( name=model_name, **{operation.option_name: removal_value} ), dependencies=dependencies, ) def generate_removed_altered_unique_together(self): self._generate_removed_altered_foo_together(operations.AlterUniqueTogether) # RemovedInDjango51Warning. def generate_removed_altered_index_together(self): self._generate_removed_altered_foo_together(operations.AlterIndexTogether) def _generate_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if new_value != removal_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: new_value}), dependencies=dependencies, ) def generate_altered_unique_together(self): self._generate_altered_foo_together(operations.AlterUniqueTogether) # RemovedInDjango51Warning. def generate_altered_index_together(self): self._generate_altered_foo_together(operations.AlterIndexTogether) def generate_altered_db_table(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_name = old_model_state.options.get("db_table") new_db_table_name = new_model_state.options.get("db_table") if old_db_table_name != new_db_table_name: self.add_operation( app_label, operations.AlterModelTable( name=model_name, table=new_db_table_name, ), ) def generate_altered_db_table_comment(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_comment = old_model_state.options.get("db_table_comment") new_db_table_comment = new_model_state.options.get("db_table_comment") if old_db_table_comment != new_db_table_comment: self.add_operation( app_label, operations.AlterModelTableComment( name=model_name, table_comment=new_db_table_comment, ), ) def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys, # unmanaged converted to managed self.old_unmanaged_keys & self.new_model_keys, # managed converted to unmanaged self.old_model_keys & self.new_unmanaged_keys, ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_options = { key: value for key, value in old_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } new_options = { key: value for key, value in new_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } if old_options != new_options: self.add_operation( app_label, operations.AlterModelOptions( name=model_name, options=new_options, ), ) def generate_altered_order_with_respect_to(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.options.get( "order_with_respect_to" ) != new_model_state.options.get("order_with_respect_to"): # Make sure it comes second if we're adding # (removal dependency is part of RemoveField) dependencies = [] if new_model_state.options.get("order_with_respect_to"): dependencies.append( ( app_label, model_name, new_model_state.options["order_with_respect_to"], True, ) ) # Actually generate the operation self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=new_model_state.options.get( "order_with_respect_to" ), ), dependencies=dependencies, ) def generate_altered_managers(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.managers != new_model_state.managers: self.add_operation( app_label, operations.AlterModelManagers( name=model_name, managers=new_model_state.managers, ), ) def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() name_map = {} for app_label, migrations in list(changes.items()): if not migrations: continue # Find the app label's current leaf node app_leaf = None for leaf in leaves: if leaf[0] == app_label: app_leaf = leaf break # Do they want an initial migration for this app? if app_leaf is None and not self.questioner.ask_initial(app_label): # They don't. for migration in migrations: name_map[(app_label, migration.name)] = (app_label, "__first__") del changes[app_label] continue # Work out the next number in the sequence if app_leaf is None: next_number = 1 else: next_number = (self.parse_number(app_leaf[1]) or 0) + 1 # Name each migration for i, migration in enumerate(migrations): if i == 0 and app_leaf: migration.dependencies.append(app_leaf) new_name_parts = ["%04i" % next_number] if migration_name: new_name_parts.append(migration_name) elif i == 0 and not app_leaf: new_name_parts.append("initial") else: new_name_parts.append(migration.suggest_name()[:100]) new_name = "_".join(new_name_parts) name_map[(app_label, migration.name)] = (app_label, new_name) next_number += 1 migration.name = new_name # Now fix dependencies for migrations in changes.values(): for migration in migrations: migration.dependencies = [ name_map.get(d, d) for d in migration.dependencies ] return changes def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies. """ # Gather other app dependencies in a first pass app_dependencies = {} for app_label, migrations in changes.items(): for migration in migrations: for dep_app_label, name in migration.dependencies: app_dependencies.setdefault(app_label, set()).add(dep_app_label) required_apps = set(app_labels) # Keep resolving till there's no change old_required_apps = None while old_required_apps != required_apps: old_required_apps = set(required_apps) required_apps.update( *[app_dependencies.get(app_label, ()) for app_label in required_apps] ) # Remove all migrations that aren't needed for app_label in list(changes): if app_label not in required_apps: del changes[app_label] return changes @classmethod def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. For a squashed migration such as '0001_squashed_0004…', return the second number. If no number is found, return None. """ if squashed_match := re.search(r".*_squashed_(\d+)", name): return int(squashed_match[1]) match = re.match(r"^\d+", name) if match: return int(match[0]) return None
6a939cd5b3dc07aff9eb2fbe261158b365486de2308ae3aa6f9d7947dd788876
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import operator import warnings from itertools import chain, islice from asgiref.sync import sync_to_async import django from django.conf import settings from django.core import exceptions from django.db import ( DJANGO_VERSION_PICKLE_KEY, IntegrityError, NotSupportedError, connections, router, transaction, ) from django.db.models import AutoField, DateField, DateTimeField, Field, sql from django.db.models.constants import LOOKUP_SEP, OnConflict from django.db.models.deletion import Collector from django.db.models.expressions import Case, F, Value, When from django.db.models.functions import Cast, Trunc from django.db.models.query_utils import FilteredRelation, Q from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE from django.db.models.utils import ( AltersData, create_namedtuple_class, resolve_callables, ) from django.utils import timezone from django.utils.functional import cached_property, partition # The maximum number of results to fetch in a get() query. MAX_GET_RESULTS = 21 # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 class BaseIterable: def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): self.queryset = queryset self.chunked_fetch = chunked_fetch self.chunk_size = chunk_size async def _async_generator(self): # Generators don't actually start running until the first time you call # next() on them, so make the generator object in the async thread and # then repeatedly dispatch to it in a sync thread. sync_generator = self.__iter__() def next_slice(gen): return list(islice(gen, self.chunk_size)) while True: chunk = await sync_to_async(next_slice)(sync_generator) for item in chunk: yield item if len(chunk) < self.chunk_size: break # __aiter__() is a *synchronous* method that has to then return an # *asynchronous* iterator/generator. Thus, nest an async generator inside # it. # This is a generic iterable converter for now, and is going to suffer a # performance penalty on large sets of items due to the cost of crossing # over the sync barrier for each chunk. Custom __aiter__() methods should # be added to each Iterable subclass, but that needs some work in the # Compiler first. def __aiter__(self): return self._async_generator() class ModelIterable(BaseIterable): """Iterable that yields a model instance for each row.""" def __iter__(self): queryset = self.queryset db = queryset.db compiler = queryset.query.get_compiler(using=db) # Execute the query. This will also fill compiler.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[-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) known_related_objects = [ ( field, related_objs, operator.attrgetter( *[ field.attname if from_field == "self" else queryset.model._meta.get_field(from_field).attname for from_field in field.from_fields ] ), ) for field, related_objs in queryset._known_related_objects.items() ] for row in compiler.results_iter(results): obj = model_cls.from_db( db, init_list, row[model_fields_start:model_fields_end] ) for rel_populator in related_populators: rel_populator.populate(row, obj) if annotation_col_map: for attr_name, col_pos in annotation_col_map.items(): setattr(obj, attr_name, row[col_pos]) # Add the known related objects to the model. for field, rel_objs, rel_getter in known_related_objects: # Avoid overwriting objects loaded by, e.g., select_related(). if field.is_cached(obj): continue rel_obj_id = rel_getter(obj) try: rel_obj = rel_objs[rel_obj_id] except KeyError: pass # May happen in qs1 | qs2 scenarios. else: setattr(obj, field.name, rel_obj) yield obj class RawModelIterable(BaseIterable): """ Iterable that yields a model instance for each row from a raw queryset. """ def __iter__(self): # Cache some things for performance reasons outside the loop. db = self.queryset.db query = self.queryset.query connection = connections[db] compiler = connection.ops.compiler("SQLCompiler")(query, connection, db) query_iterator = iter(query) try: ( model_init_names, model_init_pos, annotation_fields, ) = self.queryset.resolve_model_init_order() model_cls = self.queryset.model if model_cls._meta.pk.attname not in model_init_names: raise exceptions.FieldDoesNotExist( "Raw query must include the primary key" ) fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns] converters = compiler.get_converters( [f.get_col(f.model._meta.db_table) if f else None for f in fields] ) if converters: query_iterator = compiler.apply_converters(query_iterator, converters) for values in query_iterator: # Associate fields to values model_init_values = [values[pos] for pos in model_init_pos] instance = model_cls.from_db(db, model_init_names, model_init_values) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) yield instance finally: # Done iterating the Query. If it has its own cursor, close it. if hasattr(query, "cursor") and query.cursor: query.cursor.close() class ValuesIterable(BaseIterable): """ Iterable returned by QuerySet.values() that yields a dict for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] indexes = range(len(names)) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield {names[i]: row[i] for i in indexes} class ValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) if queryset._fields: # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] fields = [ *queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields), ] if fields != names: # Reorder according to fields. index_map = {name: idx for idx, name in enumerate(names)} rowfactory = operator.itemgetter(*[index_map[f] for f in fields]) return map( rowfactory, compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ), ) return compiler.results_iter( tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size, ) class NamedValuesListIterable(ValuesListIterable): """ Iterable returned by QuerySet.values_list(named=True) that yields a namedtuple for each row. """ def __iter__(self): queryset = self.queryset if queryset._fields: names = queryset._fields else: query = queryset.query names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] tuple_class = create_namedtuple_class(*names) new = tuple.__new__ for row in super().__iter__(): yield new(tuple_class, row) class FlatValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=True) that yields single values. """ def __iter__(self): queryset = self.queryset compiler = queryset.query.get_compiler(queryset.db) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield row[0] class QuerySet(AltersData): """Represent a lazy database lookup for a set of objects.""" def __init__(self, model=None, query=None, using=None, hints=None): self.model = model self._db = using self._hints = hints or {} self._query = query or sql.Query(self.model) self._result_cache = None self._sticky_filter = False self._for_write = False self._prefetch_related_lookups = () self._prefetch_done = False self._known_related_objects = {} # {rel_field: {pk: rel_obj}} self._iterable_class = ModelIterable self._fields = None self._defer_next_filter = False self._deferred_filter = None @property def query(self): if self._deferred_filter: negate, args, kwargs = self._deferred_filter self._filter_or_exclude_inplace(negate, args, kwargs) self._deferred_filter = None return self._query @query.setter def query(self, value): if value.values_select: self._iterable_class = ValuesIterable self._query = value def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_as_manager = True return manager as_manager.queryset_only = True as_manager = classmethod(as_manager) ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """Don't populate the QuerySet's cache.""" obj = self.__class__() for k, v in self.__dict__.items(): if k == "_result_cache": obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj def __getstate__(self): # Force the cache to be fully populated. self._fetch_all() return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__} def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled queryset instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled queryset instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) self.__dict__.update(state) def __repr__(self): data = list(self[: REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return "<%s %r>" % (self.__class__.__name__, data) def __len__(self): self._fetch_all() return len(self._result_cache) def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. """ self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def __bool__(self): self._fetch_all() return bool(self._result_cache) def __getitem__(self, k): """Retrieve an item or slice from the set of results.""" if not isinstance(k, (int, slice)): raise TypeError( "QuerySet indices must be integers or slices, not %s." % type(k).__name__ ) if (isinstance(k, int) and k < 0) or ( isinstance(k, slice) and ( (k.start is not None and k.start < 0) or (k.stop is not None and k.stop < 0) ) ): raise ValueError("Negative indexing is not supported.") if self._result_cache is not None: return self._result_cache[k] if isinstance(k, slice): qs = self._chain() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return list(qs)[:: k.step] if k.step else qs qs = self._chain() qs.query.set_limits(k, k + 1) qs._fetch_all() return qs._result_cache[0] def __class_getitem__(cls, *args, **kwargs): return cls def __and__(self, other): self._check_operator_queryset(other, "&") self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other if isinstance(self, EmptyQuerySet): return self combined = self._chain() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._check_operator_queryset(other, "|") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.OR) return combined def __xor__(self, other): self._check_operator_queryset(other, "^") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.XOR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def _iterator(self, use_chunked_fetch, chunk_size): iterable = self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size or 2000, ) if not self._prefetch_related_lookups or chunk_size is None: yield from iterable return iterator = iter(iterable) while results := list(islice(iterator, chunk_size)): prefetch_related_objects(results, *self._prefetch_related_lookups) yield from results def iterator(self, chunk_size=None): """ An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied. """ if chunk_size is None: if self._prefetch_related_lookups: raise ValueError( "chunk_size must be provided when using QuerySet.iterator() after " "prefetch_related()." ) elif chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) return self._iterator(use_chunked_fetch, chunk_size) async def aiterator(self, chunk_size=2000): """ An asynchronous iterator over the results from applying this QuerySet to the database. """ if self._prefetch_related_lookups: raise NotSupportedError( "Using QuerySet.aiterator() after prefetch_related() is not supported." ) if chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) async for item in self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size ): yield item def aggregate(self, *args, **kwargs): """ Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._validate_values_are_expressions( (*args, *kwargs.values()), method_name="aggregate" ) for arg in args: # The default_alias property raises TypeError if default_alias # can't be set automatically or AttributeError if it isn't an # attribute. try: arg.default_alias except (AttributeError, TypeError): raise TypeError("Complex aggregates require an alias") kwargs[arg.default_alias] = arg return self.query.chain().get_aggregation(self.db, kwargs) async def aaggregate(self, *args, **kwargs): return await sync_to_async(self.aggregate)(*args, **kwargs) def count(self): """ Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) return self.query.get_count(using=self.db) async def acount(self): return await sync_to_async(self.count)() def get(self, *args, **kwargs): """ Perform the query and return a single object matching the given keyword arguments. """ if self.query.combinator and (args or kwargs): raise NotSupportedError( "Calling QuerySet.get(...) with filters after %s() is not " "supported." % self.query.combinator ) clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() limit = None if ( not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit ): limit = MAX_GET_RESULTS clone.query.set_limits(high=limit) num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( "get() returned more than one %s -- it returned %s!" % ( self.model._meta.object_name, num if not limit or num < limit else "more than %s" % (limit - 1), ) ) async def aget(self, *args, **kwargs): return await sync_to_async(self.get)(*args, **kwargs) def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj async def acreate(self, **kwargs): return await sync_to_async(self.create)(**kwargs) def _prepare_for_bulk_create(self, objs): from django.db.models.expressions import DatabaseDefault connection = connections[self.db] for obj in objs: if obj.pk is None: # Populate new PK values. obj.pk = obj._meta.pk.get_pk_value_on_save(obj) if not connection.features.supports_default_keyword_in_bulk_insert: for field in obj._meta.fields: value = getattr(obj, field.attname) if isinstance(value, DatabaseDefault): setattr(obj, field.attname, field.db_default) obj._prepare_related_fields_for_save(operation_name="bulk_create") def _check_bulk_create_options( self, ignore_conflicts, update_conflicts, update_fields, unique_fields ): if ignore_conflicts and update_conflicts: raise ValueError( "ignore_conflicts and update_conflicts are mutually exclusive." ) db_features = connections[self.db].features if ignore_conflicts: if not db_features.supports_ignore_conflicts: raise NotSupportedError( "This database backend does not support ignoring conflicts." ) return OnConflict.IGNORE elif update_conflicts: if not db_features.supports_update_conflicts: raise NotSupportedError( "This database backend does not support updating conflicts." ) if not update_fields: raise ValueError( "Fields that will be updated when a row insertion fails " "on conflicts must be provided." ) if unique_fields and not db_features.supports_update_conflicts_with_target: raise NotSupportedError( "This database backend does not support updating " "conflicts with specifying unique fields that can trigger " "the upsert." ) if not unique_fields and db_features.supports_update_conflicts_with_target: raise ValueError( "Unique fields that can trigger the upsert must be provided." ) # Updating primary keys and non-concrete fields is forbidden. if any(not f.concrete or f.many_to_many for f in update_fields): raise ValueError( "bulk_create() can only be used with concrete fields in " "update_fields." ) if any(f.primary_key for f in update_fields): raise ValueError( "bulk_create() cannot be used with primary keys in " "update_fields." ) if unique_fields: if any(not f.concrete or f.many_to_many for f in unique_fields): raise ValueError( "bulk_create() can only be used with concrete fields " "in unique_fields." ) return OnConflict.UPDATE return None def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): """ Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported. """ # When you bulk insert you don't get the primary keys back (if it's an # autoincrement, except if can_return_rows_from_bulk_insert=True), so # you can't insert into the child tables which references this. There # are two workarounds: # 1) This could be implemented if you didn't have an autoincrement pk # 2) You could do it by doing O(n) normal inserts into the parent # tables to get the primary keys back and then doing a single bulk # insert into the childmost table. # We currently set the primary keys on the objects when using # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy # would not identify that case as involving multiple tables. for parent in self.model._meta.get_parent_list(): if parent._meta.concrete_model is not self.model._meta.concrete_model: raise ValueError("Can't bulk create a multi-table inherited model") if not objs: return objs opts = self.model._meta if unique_fields: # Primary key is allowed in unique_fields. unique_fields = [ self.model._meta.get_field(opts.pk.name if name == "pk" else name) for name in unique_fields ] if update_fields: update_fields = [self.model._meta.get_field(name) for name in update_fields] on_conflict = self._check_bulk_create_options( ignore_conflicts, update_conflicts, update_fields, unique_fields, ) self._for_write = True fields = opts.concrete_fields objs = list(objs) self._prepare_for_bulk_create(objs) with transaction.atomic(using=self.db, savepoint=False): objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: returned_columns = self._batched_insert( objs_with_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) for obj_with_pk, results in zip(objs_with_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): if field != opts.pk: setattr(obj_with_pk, field.attname, result) for obj_with_pk in objs_with_pk: obj_with_pk._state.adding = False obj_with_pk._state.db = self.db if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] returned_columns = self._batched_insert( objs_without_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) connection = connections[self.db] if ( connection.features.can_return_rows_from_bulk_insert and on_conflict is None ): assert len(returned_columns) == len(objs_without_pk) for obj_without_pk, results in zip(objs_without_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): setattr(obj_without_pk, field.attname, result) obj_without_pk._state.adding = False obj_without_pk._state.db = self.db return objs async def abulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): return await sync_to_async(self.bulk_create)( objs=objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts, update_conflicts=update_conflicts, update_fields=update_fields, unique_fields=unique_fields, ) def bulk_update(self, objs, fields, batch_size=None): """ Update the given fields in each of the given objects in the database. """ if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") if not fields: raise ValueError("Field names must be given to bulk_update().") objs = tuple(objs) if any(obj.pk is None for obj in objs): raise ValueError("All bulk_update() objects must have a primary key set.") fields = [self.model._meta.get_field(name) for name in fields] if any(not f.concrete or f.many_to_many for f in fields): raise ValueError("bulk_update() can only be used with concrete fields.") if any(f.primary_key for f in fields): raise ValueError("bulk_update() cannot be used with primary key fields.") if not objs: return 0 for obj in objs: obj._prepare_related_fields_for_save( operation_name="bulk_update", fields=fields ) # PK is used twice in the resulting update query, once in the filter # and once in the WHEN. Each field will also have one CAST. self._for_write = True connection = connections[self.db] max_batch_size = connection.ops.bulk_batch_size(["pk", "pk"] + fields, objs) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size requires_casting = connection.features.requires_casted_case_in_updates batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size)) updates = [] for batch_objs in batches: update_kwargs = {} for field in fields: when_statements = [] for obj in batch_objs: attr = getattr(obj, field.attname) if not hasattr(attr, "resolve_expression"): attr = Value(attr, output_field=field) when_statements.append(When(pk=obj.pk, then=attr)) case_statement = Case(*when_statements, output_field=field) if requires_casting: case_statement = Cast(case_statement, output_field=field) update_kwargs[field.attname] = case_statement updates.append(([obj.pk for obj in batch_objs], update_kwargs)) rows_updated = 0 queryset = self.using(self.db) with transaction.atomic(using=self.db, savepoint=False): for pks, update_kwargs in updates: rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs) return rows_updated bulk_update.alters_data = True async def abulk_update(self, objs, fields, batch_size=None): return await sync_to_async(self.bulk_update)( objs=objs, fields=fields, batch_size=batch_size, ) abulk_update.alters_data = True def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: return self.get(**kwargs), False except self.model.DoesNotExist: params = self._extract_model_params(defaults, **kwargs) # Try to create an object using passed params. try: with transaction.atomic(using=self.db): params = dict(resolve_callables(params)) return self.create(**params), True except IntegrityError: try: return self.get(**kwargs), False except self.model.DoesNotExist: pass raise async def aget_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.get_or_create)( defaults=defaults, **kwargs, ) def update_or_create(self, defaults=None, create_defaults=None, **kwargs): """ Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Optionally, an object can be created with different values than defaults by using create_defaults. Return a tuple (object, created), where created is a boolean specifying whether an object was created. """ if create_defaults is None: update_defaults = create_defaults = defaults or {} else: update_defaults = defaults or {} self._for_write = True with transaction.atomic(using=self.db): # Lock the row so that a concurrent update is blocked until # update_or_create() has performed its save. obj, created = self.select_for_update().get_or_create( create_defaults, **kwargs ) if created: return obj, created for k, v in resolve_callables(update_defaults): setattr(obj, k, v) update_fields = set(update_defaults) concrete_field_names = self.model._meta._non_pk_concrete_field_names # update_fields does not support non-concrete fields. if concrete_field_names.issuperset(update_fields): # Add fields which are set on pre_save(), e.g. auto_now fields. # This is to maintain backward compatibility as these fields # are not updated unless explicitly specified in the # update_fields list. for field in self.model._meta.local_concrete_fields: if not ( field.primary_key or field.__class__.pre_save is Field.pre_save ): update_fields.add(field.name) if field.name != field.attname: update_fields.add(field.attname) obj.save(using=self.db, update_fields=update_fields) else: obj.save(using=self.db) return obj, False async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs): return await sync_to_async(self.update_or_create)( defaults=defaults, create_defaults=create_defaults, **kwargs, ) def _extract_model_params(self, defaults, **kwargs): """ Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create(). """ defaults = defaults or {} params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) property_names = self.model._meta._property_names invalid_params = [] for param in params: try: self.model._meta.get_field(param) except exceptions.FieldDoesNotExist: # It's okay to use a model's property if it has a setter. if not (param in property_names and getattr(self.model, param).fset): invalid_params.append(param) if invalid_params: raise exceptions.FieldError( "Invalid field name(s) for model %s: '%s'." % ( self.model._meta.object_name, "', '".join(sorted(invalid_params)), ) ) return params def _earliest(self, *fields): """ Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by. """ if fields: order_by = fields else: order_by = getattr(self.model._meta, "get_latest_by") if order_by and not isinstance(order_by, (tuple, list)): order_by = (order_by,) if order_by is None: raise ValueError( "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta." ) obj = self._chain() obj.query.set_limits(high=1) obj.query.clear_ordering(force=True) obj.query.add_ordering(*order_by) return obj.get() def earliest(self, *fields): if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self._earliest(*fields) async def aearliest(self, *fields): return await sync_to_async(self.earliest)(*fields) def latest(self, *fields): """ Return the latest object according to fields (if given) or by the model's Meta.get_latest_by. """ if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self.reverse()._earliest(*fields) async def alatest(self, *fields): return await sync_to_async(self.latest)(*fields) def first(self): """Return the first object of a query or None if no match is found.""" if self.ordered: queryset = self else: self._check_ordering_first_last_queryset_aggregation(method="first") queryset = self.order_by("pk") for obj in queryset[:1]: return obj async def afirst(self): return await sync_to_async(self.first)() def last(self): """Return the last object of a query or None if no match is found.""" if self.ordered: queryset = self.reverse() else: self._check_ordering_first_last_queryset_aggregation(method="last") queryset = self.order_by("-pk") for obj in queryset[:1]: return obj async def alast(self): return await sync_to_async(self.last)() def in_bulk(self, id_list=None, *, field_name="pk"): """ Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet. """ if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().") opts = self.model._meta unique_fields = [ constraint.fields[0] for constraint in opts.total_unique_constraints if len(constraint.fields) == 1 ] if ( field_name != "pk" and not opts.get_field(field_name).unique and field_name not in unique_fields and self.query.distinct_fields != (field_name,) ): raise ValueError( "in_bulk()'s field_name must be a unique field but %r isn't." % field_name ) if id_list is not None: if not id_list: return {} filter_key = "{}__in".format(field_name) batch_size = connections[self.db].features.max_query_params id_list = tuple(id_list) # If the database has a limit on the number of query parameters # (e.g. SQLite), retrieve objects in batches if necessary. if batch_size and batch_size < len(id_list): qs = () for offset in range(0, len(id_list), batch_size): batch = id_list[offset : offset + batch_size] qs += tuple(self.filter(**{filter_key: batch})) else: qs = self.filter(**{filter_key: id_list}) else: qs = self._chain() return {getattr(obj, field_name): obj for obj in qs} async def ain_bulk(self, id_list=None, *, field_name="pk"): return await sync_to_async(self.in_bulk)( id_list=id_list, field_name=field_name, ) def delete(self): """Delete the records in the current QuerySet.""" self._not_support_combined_queries("delete") if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with delete().") if self.query.distinct or self.query.distinct_fields: raise TypeError("Cannot call delete() after .distinct().") if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") del_query = self._chain() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force=True) collector = Collector(using=del_query.db, origin=self) collector.collect(del_query) deleted, _rows_count = collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None return deleted, _rows_count delete.alters_data = True delete.queryset_only = True async def adelete(self): return await sync_to_async(self.delete)() adelete.alters_data = True adelete.queryset_only = True def _raw_delete(self, using): """ Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades. """ query = self.query.clone() query.__class__ = sql.DeleteQuery cursor = query.get_compiler(using).execute_sql(CURSOR) if cursor: with cursor: return cursor.rowcount return 0 _raw_delete.alters_data = True def update(self, **kwargs): """ Update all elements in the current QuerySet, setting all the given fields to the appropriate values. """ self._not_support_combined_queries("update") if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") self._for_write = True query = self.query.chain(sql.UpdateQuery) query.add_update_values(kwargs) # Inline annotations in order_by(), if possible. new_order_by = [] for col in query.order_by: alias = col descending = False if isinstance(alias, str) and alias.startswith("-"): alias = alias.removeprefix("-") descending = True if annotation := query.annotations.get(alias): if getattr(annotation, "contains_aggregate", False): raise exceptions.FieldError( f"Cannot update when ordering by an aggregate: {annotation}" ) if descending: annotation = annotation.desc() new_order_by.append(annotation) else: new_order_by.append(col) query.order_by = tuple(new_order_by) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} with transaction.mark_for_rollback_on_error(using=self.db): rows = query.get_compiler(self.db).execute_sql(CURSOR) self._result_cache = None return rows update.alters_data = True async def aupdate(self, **kwargs): return await sync_to_async(self.update)(**kwargs) aupdate.alters_data = True def _update(self, values): """ A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") query = self.query.chain(sql.UpdateQuery) query.add_update_fields(values) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} self._result_cache = None return query.get_compiler(self.db).execute_sql(CURSOR) _update.alters_data = True _update.queryset_only = False def exists(self): """ Return True if the QuerySet would have any results, False otherwise. """ if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) async def aexists(self): return await sync_to_async(self.exists)() def contains(self, obj): """ Return True if the QuerySet contains the provided obj, False otherwise. """ self._not_support_combined_queries("contains") if self._fields is not None: raise TypeError( "Cannot call QuerySet.contains() after .values() or .values_list()." ) try: if obj._meta.concrete_model != self.model._meta.concrete_model: return False except AttributeError: raise TypeError("'obj' must be a model instance.") if obj.pk is None: raise ValueError("QuerySet.contains() cannot be used on unsaved objects.") if self._result_cache is not None: return obj in self._result_cache return self.filter(pk=obj.pk).exists() async def acontains(self, obj): return await sync_to_async(self.contains)(obj=obj) def _prefetch_related_objects(self): # This method can only be called once the result cache has been filled. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def explain(self, *, format=None, **options): """ Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results. """ return self.query.explain(using=self.db, format=format, **options) async def aexplain(self, *, format=None, **options): return await sync_to_async(self.explain)(format=format, **options) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=(), translations=None, using=None): if using is None: using = self.db qs = RawQuerySet( raw_query, model=self.model, params=params, translations=translations, using=using, ) qs._prefetch_related_lookups = self._prefetch_related_lookups[:] return qs def _values(self, *fields, **expressions): clone = self._chain() if expressions: clone = clone.annotate(**expressions) clone._fields = fields clone.query.set_values(fields) return clone def values(self, *fields, **expressions): fields += tuple(expressions) clone = self._values(*fields, **expressions) clone._iterable_class = ValuesIterable return clone def values_list(self, *fields, flat=False, named=False): if flat and named: raise TypeError("'flat' and 'named' can't be used together.") if flat and len(fields) > 1: raise TypeError( "'flat' is not valid when values_list is called with more than one " "field." ) field_names = {f for f in fields if not hasattr(f, "resolve_expression")} _fields = [] expressions = {} counter = 1 for field in fields: if hasattr(field, "resolve_expression"): field_id_prefix = getattr( field, "default_alias", field.__class__.__name__.lower() ) while True: field_id = field_id_prefix + str(counter) counter += 1 if field_id not in field_names: break expressions[field_id] = field _fields.append(field_id) else: _fields.append(field) clone = self._values(*_fields, **expressions) clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) return clone def dates(self, field_name, kind, order="ASC"): """ Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day"): raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.") if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") return ( self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name), ) .values_list("datefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datefield") ) def datetimes(self, field_name, kind, order="ASC", tzinfo=None): """ Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day", "hour", "minute", "second"): raise ValueError( "'kind' must be one of 'year', 'month', 'week', 'day', " "'hour', 'minute', or 'second'." ) if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return ( self.annotate( datetimefield=Trunc( field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo, ), plain_field=F(field_name), ) .values_list("datetimefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datetimefield") ) def none(self): """Return an empty QuerySet.""" clone = self._chain() clone.query.set_empty() return clone ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._chain() def filter(self, *args, **kwargs): """ Return a new QuerySet instance with the args ANDed to the existing set. """ self._not_support_combined_queries("filter") return self._filter_or_exclude(False, args, kwargs) def exclude(self, *args, **kwargs): """ Return a new QuerySet instance with NOT (args) ANDed to the existing set. """ self._not_support_combined_queries("exclude") return self._filter_or_exclude(True, args, kwargs) def _filter_or_exclude(self, negate, args, kwargs): if (args or kwargs) and self.query.is_sliced: raise TypeError("Cannot filter a query once a slice has been taken.") clone = self._chain() if self._defer_next_filter: self._defer_next_filter = False clone._deferred_filter = negate, args, kwargs else: clone._filter_or_exclude_inplace(negate, args, kwargs) return clone def _filter_or_exclude_inplace(self, negate, args, kwargs): if negate: self._query.add_q(~Q(*args, **kwargs)) else: self._query.add_q(Q(*args, **kwargs)) def complex_filter(self, filter_obj): """ Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q): clone = self._chain() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(False, args=(), kwargs=filter_obj) def _combinator_query(self, combinator, *other_qs, all=False): # Clone the query to inherit the select list and everything clone = self._chain() # Clear limits and ordering so they can be reapplied clone.query.clear_ordering(force=True) clone.query.clear_limits() clone.query.combined_queries = (self.query,) + tuple( qs.query for qs in other_qs ) clone.query.combinator = combinator clone.query.combinator_all = all return clone def union(self, *other_qs, all=False): # If the query is an EmptyQuerySet, combine all nonempty querysets. if isinstance(self, EmptyQuerySet): qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)] if not qs: return self if len(qs) == 1: return qs[0] return qs[0]._combinator_query("union", *qs[1:], all=all) return self._combinator_query("union", *other_qs, all=all) def intersection(self, *other_qs): # If any query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self for other in other_qs: if isinstance(other, EmptyQuerySet): return other return self._combinator_query("intersection", *other_qs) def difference(self, *other_qs): # If the query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self return self._combinator_query("difference", *other_qs) def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError("The nowait option cannot be used with skip_locked.") obj = self._chain() obj._for_write = True obj.query.select_for_update = True obj.query.select_for_update_nowait = nowait obj.query.select_for_update_skip_locked = skip_locked obj.query.select_for_update_of = of obj.query.select_for_no_key_update = no_key return obj def select_related(self, *fields): """ Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list. """ self._not_support_combined_queries("select_related") if self._fields is not None: raise TypeError( "Cannot call select_related() after .values() or .values_list()" ) obj = self._chain() if fields == (None,): obj.query.select_related = False elif fields: obj.query.add_select_related(fields) else: obj.query.select_related = True return obj def prefetch_related(self, *lookups): """ Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list. """ self._not_support_combined_queries("prefetch_related") clone = self._chain() if lookups == (None,): clone._prefetch_related_lookups = () else: for lookup in lookups: if isinstance(lookup, Prefetch): lookup = lookup.prefetch_to lookup = lookup.split(LOOKUP_SEP, 1)[0] if lookup in self.query._filtered_relations: raise ValueError( "prefetch_related() is not supported with FilteredRelation." ) clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ self._not_support_combined_queries("annotate") return self._annotate(args, kwargs, select=True) def alias(self, *args, **kwargs): """ Return a query set with added aliases for extra data or aggregations. """ self._not_support_combined_queries("alias") return self._annotate(args, kwargs, select=False) def _annotate(self, args, kwargs, select=True): self._validate_values_are_expressions( args + tuple(kwargs.values()), method_name="annotate" ) annotations = {} for arg in args: # The default_alias property may raise a TypeError. try: if arg.default_alias in kwargs: raise ValueError( "The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias ) except TypeError: raise TypeError("Complex annotations require an alias") annotations[arg.default_alias] = arg annotations.update(kwargs) clone = self._chain() names = self._fields if names is None: names = set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") else (field.name,) for field in self.model._meta.get_fields() ) ) for alias, annotation in annotations.items(): if alias in names: raise ValueError( "The annotation '%s' conflicts with a field on " "the model." % alias ) if isinstance(annotation, FilteredRelation): clone.query.add_filtered_relation(annotation, alias) else: clone.query.add_annotation( annotation, alias, select=select, ) for alias, annotation in clone.query.annotations.items(): if alias in annotations and annotation.contains_aggregate: if clone._fields is None: clone.query.group_by = True else: clone.query.set_group_by() break return clone def order_by(self, *field_names): """Return a new QuerySet instance with the ordering changed.""" if self.query.is_sliced: raise TypeError("Cannot reorder a query once a slice has been taken.") obj = self._chain() obj.query.clear_ordering(force=True, clear_default=False) obj.query.add_ordering(*field_names) return obj def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ self._not_support_combined_queries("distinct") if self.query.is_sliced: raise TypeError( "Cannot create distinct fields once a slice has been taken." ) obj = self._chain() obj.query.add_distinct_fields(*field_names) return obj def extra( self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None, ): """Add extra SQL fragments to the query.""" self._not_support_combined_queries("extra") if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") clone = self._chain() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """Reverse the ordering of the QuerySet.""" if self.query.is_sliced: raise TypeError("Cannot reverse a query once a slice has been taken.") clone = self._chain() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals. """ self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._chain() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ self._not_support_combined_queries("only") if self._fields is not None: raise TypeError("Cannot call only() after .values() or .values_list()") if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") for field in fields: field = field.split(LOOKUP_SEP, 1)[0] if field in self.query._filtered_relations: raise ValueError("only() is not supported with FilteredRelation.") clone = self._chain() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """Select which database this QuerySet should execute against.""" clone = self._chain() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### @property def ordered(self): """ Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty). """ if isinstance(self, EmptyQuerySet): return True if self.query.extra_order_by or self.query.order_by: return True elif ( self.query.default_ordering and self.query.get_meta().ordering and # A default ordering doesn't affect GROUP BY queries. not self.query.group_by ): return True else: return False @property def db(self): """Return the database used if this query is executed now.""" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints) ################### # PRIVATE METHODS # ################### def _insert( self, objs, fields, returning_fields=None, raw=False, using=None, on_conflict=None, update_fields=None, unique_fields=None, ): """ Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: using = self.db query = sql.InsertQuery( self.model, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) query.insert_values(fields, objs, raw=raw) return query.get_compiler(using=using).execute_sql(returning_fields) _insert.alters_data = True _insert.queryset_only = False def _batched_insert( self, objs, fields, batch_size, on_conflict=None, update_fields=None, unique_fields=None, ): """ Helper method for bulk_create() to insert objs one batch at a time. """ connection = connections[self.db] ops = connection.ops max_batch_size = max(ops.bulk_batch_size(fields, objs), 1) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size inserted_rows = [] bulk_return = connection.features.can_return_rows_from_bulk_insert for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: if bulk_return and on_conflict is None: inserted_rows.extend( self._insert( item, fields=fields, using=self.db, returning_fields=self.model._meta.db_returning_fields, ) ) else: self._insert( item, fields=fields, using=self.db, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) return inserted_rows def _chain(self): """ Return a copy of the current QuerySet that's ready for another operation. """ obj = self._clone() if obj._sticky_filter: obj.query.filter_is_sticky = True obj._sticky_filter = False return obj def _clone(self): """ Return a copy of the current QuerySet. A lightweight alternative to deepcopy(). """ c = self.__class__( model=self.model, query=self.query.chain(), using=self._db, hints=self._hints, ) c._sticky_filter = self._sticky_filter c._for_write = self._for_write c._prefetch_related_lookups = self._prefetch_related_lookups[:] c._known_related_objects = self._known_related_objects c._iterable_class = self._iterable_class c._fields = self._fields return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self._iterable_class(self)) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def _next_is_sticky(self): """ Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """Check that two QuerySet classes may be merged.""" if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.extra_select) or set(self.query.annotation_select) != set(other.query.annotation_select) ): raise TypeError( "Merging '%s' classes must involve the same values in each case." % self.__class__.__name__ ) def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects) def resolve_expression(self, *args, **kwargs): if self._fields and len(self._fields) > 1: # values() queryset can only be used as nested queries # if they are set up to select only a single field. raise TypeError("Cannot use multi-field values as a filter value.") query = self.query.resolve_expression(*args, **kwargs) query._db = self._db return query resolve_expression.queryset_only = True def _add_hints(self, **hints): """ Update hinting information for use by routers. Add new key/values or overwrite existing key/values. """ self._hints.update(hints) def _has_filters(self): """ Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False. """ return self.query.has_filters() @staticmethod def _validate_values_are_expressions(values, method_name): invalid_args = sorted( str(arg) for arg in values if not hasattr(arg, "resolve_expression") ) if invalid_args: raise TypeError( "QuerySet.%s() received non-expression(s): %s." % ( method_name, ", ".join(invalid_args), ) ) def _not_support_combined_queries(self, operation_name): if self.query.combinator: raise NotSupportedError( "Calling QuerySet.%s() after %s() is not supported." % (operation_name, self.query.combinator) ) def _check_operator_queryset(self, other, operator_): if self.query.combinator or other.query.combinator: raise TypeError(f"Cannot use {operator_} operator with combined queryset.") def _check_ordering_first_last_queryset_aggregation(self, method): if isinstance(self.query.group_by, tuple) and not any( col.output_field is self.model._meta.pk for col in self.query.group_by ): raise TypeError( f"Cannot use QuerySet.{method}() on an unordered queryset performing " f"aggregation. Add an ordering with order_by()." ) class InstanceCheckMeta(type): def __instancecheck__(self, instance): return isinstance(instance, QuerySet) and instance.query.is_empty() class EmptyQuerySet(metaclass=InstanceCheckMeta): """ Marker class to checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True """ def __init__(self, *args, **kwargs): raise TypeError("EmptyQuerySet can't be instantiated") class RawQuerySet: """ Provide an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__( self, raw_query, model=None, query=None, params=(), translations=None, using=None, hints=None, ): self.raw_query = raw_query self.model = model self._db = using self._hints = hints or {} self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params self.translations = translations or {} self._result_cache = None self._prefetch_related_lookups = () self._prefetch_done = False def resolve_model_init_order(self): """Resolve the init field names and value positions.""" converter = connections[self.db].introspection.identifier_converter model_init_fields = [ f for f in self.model._meta.fields if converter(f.column) in self.columns ] annotation_fields = [ (column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields ] model_init_order = [ self.columns.index(converter(f.column)) for f in model_init_fields ] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields def prefetch_related(self, *lookups): """Same as QuerySet.prefetch_related()""" clone = self._clone() if lookups == (None,): clone._prefetch_related_lookups = () else: clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def _prefetch_related_objects(self): prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def _clone(self): """Same as QuerySet._clone()""" c = self.__class__( self.raw_query, model=self.model, query=self.query, params=self.params, translations=self.translations, using=self._db, hints=self._hints, ) c._prefetch_related_lookups = self._prefetch_related_lookups[:] return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def __len__(self): self._fetch_all() return len(self._result_cache) def __bool__(self): self._fetch_all() return bool(self._result_cache) def __iter__(self): self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def iterator(self): yield from RawModelIterable(self) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.query) def __getitem__(self, k): return list(self)[k] @property def db(self): """Return the database used if this query is executed now.""" return self._db or router.db_for_read(self.model, **self._hints) def using(self, alias): """Select the database this RawQuerySet should execute against.""" return RawQuerySet( self.raw_query, model=self.model, query=self.query.chain(using=alias), params=self.params, translations=self.translations, using=alias, ) @cached_property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for query_name, model_name in self.translations.items(): # Ignore translations for nonexistent column names try: index = columns.index(query_name) except ValueError: pass else: columns[index] = model_name return columns @cached_property def model_fields(self): """A dict mapping column names to model field names.""" converter = connections[self.db].introspection.identifier_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() model_fields[converter(column)] = field return model_fields class Prefetch: def __init__(self, lookup, queryset=None, to_attr=None): # `prefetch_through` is the path we traverse to perform the prefetch. self.prefetch_through = lookup # `prefetch_to` is the path to the attribute that stores the result. self.prefetch_to = lookup if queryset is not None and ( isinstance(queryset, RawQuerySet) or ( hasattr(queryset, "_iterable_class") and not issubclass(queryset._iterable_class, ModelIterable) ) ): raise ValueError( "Prefetch querysets cannot use raw(), values(), and values_list()." ) if to_attr: self.prefetch_to = LOOKUP_SEP.join( lookup.split(LOOKUP_SEP)[:-1] + [to_attr] ) self.queryset = queryset self.to_attr = to_attr def __getstate__(self): obj_dict = self.__dict__.copy() if self.queryset is not None: queryset = self.queryset._chain() # Prevent the QuerySet from being evaluated queryset._result_cache = [] queryset._prefetch_done = True obj_dict["queryset"] = queryset return obj_dict def add_prefix(self, prefix): self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to def get_current_prefetch_to(self, level): return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[: level + 1]) def get_current_to_attr(self, level): parts = self.prefetch_to.split(LOOKUP_SEP) to_attr = parts[level] as_attr = self.to_attr and level == len(parts) - 1 return to_attr, as_attr def get_current_queryset(self, level): if self.get_current_prefetch_to(level) == self.prefetch_to: return self.queryset return None def __eq__(self, other): if not isinstance(other, Prefetch): return NotImplemented return self.prefetch_to == other.prefetch_to def __hash__(self): return hash((self.__class__, self.prefetch_to)) def normalize_prefetch_lookups(lookups, prefix=None): """Normalize lookups into Prefetch objects.""" ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ret.append(lookup) return ret def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if not model_instances: return # nothing to do # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. done_queries = {} # dictionary of things like 'foo__bar': [results] auto_lookups = set() # we add to this as we go through. followed_descriptors = set() # recursion protection all_lookups = normalize_prefetch_lookups(reversed(related_lookups)) while all_lookups: lookup = all_lookups.pop() if lookup.prefetch_to in done_queries: if lookup.queryset is not None: raise ValueError( "'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to ) continue # Top level, the list of objects to decorate is the result cache # from the primary QuerySet. It won't be for deeper levels. obj_list = model_instances through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) for level, through_attr in enumerate(through_attrs): # Prepare main instances if not obj_list: break prefetch_to = lookup.get_current_prefetch_to(level) if prefetch_to in done_queries: # Skip any prefetching, and any object preparation obj_list = done_queries[prefetch_to] continue # Prepare objects: good_objects = True for obj in obj_list: # Since prefetching can re-use instances, it is possible to have # the same instance multiple times in obj_list, so obj might # already be prepared. if not hasattr(obj, "_prefetched_objects_cache"): try: obj._prefetched_objects_cache = {} except (AttributeError, TypeError): # Must be an immutable object from # values_list(flat=True), for example (TypeError) or # a QuerySet subclass that isn't returning Model # instances (AttributeError), either in Django or a 3rd # party. prefetch_related() doesn't make sense, so quit. good_objects = False break if not good_objects: break # Descend down tree # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] to_attr = lookup.get_current_to_attr(level)[0] prefetcher, descriptor, attr_found, is_fetched = get_prefetcher( first_obj, through_attr, to_attr ) if not attr_found: raise AttributeError( "Cannot find '%s' on %s object, '%s' is an invalid " "parameter to prefetch_related()" % ( through_attr, first_obj.__class__.__name__, lookup.prefetch_through, ) ) if level == len(through_attrs) - 1 and prefetcher is None: # Last one, this *must* resolve to something that supports # prefetching, otherwise there is no point adding it and the # developer asking for it has made a mistake. raise ValueError( "'%s' does not resolve to an item that supports " "prefetching - this is an invalid parameter to " "prefetch_related()." % lookup.prefetch_through ) obj_to_fetch = None if prefetcher is not None: obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)] if obj_to_fetch: obj_list, additional_lookups = prefetch_one_level( obj_to_fetch, prefetcher, lookup, level, ) # We need to ensure we don't keep adding lookups from the # same relationships to stop infinite recursion. So, if we # are already on an automatically added lookup, don't add # the new lookups from relationships we've seen already. if not ( prefetch_to in done_queries and lookup in auto_lookups and descriptor in followed_descriptors ): done_queries[prefetch_to] = obj_list new_lookups = normalize_prefetch_lookups( reversed(additional_lookups), prefetch_to ) auto_lookups.update(new_lookups) all_lookups.extend(new_lookups) followed_descriptors.add(descriptor) else: # Either a singly related object that has already been fetched # (e.g. via select_related), or hopefully some other property # that doesn't support prefetching but needs to be traversed. # We replace the current list of parent objects with the list # of related objects, filtering out empty or missing values so # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: if through_attr in getattr(obj, "_prefetched_objects_cache", ()): # If related objects have been prefetched, use the # cache rather than the object's through_attr. new_obj = list(obj._prefetched_objects_cache.get(through_attr)) else: try: new_obj = getattr(obj, through_attr) except exceptions.ObjectDoesNotExist: continue if new_obj is None: continue # We special-case `list` rather than something more generic # like `Iterable` because we don't want to accidentally match # user models that define __iter__. if isinstance(new_obj, list): new_obj_list.extend(new_obj) else: new_obj_list.append(new_obj) obj_list = new_obj_list def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, find an object that has a get_prefetch_queryset(). Return a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute was not found at all, a function that takes an instance and returns a boolean that is True if the attribute has already been fetched for that instance) """ def has_to_attr_attribute(instance): return hasattr(instance, to_attr) prefetcher = None is_fetched = has_to_attr_attribute # For singly related objects, we have to avoid getting the attribute # from the object, as this will trigger the query. So we first try # on the class, in order to get the descriptor object. rel_obj_descriptor = getattr(instance.__class__, through_attr, None) if rel_obj_descriptor is None: attr_found = hasattr(instance, through_attr) else: attr_found = True if rel_obj_descriptor: # singly related object, descriptor object has the # get_prefetch_queryset() method. if hasattr(rel_obj_descriptor, "get_prefetch_queryset"): prefetcher = rel_obj_descriptor is_fetched = rel_obj_descriptor.is_cached else: # descriptor doesn't support prefetching, so we go ahead and get # the attribute on the instance rather than the class to # support many related managers rel_obj = getattr(instance, through_attr) if hasattr(rel_obj, "get_prefetch_queryset"): prefetcher = rel_obj if through_attr != to_attr: # Special case cached_property instances because hasattr # triggers attribute computation and assignment. if isinstance( getattr(instance.__class__, to_attr, None), cached_property ): def has_cached_property(instance): return to_attr in instance.__dict__ is_fetched = has_cached_property else: def in_prefetched_cache(instance): return through_attr in instance._prefetched_objects_cache is_fetched = in_prefetched_cache return prefetcher, rel_obj_descriptor, attr_found, is_fetched def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects(). Run prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. Return the prefetched objects along with any additional prefetches that must be done due to prefetch_related lookups found from default managers. """ # prefetcher must have a method get_prefetch_queryset() which takes a list # of instances, and returns a tuple: # (queryset of instances of self.model that are related to passed in instances, # callable that gets value to be matched for returned instances, # callable that gets value to be matched for passed in instances, # boolean that is True for singly related objects, # cache or field name to assign to, # boolean that is True when the previous argument is a cache name vs a field name). # The 'values to be matched' must be hashable as they will be used # in a dictionary. ( rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor, ) = prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)) # We have to handle the possibility that the QuerySet we just got back # contains some prefetch_related lookups. We don't want to trigger the # prefetch_related functionality by evaluating the query. Rather, we need # to merge in the prefetch_related lookups. # Copy the lookups in case it is a Prefetch object which could be reused # later (happens in nested prefetch_related). additional_lookups = [ copy.copy(additional_lookup) for additional_lookup in getattr(rel_qs, "_prefetch_related_lookups", ()) ] if additional_lookups: # Don't need to clone because the manager should have given us a fresh # instance, so we access an internal instead of using public interface # for performance reasons. rel_qs._prefetch_related_lookups = () all_related_objects = list(rel_qs) rel_obj_cache = {} for rel_obj in all_related_objects: rel_attr_val = rel_obj_attr(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) to_attr, as_attr = lookup.get_current_to_attr(level) # Make sure `to_attr` does not conflict with a field. if as_attr and instances: # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. model = instances[0].__class__ try: model._meta.get_field(to_attr) except exceptions.FieldDoesNotExist: pass else: msg = "to_attr={} conflicts with a field on the {} model." raise ValueError(msg.format(to_attr, model.__name__)) # Whether or not we're prefetching the last part of the lookup. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level for obj in instances: instance_attr_val = instance_attr(obj) vals = rel_obj_cache.get(instance_attr_val, []) if single: val = vals[0] if vals else None if as_attr: # A to_attr has been given for the prefetch. setattr(obj, to_attr, val) elif is_descriptor: # cache_name points to a field name in obj. # This field is a descriptor for a related object. setattr(obj, cache_name, val) else: # No to_attr has been given for this prefetch operation and the # cache_name does not point to a descriptor. Store the value of # the field in the object's field cache. obj._state.fields_cache[cache_name] = val else: if as_attr: setattr(obj, to_attr, vals) else: manager = getattr(obj, to_attr) if leaf and lookup.queryset is not None: qs = manager._apply_rel_filters(lookup.queryset) else: qs = manager.get_queryset() qs._result_cache = vals # We don't want the individual qs doing prefetch_related now, # since we have merged this into the current work. qs._prefetch_done = True obj._prefetched_objects_cache[cache_name] = qs return all_related_objects, additional_lookups class RelatedPopulator: """ RelatedPopulator is used for select_related() object instantiation. The idea is that each select_related() model will be populated by a different RelatedPopulator instance. The RelatedPopulator instances get klass_info and select (computed in SQLCompiler) plus the used db as input for initialization. That data is used to compute which columns to use, how to instantiate the model, and how to populate the links between the objects. The actual creation of the objects is done in populate() method. This method gets row and from_obj as input and populates the select_related() model instance. """ def __init__(self, klass_info, select, db): self.db = db # Pre-compute needed attributes. The attributes are: # - model_cls: the possibly deferred model class to instantiate # - either: # - cols_start, cols_end: usually the columns in the row are # in the same order model_cls.__init__ expects them, so we # can instantiate by model_cls(*row[cols_start:cols_end]) # - reorder_for_init: When select_related descends to a child # class, then we want to reuse the already selected parent # data. However, in this case the parent data isn't necessarily # in the same order that Model.__init__ expects it to be, so # we have to reorder the parent data. The reorder_for_init # attribute contains a function used to reorder the field data # in the order __init__ expects it. # - pk_idx: the index of the primary key field in the reordered # model data. Used to check if a related object exists at all. # - init_list: the field attnames fetched from the database. For # deferred models this isn't the same as all attnames of the # model's fields. # - related_populators: a list of RelatedPopulator instances if # select_related() descends to related models from this model. # - local_setter, remote_setter: Methods to set cached values on # the object being populated and on the remote object. Usually # these are Field.set_cached_value() methods. select_fields = klass_info["select_fields"] from_parent = klass_info["from_parent"] if not from_parent: self.cols_start = select_fields[0] self.cols_end = select_fields[-1] + 1 self.init_list = [ f[0].target.attname for f in select[self.cols_start : self.cols_end] ] self.reorder_for_init = None else: attname_indexes = { select[idx][0].target.attname: idx for idx in select_fields } model_init_attnames = ( f.attname for f in klass_info["model"]._meta.concrete_fields ) self.init_list = [ attname for attname in model_init_attnames if attname in attname_indexes ] self.reorder_for_init = operator.itemgetter( *[attname_indexes[attname] for attname in self.init_list] ) self.model_cls = klass_info["model"] self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) self.related_populators = get_related_populators(klass_info, select, self.db) self.local_setter = klass_info["local_setter"] self.remote_setter = klass_info["remote_setter"] def populate(self, row, from_obj): if self.reorder_for_init: obj_data = self.reorder_for_init(row) else: obj_data = row[self.cols_start : self.cols_end] if obj_data[self.pk_idx] is None: obj = None else: obj = self.model_cls.from_db(self.db, self.init_list, obj_data) for rel_iter in self.related_populators: rel_iter.populate(row, obj) self.local_setter(from_obj, obj) if obj is not None: self.remote_setter(obj, from_obj) def get_related_populators(klass_info, select, db): iterators = [] related_klass_infos = klass_info.get("related_klass_infos", []) for rel_klass_info in related_klass_infos: rel_cls = RelatedPopulator(rel_klass_info, select, db) iterators.append(rel_cls) return iterators
ddd41308412696e426aa9c83d1191139071ad2f76bf567002fa0a0565e748cc6
import bisect import copy import inspect import warnings from collections import defaultdict from django.apps import apps from django.conf import settings from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.db import connections from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint from django.db.models.query_utils import PathInfo from django.utils.datastructures import ImmutableList, OrderedSet from django.utils.deprecation import RemovedInDjango51Warning from django.utils.functional import cached_property from django.utils.module_loading import import_string from django.utils.text import camel_case_to_spaces, format_lazy from django.utils.translation import override PROXY_PARENTS = object() EMPTY_RELATION_TREE = () IMMUTABLE_WARNING = ( "The return type of '%s' should never be mutated. If you want to manipulate this " "list for your own use, make a copy first." ) DEFAULT_NAMES = ( "verbose_name", "verbose_name_plural", "db_table", "db_table_comment", "ordering", "unique_together", "permissions", "get_latest_by", "order_with_respect_to", "app_label", "db_tablespace", "abstract", "managed", "proxy", "swappable", "auto_created", "index_together", # RemovedInDjango51Warning. "apps", "default_permissions", "select_on_save", "default_related_name", "required_db_features", "required_db_vendor", "base_manager_name", "default_manager_name", "indexes", "constraints", ) def normalize_together(option_together): """ option_together can be either 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 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_together 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_fields", "_non_pk_concrete_field_names", "_forward_fields_map", "managers", "managers_map", "base_manager", "default_manager", } REVERSE_PROPERTIES = {"related_objects", "fields_map", "_relation_tree"} default_apps = apps def __init__(self, meta, app_label=None): self._get_fields_cache = {} self.local_fields = [] self.local_many_to_many = [] self.private_fields = [] self.local_managers = [] self.base_manager_name = None self.default_manager_name = None self.model_name = None self.verbose_name = None self.verbose_name_plural = None self.db_table = "" self.db_table_comment = "" self.ordering = [] self._ordering_clash = False self.indexes = [] self.constraints = [] self.unique_together = [] self.index_together = [] # RemovedInDjango51Warning. self.select_on_save = False self.default_permissions = ("add", "change", "delete", "view") self.permissions = [] self.object_name = None self.app_label = app_label self.get_latest_by = None self.order_with_respect_to = None self.db_tablespace = settings.DEFAULT_TABLESPACE self.required_db_features = [] self.required_db_vendor = None self.meta = meta self.pk = None self.auto_field = None self.abstract = False self.managed = True self.proxy = False # For any class that is a proxy (including automatically created # classes for deferred object loading), proxy_for_model tells us # which class this model is proxying. Note that proxy_for_model # can create a chain of proxy models. For non-proxy models, the # variable is always None. self.proxy_for_model = None # For any non-abstract class, the concrete class is the model # in the end of the proxy_for_model chain. In particular, for # concrete models, the concrete_model is always the class itself. self.concrete_model = None self.swappable = None self.parents = {} self.auto_created = False # List of all lookups defined in ForeignKey 'limit_choices_to' options # from *other* models. Needed for some admin checks. Internal use only. self.related_fkey_lookups = [] # A custom app registry to use, if you're making a separate model set. self.apps = self.default_apps self.default_related_name = None @property def label(self): return "%s.%s" % (self.app_label, self.object_name) @property def label_lower(self): return "%s.%s" % (self.app_label, self.model_name) @property def app_config(self): # Don't go through get_app_config to avoid triggering imports. return self.apps.app_configs.get(self.app_label) def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith("_"): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) if self.index_together: warnings.warn( f"'index_together' is deprecated. Use 'Meta.indexes' in " f"{self.label!r} instead.", RemovedInDjango51Warning, ) # App label/class name interpolation for names of constraints and # indexes. if not getattr(cls._meta, "abstract", False): for attr_name in {"constraints", "indexes"}: objs = getattr(self, attr_name, []) setattr(self, attr_name, self._format_names_with_class(cls, objs)) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError( "'class Meta' got invalid attribute(s): %s" % ",".join(meta_attrs) ) else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name( self.db_table, connection.ops.max_name_length() ) def _format_names_with_class(self, cls, objs): """App label/class name interpolation for object names.""" new_objs = [] for obj in objs: obj = obj.clone() obj.name = obj.name % { "app_label": cls._meta.app_label.lower(), "class": cls.__name__.lower(), } new_objs.append(obj) return new_objs def _get_default_pk_class(self): pk_class_path = getattr( self.app_config, "default_auto_field", settings.DEFAULT_AUTO_FIELD, ) if self.app_config and self.app_config._is_default_auto_field_overridden: app_config_class = type(self.app_config) source = ( f"{app_config_class.__module__}." f"{app_config_class.__qualname__}.default_auto_field" ) else: source = "DEFAULT_AUTO_FIELD" if not pk_class_path: raise ImproperlyConfigured(f"{source} must not be empty.") try: pk_class = import_string(pk_class_path) except ImportError as e: msg = ( f"{source} refers to the module '{pk_class_path}' that could " f"not be imported." ) raise ImproperlyConfigured(msg) from e if not issubclass(pk_class, AutoField): raise ValueError( f"Primary key '{pk_class_path}' referred by {source} must " f"subclass AutoField." ) return pk_class def _prepare(self, model): if self.order_with_respect_to: # The app registry will not be ready at this point, so we cannot # use get_field(). query = self.order_with_respect_to try: self.order_with_respect_to = next( f for f in self._get_fields(reverse=False) if f.name == query or f.attname == query ) except StopIteration: raise FieldDoesNotExist( "%s has no field named '%s'" % (self.object_name, query) ) self.ordering = ("_order",) if not any( isinstance(field, OrderWrt) for field in model._meta.local_fields ): model.add_to_class("_order", OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = next(iter(self.parents.values())) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [ fld for fld in self.local_fields if fld.name == field.name ] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: pk_class = self._get_default_pk_class() auto = pk_class(verbose_name="ID", primary_key=True, auto_created=True) model.add_to_class("id", auto) def add_manager(self, manager): self.local_managers.append(manager) self._expire_cache() def add_field(self, field, private=False): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into # self.many_to_many. if private: self.private_fields.append(field) elif field.is_relation and field.many_to_many: bisect.insort(self.local_many_to_many, field) else: bisect.insort(self.local_fields, field) self.setup_pk(field) # If the field being added is a relation to another known field, # expire the cache on this field and the forward cache on the field # being referenced, because there will be new relationships in the # cache. Otherwise, expire the cache of references *to* this field. # The mechanism for getting at the related model is slightly odd - # ideally, we'd just ask for field.related_model. However, related_model # is a cached property, and all the models haven't been loaded yet, so # we need to make sure we don't cache a string reference. if ( field.is_relation and hasattr(field.remote_field, "model") and field.remote_field.model ): try: field.remote_field.model._meta._expire_cache(forward=False) except AttributeError: pass self._expire_cache() else: self._expire_cache(reverse=False) def setup_pk(self, field): if not self.pk and field.primary_key: self.pk = field field.serialize = False def setup_proxy(self, target): """ Do the internal setup so that the current model is a proxy for "target". """ self.pk = target._meta.pk self.proxy_for_model = target self.db_table = target._meta.db_table def __repr__(self): return "<Options for %s>" % self.object_name def __str__(self): return self.label_lower def can_migrate(self, connection): """ Return True if the model can/should be migrated on the `connection`. `connection` can be either a real connection or a connection alias. """ if self.proxy or self.swapped or not self.managed: return False if isinstance(connection, str): connection = connections[connection] if self.required_db_vendor: return self.required_db_vendor == connection.vendor if self.required_db_features: return all( getattr(connection.features, feat, False) for feat in self.required_db_features ) return True @property def verbose_name_raw(self): """Return the untranslated verbose name.""" with override(None): return str(self.verbose_name) @property def swapped(self): """ Has this model been swapped out for another? If so, return the model name of the replacement; otherwise, return None. For historical reasons, model name lookups using get_model() are case insensitive, so we make sure we are case insensitive here. """ if self.swappable: swapped_for = getattr(settings, self.swappable, None) if swapped_for: try: swapped_label, swapped_object = swapped_for.split(".") except ValueError: # setting not in the format app_label.model_name # raising ImproperlyConfigured here causes problems with # test cleanup code - instead it is raised in get_user_model # or as part of validation. return swapped_for if ( "%s.%s" % (swapped_label, swapped_object.lower()) != self.label_lower ): return swapped_for return None @cached_property def managers(self): managers = [] seen_managers = set() bases = (b for b in self.model.mro() if hasattr(b, "_meta")) for depth, base in enumerate(bases): for manager in base._meta.local_managers: if manager.name in seen_managers: continue manager = copy.copy(manager) manager.model = self.model seen_managers.add(manager.name) managers.append((depth, manager.creation_counter, manager)) return make_immutable_fields_list( "managers", (m[2] for m in sorted(managers)), ) @cached_property def managers_map(self): return {manager.name: manager for manager in self.managers} @cached_property def base_manager(self): base_manager_name = self.base_manager_name if not base_manager_name: # Get the first parent's base_manager_name if there's one. for parent in self.model.mro()[1:]: if hasattr(parent, "_meta"): if parent._base_manager.name != "_base_manager": base_manager_name = parent._base_manager.name break if base_manager_name: try: return self.managers_map[base_manager_name] except KeyError: raise ValueError( "%s has no manager named %r" % ( self.object_name, base_manager_name, ) ) manager = Manager() manager.name = "_base_manager" manager.model = self.model manager.auto_created = True return manager @cached_property def default_manager(self): default_manager_name = self.default_manager_name if not default_manager_name and not self.local_managers: # Get the first parent's default_manager_name if there's one. for parent in self.model.mro()[1:]: if hasattr(parent, "_meta"): default_manager_name = parent._meta.default_manager_name break if default_manager_name: try: return self.managers_map[default_manager_name] except KeyError: raise ValueError( "%s has no manager named %r" % ( self.object_name, default_manager_name, ) ) if self.managers: return self.managers[0] @cached_property def fields(self): """ Return a list of all forward fields on the model and its parents, excluding ManyToManyFields. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ # For legacy reasons, the fields property should only contain forward # fields that are not private or with a m2m cardinality. Therefore we # pass these three filters as filters to the generator. # The third lambda is a longwinded way of checking f.related_model - we don't # use that property directly because related_model is a cached property, # and all the models may not have been loaded yet; we don't want to cache # the string reference to the related_model. def is_not_an_m2m_field(f): return not (f.is_relation and f.many_to_many) def is_not_a_generic_relation(f): return not (f.is_relation and f.one_to_many) def is_not_a_generic_foreign_key(f): return not ( f.is_relation and f.many_to_one and not (hasattr(f.remote_field, "model") and f.remote_field.model) ) return make_immutable_fields_list( "fields", ( f for f in self._get_fields(reverse=False) if is_not_an_m2m_field(f) and is_not_a_generic_relation(f) and is_not_a_generic_foreign_key(f) ), ) @cached_property def concrete_fields(self): """ Return a list of all concrete fields on the model and its parents. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ return make_immutable_fields_list( "concrete_fields", (f for f in self.fields if f.concrete) ) @cached_property def local_concrete_fields(self): """ Return a list of all concrete fields on the model. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ return make_immutable_fields_list( "local_concrete_fields", (f for f in self.local_fields if f.concrete) ) @cached_property def many_to_many(self): """ Return a list of all many to many fields on the model and its parents. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this list. """ return make_immutable_fields_list( "many_to_many", ( f for f in self._get_fields(reverse=False) if f.is_relation and f.many_to_many ), ) @cached_property def related_objects(self): """ Return all related objects pointing to the current model. The related objects can come from a one-to-one, one-to-many, or many-to-many field relation type. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ all_related_fields = self._get_fields( forward=False, reverse=True, include_hidden=True ) return make_immutable_fields_list( "related_objects", ( obj for obj in all_related_fields if not obj.hidden or obj.field.many_to_many ), ) @cached_property def _forward_fields_map(self): res = {} fields = self._get_fields(reverse=False) for field in fields: res[field.name] = field # Due to the way Django's internals work, get_field() should also # be able to fetch a field by attname. In the case of a concrete # field with relation, includes the *_id name too try: res[field.attname] = field except AttributeError: pass return res @cached_property def fields_map(self): res = {} fields = self._get_fields(forward=False, include_hidden=True) for field in fields: res[field.name] = field # Due to the way Django's internals work, get_field() should also # be able to fetch a field by attname. In the case of a concrete # field with relation, includes the *_id name too try: res[field.attname] = field except AttributeError: pass return res def get_field(self, field_name): """ Return a field instance given the name of a forward or reverse field. """ try: # In order to avoid premature loading of the relation tree # (expensive) we prefer checking if the field is a forward field. return self._forward_fields_map[field_name] except KeyError: # If the app registry is not ready, reverse fields are # unavailable, therefore we throw a FieldDoesNotExist exception. if not self.apps.models_ready: raise FieldDoesNotExist( "%s has no field named '%s'. The app cache isn't ready yet, " "so if this is an auto-created related field, it won't " "be available yet." % (self.object_name, field_name) ) try: # Retrieve field instance by name from cached or just-computed # field map. return self.fields_map[field_name] except KeyError: raise FieldDoesNotExist( "%s has no field named '%s'" % (self.object_name, field_name) ) def get_base_chain(self, model): """ Return a list of parent classes leading to `model` (ordered from closest to most distant ancestor). This has to handle the case where `model` is a grandparent or even more distant relation. """ if not self.parents: return [] if model in self.parents: return [model] for parent in self.parents: res = parent._meta.get_base_chain(model) if res: res.insert(0, parent) return res return [] def get_parent_list(self): """ Return all the ancestors of this model as a list ordered by MRO. Useful for determining if something is an ancestor, regardless of lineage. """ result = OrderedSet(self.parents) for parent in self.parents: for ancestor in parent._meta.get_parent_list(): result.add(ancestor) return list(result) def get_ancestor_link(self, ancestor): """ Return the field on the current model which points to the given "ancestor". This is possible an indirect link (a pointer to a parent model, which points, eventually, to the ancestor). Used when constructing table joins for model inheritance. Return None if the model isn't an ancestor of this one. """ if ancestor in self.parents: return self.parents[ancestor] for parent in self.parents: # Tries to get a link field from the immediate parent parent_link = parent._meta.get_ancestor_link(ancestor) if parent_link: # In case of a proxied model, the first link # of the chain to the ancestor is that parent # links return self.parents[parent] or parent_link def get_path_to_parent(self, parent): """ Return a list of PathInfos containing the path from the current model to the parent model, or an empty list if parent is not a parent of the current model. """ if self.model is parent: return [] # Skip the chain of proxy to the concrete proxied model. proxied_model = self.concrete_model path = [] opts = self for int_model in self.get_base_chain(parent): if int_model is proxied_model: opts = int_model._meta else: final_field = opts.parents[int_model] targets = (final_field.remote_field.get_related_field(),) opts = int_model._meta path.append( PathInfo( from_opts=final_field.model._meta, to_opts=opts, target_fields=targets, join_field=final_field, m2m=False, direct=True, filtered_relation=None, ) ) return path def get_path_from_parent(self, parent): """ Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model. """ if self.model is parent: return [] model = self.concrete_model # Get a reversed base chain including both the current and parent # models. chain = model._meta.get_base_chain(parent) chain.reverse() chain.append(model) # Construct a list of the PathInfos between models in chain. path = [] for i, ancestor in enumerate(chain[:-1]): child = chain[i + 1] link = child._meta.get_ancestor_link(ancestor) path.extend(link.reverse_path_infos) return path def _populate_directed_relation_graph(self): """ This method is used by each model to find its reverse objects. As this method is very expensive and is accessed frequently (it looks up every field in a model, in every app), it is computed on first access and then is set as a property on every model. """ related_objects_graph = defaultdict(list) all_models = self.apps.get_models(include_auto_created=True) for model in all_models: opts = model._meta # Abstract model's fields are copied to child models, hence we will # see the fields from the child models. if opts.abstract: continue fields_with_relations = ( f for f in opts._get_fields(reverse=False, include_parents=False) if f.is_relation and f.related_model is not None ) for f in fields_with_relations: if not isinstance(f.remote_field.model, str): remote_label = f.remote_field.model._meta.concrete_model._meta.label related_objects_graph[remote_label].append(f) for model in all_models: # Set the relation_tree using the internal __dict__. In this way # we avoid calling the cached property. In attribute lookup, # __dict__ takes precedence over a data descriptor (such as # @cached_property). This means that the _meta._relation_tree is # only called if related_objects is not in __dict__. related_objects = related_objects_graph[ model._meta.concrete_model._meta.label ] model._meta.__dict__["_relation_tree"] = related_objects # It seems it is possible that self is not in all_models, so guard # against that with default for get(). return self.__dict__.get("_relation_tree", EMPTY_RELATION_TREE) @cached_property def _relation_tree(self): return self._populate_directed_relation_graph() def _expire_cache(self, forward=True, reverse=True): # This method is usually called by apps.cache_clear(), when the # registry is finalized, or when a new field is added. if forward: for cache_key in self.FORWARD_PROPERTIES: if cache_key in self.__dict__: delattr(self, cache_key) if reverse and not self.abstract: for cache_key in self.REVERSE_PROPERTIES: if cache_key in self.__dict__: delattr(self, cache_key) self._get_fields_cache = {} def get_fields(self, include_parents=True, include_hidden=False): """ Return a list of fields associated to the model. By default, include forward and reverse fields, fields derived from inheritance, but not hidden fields. The returned fields can be changed using the parameters: - include_parents: include fields derived from inheritance - include_hidden: include fields that have a related_name that starts with a "+" """ if include_parents is False: include_parents = PROXY_PARENTS return self._get_fields( include_parents=include_parents, include_hidden=include_hidden ) def _get_fields( self, forward=True, reverse=True, include_parents=True, include_hidden=False, seen_models=None, ): """ Internal helper function to return fields of the model. * If forward=True, then fields defined on this model are returned. * If reverse=True, then relations pointing to this model are returned. * If include_hidden=True, then fields with is_hidden=True are returned. * The include_parents argument toggles if fields from parent models should be included. It has three values: True, False, and PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all fields defined for the current model or any of its parents in the parent chain to the model's concrete model. """ if include_parents not in (True, False, PROXY_PARENTS): raise TypeError( "Invalid argument for include_parents: %s" % (include_parents,) ) # This helper function is used to allow recursion in ``get_fields()`` # implementation and to provide a fast way for Django's internals to # access specific subsets of fields. # We must keep track of which models we have already seen. Otherwise we # could include the same field multiple times from different models. topmost_call = seen_models is None if topmost_call: seen_models = set() seen_models.add(self.model) # Creates a cache key composed of all arguments cache_key = (forward, reverse, include_parents, include_hidden, topmost_call) try: # In order to avoid list manipulation. Always return a shallow copy # of the results. return self._get_fields_cache[cache_key] except KeyError: pass fields = [] # Recursively call _get_fields() on each parent, with the same # options provided in this call. if include_parents is not False: for parent in self.parents: # In diamond inheritance it is possible that we see the same # model from two different routes. In that case, avoid adding # fields from the same parent again. if parent in seen_models: continue if ( parent._meta.concrete_model != self.concrete_model and include_parents == PROXY_PARENTS ): continue for obj in parent._meta._get_fields( forward=forward, reverse=reverse, include_parents=include_parents, include_hidden=include_hidden, seen_models=seen_models, ): if ( not getattr(obj, "parent_link", False) or obj.model == self.concrete_model ): fields.append(obj) if reverse and not self.proxy: # Tree is computed once and cached until the app cache is expired. # It is composed of a list of fields pointing to the current model # from other models. all_fields = self._relation_tree for field in all_fields: # If hidden fields should be included or the relation is not # intentionally hidden, add to the fields dict. if include_hidden or not field.remote_field.hidden: fields.append(field.remote_field) if forward: fields += self.local_fields fields += self.local_many_to_many # Private fields are recopied to each child model, and they get a # different model as field.model in each child. Hence we have to # add the private fields separately from the topmost call. If we # did this recursively similar to local_fields, we would get field # instances with field.model != self.model. if topmost_call: fields += self.private_fields # In order to avoid list manipulation. Always # return a shallow copy of the results fields = make_immutable_fields_list("get_fields()", fields) # Store result into cache for later access self._get_fields_cache[cache_key] = fields return fields @cached_property def total_unique_constraints(self): """ Return a list of total unique constraints. Useful for determining set of fields guaranteed to be unique for all rows. """ return [ constraint for constraint in self.constraints if ( isinstance(constraint, UniqueConstraint) and constraint.condition is None and not constraint.contains_expressions ) ] @cached_property def _property_names(self): """Return a set of the names of the properties defined on the model.""" names = [] for name in dir(self.model): attr = inspect.getattr_static(self.model, name) if isinstance(attr, property): names.append(name) return frozenset(names) @cached_property def _non_pk_concrete_field_names(self): """ Return a set of the non-pk concrete field names defined on the model. """ names = [] for field in self.concrete_fields: if not field.primary_key: names.append(field.name) if field.name != field.attname: names.append(field.attname) return frozenset(names) @cached_property def db_returning_fields(self): """ Private API intended only to be used by Django itself. Fields to be returned after a database insert. """ return [ field for field in self._get_fields( forward=True, reverse=False, include_parents=PROXY_PARENTS ) if getattr(field, "db_returning", False) ]
fcfb2a2ac532716c8cf268816a4c15dd6f53e64ada0be8eda0b526d97176377c
import copy import inspect import warnings from functools import partialmethod from itertools import chain from asgiref.sync import sync_to_async import django from django.apps import apps from django.conf import settings from django.core import checks from django.core.exceptions import ( NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned, ObjectDoesNotExist, ValidationError, ) from django.db import ( DJANGO_VERSION_PICKLE_KEY, DatabaseError, connection, connections, router, transaction, ) from django.db.models import NOT_PROVIDED, ExpressionWrapper, IntegerField, Max, Value from django.db.models.constants import LOOKUP_SEP from django.db.models.constraints import CheckConstraint, UniqueConstraint from django.db.models.deletion import CASCADE, Collector from django.db.models.expressions import RawSQL from django.db.models.fields.related import ( ForeignObjectRel, OneToOneField, lazy_related_operation, resolve_relation, ) from django.db.models.functions import Coalesce from django.db.models.manager import Manager from django.db.models.options import Options from django.db.models.query import F, Q from django.db.models.signals import ( class_prepared, post_init, post_save, pre_init, pre_save, ) from django.db.models.utils import AltersData, make_model_tuple from django.utils.encoding import force_str from django.utils.hashable import make_hashable from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext_lazy as _ class Deferred: def __repr__(self): return "<Deferred field>" def __str__(self): return "<Deferred field>" DEFERRED = Deferred() def subclass_exception(name, bases, module, attached_to): """ Create exception subclass. Used by ModelBase below. The exception is created in a way that allows it to be pickled, assuming that the returned exception class will be added as an attribute to the 'attached_to' class. """ return type( name, bases, { "__module__": module, "__qualname__": "%s.%s" % (attached_to.__qualname__, name), }, ) def _has_contribute_to_class(value): # Only call contribute_to_class() if it's bound. return not inspect.isclass(value) and hasattr(value, "contribute_to_class") class ModelBase(type): """Metaclass for all models.""" def __new__(cls, name, bases, attrs, **kwargs): super_new = super().__new__ # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop("__module__") new_attrs = {"__module__": module} classcell = attrs.pop("__classcell__", None) if classcell is not None: new_attrs["__classcell__"] = classcell attr_meta = attrs.pop("Meta", None) # Pass all attrs 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_name] = obj else: new_attrs[obj_name] = obj new_class = super_new(cls, name, bases, new_attrs, **kwargs) abstract = getattr(attr_meta, "abstract", False) 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. app_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 doesn't declare an explicit " "app_label and isn't in an application in " "INSTALLED_APPS." % (module, name) ) else: app_label = app_config.label new_class.add_to_class("_meta", Options(meta, app_label)) if not abstract: new_class.add_to_class( "DoesNotExist", subclass_exception( "DoesNotExist", tuple( x.DoesNotExist for x in parents if hasattr(x, "_meta") and not x._meta.abstract ) or (ObjectDoesNotExist,), module, attached_to=new_class, ), ) new_class.add_to_class( "MultipleObjectsReturned", subclass_exception( "MultipleObjectsReturned", tuple( x.MultipleObjectsReturned for x in parents if hasattr(x, "_meta") and not x._meta.abstract ) or (MultipleObjectsReturned,), module, attached_to=new_class, ), ) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, "ordering"): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, "get_latest_by"): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy # If the model is a proxy, ensure that the base class # hasn't been swapped out. if is_proxy and base_meta and base_meta.swapped: raise TypeError( "%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped) ) # Add remaining attributes (those with a contribute_to_class() method) # to the class. for obj_name, obj in contributable_attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = chain( new_class._meta.local_fields, new_class._meta.local_many_to_many, new_class._meta.private_fields, ) field_names = {f.name for f in new_fields} # Basic setup for proxy models. if is_proxy: base = None for parent in [kls for kls in parents if hasattr(kls, "_meta")]: if parent._meta.abstract: if parent._meta.fields: raise TypeError( "Abstract base class containing model fields not " "permitted for proxy model '%s'." % name ) else: continue if base is None: base = parent elif parent._meta.concrete_model is not base._meta.concrete_model: raise TypeError( "Proxy model '%s' has more than one non-abstract model base " "class." % name ) if base is None: raise TypeError( "Proxy model '%s' has no non-abstract model base class." % name ) new_class._meta.setup_proxy(base) new_class._meta.concrete_model = base._meta.concrete_model else: new_class._meta.concrete_model = new_class # Collect the parent links for multi-table inheritance. parent_links = {} for base in reversed([new_class] + parents): # Conceptually equivalent to `if base is Model`. if not hasattr(base, "_meta"): continue # Skip concrete parent classes. if base != new_class and not base._meta.abstract: continue # Locate OneToOneField instances. for field in base._meta.local_fields: if isinstance(field, OneToOneField) and field.remote_field.parent_link: related = resolve_relation(new_class, field.remote_field.model) parent_links[make_model_tuple(related)] = field # Track fields inherited from base models. inherited_attributes = set() # Do the appropriate setup for any model parents. for base in new_class.mro(): if base not in parents or not hasattr(base, "_meta"): # Things without _meta aren't functional models, so they're # uninteresting parents. inherited_attributes.update(base.__dict__) continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many if not base._meta.abstract: # Check for clashes between locally declared fields and those # on the base classes. for field in parent_fields: if field.name in field_names: raise FieldError( "Local field %r in class %r clashes with field of " "the same name from base class %r." % ( field.name, name, base.__name__, ) ) else: inherited_attributes.add(field.name) # Concrete classes... base = base._meta.concrete_model base_key = make_model_tuple(base) if base_key in parent_links: field = parent_links[base_key] elif not is_proxy: attr_name = "%s_ptr" % base._meta.model_name field = OneToOneField( base, on_delete=CASCADE, name=attr_name, auto_created=True, parent_link=True, ) if attr_name in field_names: raise FieldError( "Auto-generated field '%s' in class %r for " "parent_link to base class %r clashes with " "declared field of the same name." % ( attr_name, name, base.__name__, ) ) # Only add the ptr field if it's not already present; # e.g. migrations will already have it specified if not hasattr(new_class, attr_name): new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: base_parents = base._meta.parents.copy() # Add fields from abstract base class if it wasn't overridden. for field in parent_fields: if ( field.name not in field_names and field.name not in new_class.__dict__ and field.name not in inherited_attributes ): new_field = copy.deepcopy(field) new_class.add_to_class(field.name, new_field) # Replace parent links defined on this base by the new # field. It will be appropriately resolved if required. if field.one_to_one: for parent, parent_link in base_parents.items(): if field == parent_link: base_parents[parent] = new_field # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base_parents) # Inherit private fields (like GenericForeignKey) from the parent # class for field in base._meta.private_fields: if field.name in field_names: if not base._meta.abstract: raise FieldError( "Local field %r in class %r clashes with field of " "the same name from base class %r." % ( field.name, name, base.__name__, ) ) else: field = copy.deepcopy(field) if not base._meta.abstract: field.mti_inherited = True new_class.add_to_class(field.name, field) # Copy indexes so that index names are unique when models extend an # abstract model. new_class._meta.indexes = [ copy.deepcopy(idx) for idx in new_class._meta.indexes ] if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() new_class._meta.apps.register_model(new_class._meta.app_label, new_class) return new_class def add_to_class(cls, name, value): if _has_contribute_to_class(value): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _prepare(cls): """Create some methods once self._meta has been populated.""" opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = partialmethod( cls._get_next_or_previous_in_order, is_next=True ) cls.get_previous_in_order = partialmethod( cls._get_next_or_previous_in_order, is_next=False ) # Defer creating accessors on the foreign class until it has been # created and registered. If remote_field is None, we're ordering # with respect to a GenericForeignKey and don't know what the # foreign class is - we'll add those accessors later in # contribute_to_class(). if opts.order_with_respect_to.remote_field: wrt = opts.order_with_respect_to remote = wrt.remote_field.model lazy_related_operation(make_foreign_order_accessors, cls, remote) # Give the class a docstring -- its definition. if cls.__doc__ is None: cls.__doc__ = "%s(%s)" % ( cls.__name__, ", ".join(f.name for f in opts.fields), ) get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get( opts.label_lower ) if get_absolute_url_override: setattr(cls, "get_absolute_url", get_absolute_url_override) if not opts.managers: if any(f.name == "objects" for f in opts.fields): raise ValueError( "Model %s must specify a custom Manager, because it has a " "field named 'objects'." % cls.__name__ ) manager = Manager() manager.auto_created = True cls.add_to_class("objects", manager) # Set the name of _meta.indexes. This can't be done in # Options.contribute_to_class() because fields haven't been added to # the model at that point. for index in cls._meta.indexes: if not index.name: index.set_name_with_model(cls) class_prepared.send(sender=cls) @property def _base_manager(cls): return cls._meta.base_manager @property def _default_manager(cls): return cls._meta.default_manager class ModelStateFieldsCacheDescriptor: def __get__(self, instance, cls=None): if instance is None: return self res = instance.fields_cache = {} return res class ModelState: """Store model instance state.""" db = None # If true, uniqueness validation checks will consider this a new, unsaved # object. Necessary for correct validation of new instances of objects with # explicit (non-auto) PKs. This impacts validation only; it has no effect # on the actual save. adding = True fields_cache = ModelStateFieldsCacheDescriptor() class Model(AltersData, metaclass=ModelBase): def __init__(self, *args, **kwargs): # Alias some things as locals to avoid repeat global lookups cls = self.__class__ opts = self._meta _setattr = setattr _DEFERRED = DEFERRED if opts.abstract: raise TypeError("Abstract models cannot be instantiated.") pre_init.send(sender=cls, args=args, kwargs=kwargs) # Set up the storage for instance state self._state = ModelState() # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check is that standard iterator passes in by # args, and instantiation for iteration is 33% faster. if len(args) > len(opts.concrete_fields): # Daft, but matches old exception sans the err msg. raise IndexError("Number of args exceeds number of fields") if not kwargs: fields_iter = iter(opts.concrete_fields) # The ordering of the zip calls matter - zip throws StopIteration # when an iter throws it. So if the first iter throws it, the second # is *not* consumed. We rely on this, so don't change the order # without changing the logic. for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) else: # Slower, kwargs-ready version. fields_iter = iter(opts.fields) for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) if kwargs.pop(field.name, NOT_PROVIDED) is not NOT_PROVIDED: raise TypeError( f"{cls.__qualname__}() got both positional and " f"keyword arguments for field '{field.name}'." ) # Now we're left with the unprocessed fields that *must* come from # keywords, or default. for field in fields_iter: is_related_object = False # Virtual field if field.attname not in kwargs and field.column is None: continue if kwargs: if isinstance(field.remote_field, ForeignObjectRel): try: # Assume object instance was passed in. rel_obj = kwargs.pop(field.name) is_related_object = True except KeyError: try: # Object instance wasn't passed in -- must be an ID. val = kwargs.pop(field.attname) except KeyError: val = field.get_default() else: try: val = kwargs.pop(field.attname) except KeyError: # This is done with an exception rather than the # default argument on pop because we don't want # get_default() to be evaluated, and then not used. # Refs #12057. val = field.get_default() else: val = field.get_default() if is_related_object: # If we are passed a related instance, set it using the # field.name instead of field.attname (e.g. "user" instead of # "user_id") so that the object gets properly cached (and type # checked) by the RelatedObjectDescriptor. if rel_obj is not _DEFERRED: _setattr(self, field.name, rel_obj) else: if val is not _DEFERRED: _setattr(self, field.attname, val) if kwargs: property_names = opts._property_names unexpected = () for prop, value in kwargs.items(): # Any remaining kwargs must correspond to properties or virtual # fields. if prop in property_names: if value is not _DEFERRED: _setattr(self, prop, value) else: try: opts.get_field(prop) except FieldDoesNotExist: unexpected += (prop,) else: if value is not _DEFERRED: _setattr(self, prop, value) if unexpected: unexpected_names = ", ".join(repr(n) for n in unexpected) raise TypeError( f"{cls.__name__}() got unexpected keyword arguments: " f"{unexpected_names}" ) super().__init__() post_init.send(sender=cls, instance=self) @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values_iter = iter(values) values = [ next(values_iter) if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields ] new = cls(*values) new._state.adding = False new._state.db = db return new def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def __str__(self): return "%s object (%s)" % (self.__class__.__name__, self.pk) def __eq__(self, other): if not isinstance(other, Model): return NotImplemented if self._meta.concrete_model != other._meta.concrete_model: return False my_pk = self.pk if my_pk is None: return self is other return my_pk == other.pk def __hash__(self): if self.pk is None: raise TypeError("Model instances without primary key value are unhashable") return hash(self.pk) def __reduce__(self): data = self.__getstate__() data[DJANGO_VERSION_PICKLE_KEY] = django.__version__ class_id = self._meta.app_label, self._meta.object_name return model_unpickle, (class_id,), data def __getstate__(self): """Hook to allow choosing the attributes to pickle.""" state = self.__dict__.copy() state["_state"] = copy.copy(state["_state"]) state["_state"].fields_cache = state["_state"].fields_cache.copy() # memoryview cannot be pickled, so cast it to bytes and store # separately. _memoryview_attrs = [] for attr, value in state.items(): if isinstance(value, memoryview): _memoryview_attrs.append((attr, bytes(value))) if _memoryview_attrs: state["_memoryview_attrs"] = _memoryview_attrs for attr, value in _memoryview_attrs: state.pop(attr) return state def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled model instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled model instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) if "_memoryview_attrs" in state: for attr, value in state.pop("_memoryview_attrs"): state[attr] = memoryview(value) self.__dict__.update(state) def _get_pk_val(self, meta=None): meta = meta or self._meta return getattr(self, meta.pk.attname) def _set_pk_val(self, value): for parent_link in self._meta.parents.values(): if parent_link and parent_link != self._meta.pk: setattr(self, parent_link.target_field.attname, value) return setattr(self, self._meta.pk.attname, value) pk = property(_get_pk_val, _set_pk_val) def get_deferred_fields(self): """ Return a set containing names of deferred fields for this instance. """ return { f.attname for f in self._meta.concrete_fields if f.attname not in self.__dict__ } def refresh_from_db(self, using=None, fields=None): """ Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default. Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded. When accessing deferred fields of an instance, the deferred loading of the field will call this method. """ if fields is None: self._prefetched_objects_cache = {} else: prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ()) for field in fields: if field in prefetched_objects_cache: del prefetched_objects_cache[field] fields.remove(field) if not fields: return if any(LOOKUP_SEP in f for f in fields): raise ValueError( 'Found "%s" in fields argument. Relations and transforms ' "are not allowed in fields." % LOOKUP_SEP ) hints = {"instance": self} db_instance_qs = self.__class__._base_manager.db_manager( using, hints=hints ).filter(pk=self.pk) # Use provided fields, if not set then reload all non-deferred fields. deferred_fields = self.get_deferred_fields() if fields is not None: fields = list(fields) db_instance_qs = db_instance_qs.only(*fields) elif deferred_fields: fields = [ f.attname for f in self._meta.concrete_fields if f.attname not in deferred_fields ] db_instance_qs = db_instance_qs.only(*fields) db_instance = db_instance_qs.get() non_loaded_fields = db_instance.get_deferred_fields() for field in self._meta.concrete_fields: if field.attname in non_loaded_fields: # This field wasn't refreshed - skip ahead. continue setattr(self, field.attname, getattr(db_instance, field.attname)) # Clear cached foreign keys. if field.is_relation and field.is_cached(self): field.delete_cached_value(self) # Clear cached relations. for field in self._meta.related_objects: if field.is_cached(self): field.delete_cached_value(self) # Clear cached private relations. for field in self._meta.private_fields: if field.is_relation and field.is_cached(self): field.delete_cached_value(self) self._state.db = db_instance._state.db async def arefresh_from_db(self, using=None, fields=None): return await sync_to_async(self.refresh_from_db)(using=using, fields=fields) def serializable_value(self, field_name): """ Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ try: field = self._meta.get_field(field_name) except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.attname) def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): """ Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set. """ self._prepare_related_fields_for_save(operation_name="save") using = using or router.db_for_write(self.__class__, instance=self) if force_insert and (force_update or update_fields): raise ValueError("Cannot force both insert and updating in model saving.") deferred_fields = self.get_deferred_fields() if update_fields is not None: # If update_fields is empty, skip the save. We do also check for # no-op saves later on for inheritance cases. This bailout is # still needed for skipping signal sending. if not update_fields: return update_fields = frozenset(update_fields) field_names = self._meta._non_pk_concrete_field_names non_model_fields = update_fields.difference(field_names) if non_model_fields: raise ValueError( "The following fields do not exist in this model, are m2m " "fields, or are non-concrete fields: %s" % ", ".join(non_model_fields) ) # If saving to the same database, and this model is deferred, then # automatically do an "update_fields" save on the loaded fields. elif not force_insert and deferred_fields and using == self._state.db: field_names = set() for field in self._meta.concrete_fields: if not field.primary_key and not hasattr(field, "through"): field_names.add(field.attname) loaded_fields = field_names.difference(deferred_fields) if loaded_fields: update_fields = frozenset(loaded_fields) self.save_base( using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields, ) save.alters_data = True async def asave( self, force_insert=False, force_update=False, using=None, update_fields=None ): return await sync_to_async(self.save)( force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields, ) asave.alters_data = True def save_base( self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None, ): """ Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading. """ using = using or router.db_for_write(self.__class__, instance=self) assert not (force_insert and (force_update or update_fields)) assert update_fields is None or update_fields cls = origin = self.__class__ # Skip proxies, but keep the origin as the proxy model. if cls._meta.proxy: cls = cls._meta.concrete_model meta = cls._meta if not meta.auto_created: pre_save.send( sender=origin, instance=self, raw=raw, using=using, update_fields=update_fields, ) # A transaction isn't needed if one query is issued. if meta.parents: context_manager = transaction.atomic(using=using, savepoint=False) else: context_manager = transaction.mark_for_rollback_on_error(using=using) with context_manager: parent_inserted = False if not raw: parent_inserted = self._save_parents(cls, using, update_fields) updated = self._save_table( raw, cls, force_insert or parent_inserted, force_update, using, update_fields, ) # Store the database on which the object was saved self._state.db = using # Once saved, this is no longer a to-be-added instance. self._state.adding = False # Signal that the save is complete if not meta.auto_created: post_save.send( sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using, ) save_base.alters_data = True def _save_parents(self, cls, using, update_fields): """Save all the parents of cls using values from self.""" meta = cls._meta inserted = False for parent, field in meta.parents.items(): # Make sure the link fields are synced between parent and self. if ( field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None ): setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) parent_inserted = self._save_parents( cls=parent, using=using, update_fields=update_fields ) updated = self._save_table( cls=parent, using=using, update_fields=update_fields, force_insert=parent_inserted, ) if not updated: inserted = True # Set the parent's PK value to self. if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) # Since we didn't have an instance of the parent handy set # attname directly, bypassing the descriptor. Invalidate # the related object cache, in case it's been accidentally # populated. A fresh instance will be re-built from the # database if necessary. if field.is_cached(self): field.delete_cached_value(self) return inserted def _save_table( self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None, ): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for f in meta.local_concrete_fields if not f.primary_key] if update_fields: non_pks = [ f for f in non_pks if f.name in update_fields or f.attname in update_fields ] pk_val = self._get_pk_val(meta) if pk_val is None: pk_val = meta.pk.get_pk_value_on_save(self) setattr(self, meta.pk.attname, pk_val) pk_set = pk_val is not None if not pk_set and (force_update or update_fields): raise ValueError("Cannot force an update in save() with no primary key.") updated = False # Skip an UPDATE when adding an instance and primary key has a default. if ( not raw and not force_insert and self._state.adding and ( (meta.pk.default and meta.pk.default is not NOT_PROVIDED) or (meta.pk.db_default and meta.pk.db_default is not NOT_PROVIDED) ) ): force_insert = True # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) values = [ ( f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)), ) for f in non_pks ] forced_update = update_fields or force_update updated = self._do_update( base_qs, using, pk_val, values, update_fields, forced_update ) if force_update and not updated: raise DatabaseError("Forced update did not affect any rows.") if update_fields and not updated: raise DatabaseError("Save with update_fields did not affect any rows.") if not updated: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to filter_args = field.get_filter_kwargs_for_object(self) self._order = ( cls._base_manager.using(using) .filter(**filter_args) .aggregate( _order__max=Coalesce( ExpressionWrapper( Max("_order") + Value(1), output_field=IntegerField() ), Value(0), ), )["_order__max"] ) fields = meta.local_concrete_fields if not pk_set: fields = [f for f in fields if f is not meta.auto_field] returning_fields = meta.db_returning_fields results = self._do_insert( cls._base_manager, using, fields, returning_fields, raw ) if results: for value, field in zip(results[0], returning_fields): setattr(self, field.attname, value) return updated def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update): """ Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB). """ filtered = base_qs.filter(pk=pk_val) if not values: # We can end up here when saving a model in inheritance chain where # update_fields doesn't target any field in current model. In that # case we just say the update succeeded. Another case ending up here # is a model with just PK - in that case check that the PK still # exists. return update_fields is not None or filtered.exists() if self._meta.select_on_save and not forced_update: return ( filtered.exists() and # It may happen that the object is deleted from the DB right after # this check, causing the subsequent UPDATE to return zero matching # rows. The same result can occur in some rare cases when the # database returns zero despite the UPDATE being executed # successfully (a row is matched and updated). In order to # distinguish these two cases, the object's existence in the # database is again checked for if the UPDATE query returns 0. (filtered._update(values) > 0 or filtered.exists()) ) return filtered._update(values) > 0 def _do_insert(self, manager, using, fields, returning_fields, raw): """ Do an INSERT. If returning_fields is defined then this method should return the newly created data for the model. """ return manager._insert( [self], fields=fields, returning_fields=returning_fields, using=using, raw=raw, ) def _prepare_related_fields_for_save(self, operation_name, fields=None): # Ensure that a model instance without a PK hasn't been assigned to # a ForeignKey, GenericForeignKey or OneToOneField on this model. If # the field is nullable, allowing the save would result in silent data # loss. for field in self._meta.concrete_fields: if fields and field not in fields: continue # If the related field isn't cached, then an instance hasn't been # assigned and there's no need to worry about this check. if field.is_relation and field.is_cached(self): obj = getattr(self, field.name, None) if not obj: continue # A pk may have been assigned manually to a model instance not # saved to the database (or auto-generated in a case like # UUIDField), but we allow the save to proceed and rely on the # database to raise an IntegrityError if applicable. If # constraints aren't supported by the database, there's the # unavoidable risk of data corruption. if obj.pk is None: # Remove the object from a related instance cache. if not field.remote_field.multiple: field.remote_field.delete_cached_value(obj) raise ValueError( "%s() prohibited to prevent data loss due to unsaved " "related object '%s'." % (operation_name, field.name) ) elif getattr(self, field.attname) in field.empty_values: # Set related object if it has been saved after an # assignment. setattr(self, field.name, obj) # If the relationship's pk/to_field was changed, clear the # cached relationship. if getattr(obj, field.target_field.attname) != getattr( self, field.attname ): field.delete_cached_value(self) # GenericForeignKeys are private. for field in self._meta.private_fields: if fields and field not in fields: continue if ( field.is_relation and field.is_cached(self) and hasattr(field, "fk_field") ): obj = field.get_cached_value(self, default=None) if obj and obj.pk is None: raise ValueError( f"{operation_name}() prohibited to prevent data loss due to " f"unsaved related object '{field.name}'." ) def delete(self, using=None, keep_parents=False): if self.pk is None: raise ValueError( "%s object can't be deleted because its %s attribute is set " "to None." % (self._meta.object_name, self._meta.pk.attname) ) using = using or router.db_for_write(self.__class__, instance=self) collector = Collector(using=using, origin=self) collector.collect([self], keep_parents=keep_parents) return collector.delete() delete.alters_data = True async def adelete(self, using=None, keep_parents=False): return await sync_to_async(self.delete)( using=using, keep_parents=keep_parents, ) adelete.alters_data = True def _get_FIELD_display(self, field): value = getattr(self, field.attname) choices_dict = dict(make_hashable(field.flatchoices)) # force_str() to coerce lazy strings. return force_str( choices_dict.get(make_hashable(value), value), strings_only=True ) def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): if not self.pk: raise ValueError("get_next/get_previous cannot be used on unsaved objects.") op = "gt" if is_next else "lt" order = "" if is_next else "-" param = getattr(self, field.attname) q = Q.create([(field.name, param), (f"pk__{op}", self.pk)], connector=Q.AND) q = Q.create([q, (f"{field.name}__{op}", param)], connector=Q.OR) qs = ( self.__class__._default_manager.using(self._state.db) .filter(**kwargs) .filter(q) .order_by("%s%s" % (order, field.name), "%spk" % order) ) try: return qs[0] except IndexError: raise self.DoesNotExist( "%s matching query does not exist." % self.__class__._meta.object_name ) def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): op = "gt" if is_next else "lt" order = "_order" if is_next else "-_order" order_field = self._meta.order_with_respect_to filter_args = order_field.get_filter_kwargs_for_object(self) obj = ( self.__class__._default_manager.filter(**filter_args) .filter( **{ "_order__%s" % op: self.__class__._default_manager.values("_order").filter( **{self._meta.pk.name: self.pk} ) } ) .order_by(order)[:1] .get() ) setattr(self, cachename, obj) return getattr(self, cachename) def _get_field_value_map(self, meta, exclude=None): if exclude is None: exclude = set() meta = meta or self._meta return { field.name: Value(getattr(self, field.attname), field) for field in meta.local_concrete_fields if field.name not in exclude } def prepare_database_save(self, field): if self.pk is None: raise ValueError( "Unsaved model instance %r cannot be used in an ORM query." % self ) return getattr(self, field.remote_field.get_related_field().attname) def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS. """ pass def validate_unique(self, exclude=None): """ Check unique constraints on the model and raise ValidationError if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors = self._perform_date_checks(date_checks) for k, v in date_errors.items(): errors.setdefault(k, []).extend(v) if errors: raise ValidationError(errors) def _get_unique_checks(self, exclude=None, include_meta_constraints=False): """ Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but they need to be passed in via the exclude argument. """ if exclude is None: exclude = set() unique_checks = [] unique_togethers = [(self.__class__, self._meta.unique_together)] constraints = [] if include_meta_constraints: constraints = [(self.__class__, self._meta.total_unique_constraints)] for parent_class in self._meta.get_parent_list(): if parent_class._meta.unique_together: unique_togethers.append( (parent_class, parent_class._meta.unique_together) ) if include_meta_constraints and parent_class._meta.total_unique_constraints: constraints.append( (parent_class, parent_class._meta.total_unique_constraints) ) for model_class, unique_together in unique_togethers: for check in unique_together: if not any(name in exclude for name in check): # Add the check if the field isn't excluded. unique_checks.append((model_class, tuple(check))) if include_meta_constraints: for model_class, model_constraints in constraints: for constraint in model_constraints: if not any(name in exclude for name in constraint.fields): unique_checks.append((model_class, constraint.fields)) # These are checks for the unique_for_<date/year/month>. date_checks = [] # Gather a list of checks for fields declared as unique and add them to # the list of checks. fields_with_class = [(self.__class__, self._meta.local_fields)] for parent_class in self._meta.get_parent_list(): fields_with_class.append((parent_class, parent_class._meta.local_fields)) for model_class, fields in fields_with_class: for f in fields: name = f.name if name in exclude: continue if f.unique: unique_checks.append((model_class, (name,))) if f.unique_for_date and f.unique_for_date not in exclude: date_checks.append((model_class, "date", name, f.unique_for_date)) if f.unique_for_year and f.unique_for_year not in exclude: date_checks.append((model_class, "year", name, f.unique_for_year)) if f.unique_for_month and f.unique_for_month not in exclude: date_checks.append((model_class, "month", name, f.unique_for_month)) return unique_checks, date_checks def _perform_unique_checks(self, unique_checks): errors = {} for model_class, unique_check in unique_checks: # Try to look up an existing object with the same values as this # object's values for all the unique field. lookup_kwargs = {} for field_name in unique_check: f = self._meta.get_field(field_name) lookup_value = getattr(self, f.attname) # TODO: Handle multiple backends with different feature flags. if lookup_value is None or ( lookup_value == "" and connection.features.interprets_empty_strings_as_nulls ): # no value, skip the lookup continue if f.primary_key and not self._state.adding: # no need to check for unique primary key when editing continue lookup_kwargs[str(field_name)] = lookup_value # some fields were skipped, no reason to do the check if len(unique_check) != len(lookup_kwargs): continue qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) # Note that we need to use the pk as defined by model_class, not # self.pk. These can be different fields because model inheritance # allows single model to have effectively multiple primary keys. # Refs #17615. model_class_pk = self._get_pk_val(model_class._meta) if not self._state.adding and model_class_pk is not None: qs = qs.exclude(pk=model_class_pk) if qs.exists(): if len(unique_check) == 1: key = unique_check[0] else: key = NON_FIELD_ERRORS errors.setdefault(key, []).append( self.unique_error_message(model_class, unique_check) ) return errors def _perform_date_checks(self, date_checks): errors = {} for model_class, lookup_type, field, unique_for in date_checks: lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == "date": lookup_kwargs["%s__day" % unique_for] = date.day lookup_kwargs["%s__month" % unique_for] = date.month lookup_kwargs["%s__year" % unique_for] = date.year else: lookup_kwargs["%s__%s" % (unique_for, lookup_type)] = getattr( date, lookup_type ) lookup_kwargs[field] = getattr(self, field) qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): errors.setdefault(field, []).append( self.date_error_message(lookup_type, field, unique_for) ) return errors def date_error_message(self, lookup_type, field_name, unique_for): opts = self._meta field = opts.get_field(field_name) return ValidationError( message=field.error_messages["unique_for_date"], code="unique_for_date", params={ "model": self, "model_name": capfirst(opts.verbose_name), "lookup_type": lookup_type, "field": field_name, "field_label": capfirst(field.verbose_name), "date_field": unique_for, "date_field_label": capfirst(opts.get_field(unique_for).verbose_name), }, ) def unique_error_message(self, model_class, unique_check): opts = model_class._meta params = { "model": self, "model_class": model_class, "model_name": capfirst(opts.verbose_name), "unique_check": unique_check, } # A unique field if len(unique_check) == 1: field = opts.get_field(unique_check[0]) params["field_label"] = capfirst(field.verbose_name) return ValidationError( message=field.error_messages["unique"], code="unique", params=params, ) # unique_together else: field_labels = [ capfirst(opts.get_field(f).verbose_name) for f in unique_check ] params["field_labels"] = get_text_list(field_labels, _("and")) return ValidationError( message=_("%(model_name)s with this %(field_labels)s already exists."), code="unique_together", params=params, ) def get_constraints(self): constraints = [(self.__class__, self._meta.constraints)] for parent_class in self._meta.get_parent_list(): if parent_class._meta.constraints: constraints.append((parent_class, parent_class._meta.constraints)) return constraints def validate_constraints(self, exclude=None): constraints = self.get_constraints() using = router.db_for_write(self.__class__, instance=self) errors = {} for model_class, model_constraints in constraints: for constraint in model_constraints: try: constraint.validate(model_class, self, exclude=exclude, using=using) except ValidationError as e: if ( getattr(e, "code", None) == "unique" and len(constraint.fields) == 1 ): errors.setdefault(constraint.fields[0], []).append(e) else: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def full_clean(self, exclude=None, validate_unique=True, validate_constraints=True): """ Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = set() else: exclude = set(exclude) try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors: if name != NON_FIELD_ERRORS and name not in exclude: exclude.add(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Run constraints checks, but only for fields that passed validation. if validate_constraints: for name in errors: if name != NON_FIELD_ERRORS and name not in exclude: exclude.add(name) try: self.validate_constraints(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def clean_fields(self, exclude=None): """ Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur. """ if exclude is None: exclude = set() errors = {} for f in self._meta.fields: if f.name in exclude: continue # Skip validation for empty fields with blank=True. The developer # is responsible for making sure they have a valid value. raw_value = getattr(self, f.attname) if f.blank and raw_value in f.empty_values: continue try: setattr(self, f.attname, f.clean(raw_value, self)) except ValidationError as e: errors[f.name] = e.error_list if errors: raise ValidationError(errors) @classmethod def check(cls, **kwargs): errors = [ *cls._check_swappable(), *cls._check_model(), *cls._check_managers(**kwargs), ] if not cls._meta.swapped: databases = kwargs.get("databases") or [] errors += [ *cls._check_fields(**kwargs), *cls._check_m2m_through_same_relationship(), *cls._check_long_column_names(databases), ] clash_errors = ( *cls._check_id_field(), *cls._check_field_name_clashes(), *cls._check_model_name_db_lookup_clashes(), *cls._check_property_name_related_field_accessor_clashes(), *cls._check_single_primary_key(), ) errors.extend(clash_errors) # If there are field name clashes, hide consequent column name # clashes. if not clash_errors: errors.extend(cls._check_column_name_clashes()) errors += [ *cls._check_index_together(), *cls._check_unique_together(), *cls._check_indexes(databases), *cls._check_ordering(), *cls._check_constraints(databases), *cls._check_default_pk(), *cls._check_db_table_comment(databases), ] return errors @classmethod def _check_default_pk(cls): if ( not cls._meta.abstract and cls._meta.pk.auto_created and # Inherited PKs are checked in parents models. not ( isinstance(cls._meta.pk, OneToOneField) and cls._meta.pk.remote_field.parent_link ) and not settings.is_overridden("DEFAULT_AUTO_FIELD") and cls._meta.app_config and not cls._meta.app_config._is_default_auto_field_overridden ): return [ checks.Warning( f"Auto-created primary key used when not defining a " f"primary key type, by default " f"'{settings.DEFAULT_AUTO_FIELD}'.", hint=( f"Configure the DEFAULT_AUTO_FIELD setting or the " f"{cls._meta.app_config.__class__.__qualname__}." f"default_auto_field attribute to point to a subclass " f"of AutoField, e.g. 'django.db.models.BigAutoField'." ), obj=cls, id="models.W042", ), ] return [] @classmethod def _check_db_table_comment(cls, databases): if not cls._meta.db_table_comment: return [] errors = [] for db in databases: if not router.allow_migrate_model(db, cls): continue connection = connections[db] if not ( connection.features.supports_comments or "supports_comments" in cls._meta.required_db_features ): errors.append( checks.Warning( f"{connection.display_name} does not support comments on " f"tables (db_table_comment).", obj=cls, id="models.W046", ) ) return errors @classmethod def _check_swappable(cls): """Check if the swapped model exists.""" errors = [] if cls._meta.swapped: try: apps.get_model(cls._meta.swapped) except ValueError: errors.append( checks.Error( "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable, id="models.E001", ) ) except LookupError: app_label, model_name = cls._meta.swapped.split(".") errors.append( checks.Error( "'%s' references '%s.%s', which has not been " "installed, or is abstract." % (cls._meta.swappable, app_label, model_name), id="models.E002", ) ) return errors @classmethod def _check_model(cls): errors = [] if cls._meta.proxy: if cls._meta.local_fields or cls._meta.local_many_to_many: errors.append( checks.Error( "Proxy model '%s' contains model fields." % cls.__name__, id="models.E017", ) ) return errors @classmethod def _check_managers(cls, **kwargs): """Perform all manager checks.""" errors = [] for manager in cls._meta.managers: errors.extend(manager.check(**kwargs)) return errors @classmethod def _check_fields(cls, **kwargs): """Perform all field checks.""" errors = [] for field in cls._meta.local_fields: errors.extend(field.check(**kwargs)) for field in cls._meta.local_many_to_many: errors.extend(field.check(from_model=cls, **kwargs)) return errors @classmethod def _check_m2m_through_same_relationship(cls): """Check if no relationship model is used by more than one m2m field.""" errors = [] seen_intermediary_signatures = [] fields = cls._meta.local_many_to_many # Skip when the target model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase)) # Skip when the relationship model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase)) for f in fields: signature = ( f.remote_field.model, cls, f.remote_field.through, f.remote_field.through_fields, ) if signature in seen_intermediary_signatures: errors.append( checks.Error( "The model has two identical many-to-many relations " "through the intermediate model '%s'." % f.remote_field.through._meta.label, obj=cls, id="models.E003", ) ) else: seen_intermediary_signatures.append(signature) return errors @classmethod def _check_id_field(cls): """Check if `id` field is a primary key.""" fields = [ f for f in cls._meta.local_fields if f.name == "id" and f != cls._meta.pk ] # fields is empty or consists of the invalid "id" field if fields and not fields[0].primary_key and cls._meta.pk.name == "id": return [ checks.Error( "'id' can only be used as a field name if the field also " "sets 'primary_key=True'.", obj=cls, id="models.E004", ) ] else: return [] @classmethod def _check_field_name_clashes(cls): """Forbid field shadowing in multi-table inheritance.""" errors = [] used_fields = {} # name or attname -> field # Check that multi-inheritance doesn't cause field name shadowing. for parent in cls._meta.get_parent_list(): for f in parent._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None if clash: errors.append( checks.Error( "The field '%s' from parent model " "'%s' clashes with the field '%s' " "from parent model '%s'." % (clash.name, clash.model._meta, f.name, f.model._meta), obj=cls, id="models.E005", ) ) used_fields[f.name] = f used_fields[f.attname] = f # Check that fields defined in the model don't clash with fields from # parents, including auto-generated fields like multi-table inheritance # child accessors. for parent in cls._meta.get_parent_list(): for f in parent._meta.get_fields(): if f not in used_fields: used_fields[f.name] = f for f in cls._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None # Note that we may detect clash between user-defined non-unique # field "id" and automatically added unique field "id", both # defined at the same model. This special case is considered in # _check_id_field and here we ignore it. id_conflict = ( f.name == "id" and clash and clash.name == "id" and clash.model == cls ) if clash and not id_conflict: errors.append( checks.Error( "The field '%s' clashes with the field '%s' " "from model '%s'." % (f.name, clash.name, clash.model._meta), obj=f, id="models.E006", ) ) used_fields[f.name] = f used_fields[f.attname] = f return errors @classmethod def _check_column_name_clashes(cls): # Store a list of column names which have already been used by other fields. used_column_names = [] errors = [] for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Ensure the column name is not already in use. if column_name and column_name in used_column_names: errors.append( checks.Error( "Field '%s' has column name '%s' that is used by " "another field." % (f.name, column_name), hint="Specify a 'db_column' for the field.", obj=cls, id="models.E007", ) ) else: used_column_names.append(column_name) return errors @classmethod def _check_model_name_db_lookup_clashes(cls): errors = [] model_name = cls.__name__ if model_name.startswith("_") or model_name.endswith("_"): errors.append( checks.Error( "The model name '%s' cannot start or end with an underscore " "as it collides with the query lookup syntax." % model_name, obj=cls, id="models.E023", ) ) elif LOOKUP_SEP in model_name: errors.append( checks.Error( "The model name '%s' cannot contain double underscores as " "it collides with the query lookup syntax." % model_name, obj=cls, id="models.E024", ) ) return errors @classmethod def _check_property_name_related_field_accessor_clashes(cls): errors = [] property_names = cls._meta._property_names related_field_accessors = ( f.get_attname() for f in cls._meta._get_fields(reverse=False) if f.is_relation and f.related_model is not None ) for accessor in related_field_accessors: if accessor in property_names: errors.append( checks.Error( "The property '%s' clashes with a related field " "accessor." % accessor, obj=cls, id="models.E025", ) ) return errors @classmethod def _check_single_primary_key(cls): errors = [] if sum(1 for f in cls._meta.local_fields if f.primary_key) > 1: errors.append( checks.Error( "The model cannot have more than one field with " "'primary_key=True'.", obj=cls, id="models.E026", ) ) return errors # RemovedInDjango51Warning. @classmethod def _check_index_together(cls): """Check the value of "index_together" option.""" if not isinstance(cls._meta.index_together, (tuple, list)): return [ checks.Error( "'index_together' must be a list or tuple.", obj=cls, id="models.E008", ) ] elif any( not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together ): return [ checks.Error( "All 'index_together' elements must be lists or tuples.", obj=cls, id="models.E009", ) ] else: errors = [] for fields in cls._meta.index_together: errors.extend(cls._check_local_fields(fields, "index_together")) return errors @classmethod def _check_unique_together(cls): """Check the value of "unique_together" option.""" if not isinstance(cls._meta.unique_together, (tuple, list)): return [ checks.Error( "'unique_together' must be a list or tuple.", obj=cls, id="models.E010", ) ] elif any( not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together ): return [ checks.Error( "All 'unique_together' elements must be lists or tuples.", obj=cls, id="models.E011", ) ] else: errors = [] for fields in cls._meta.unique_together: errors.extend(cls._check_local_fields(fields, "unique_together")) return errors @classmethod def _check_indexes(cls, databases): """Check fields, names, and conditions of indexes.""" errors = [] references = set() for index in cls._meta.indexes: # Index name can't start with an underscore or a number, restricted # for cross-database compatibility with Oracle. if index.name[0] == "_" or index.name[0].isdigit(): errors.append( checks.Error( "The index name '%s' cannot start with an underscore " "or a number." % index.name, obj=cls, id="models.E033", ), ) if len(index.name) > index.max_name_length: errors.append( checks.Error( "The index name '%s' cannot be longer than %d " "characters." % (index.name, index.max_name_length), obj=cls, id="models.E034", ), ) if index.contains_expressions: for expression in index.expressions: references.update( ref[0] for ref in cls._get_expr_references(expression) ) for db in databases: if not router.allow_migrate_model(db, cls): continue connection = connections[db] if not ( connection.features.supports_partial_indexes or "supports_partial_indexes" in cls._meta.required_db_features ) and any(index.condition is not None for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes with conditions." % connection.display_name, hint=( "Conditions will be ignored. Silence this warning " "if you don't care about it." ), obj=cls, id="models.W037", ) ) if not ( connection.features.supports_covering_indexes or "supports_covering_indexes" in cls._meta.required_db_features ) and any(index.include for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes with non-key columns." % connection.display_name, hint=( "Non-key columns will be ignored. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W040", ) ) if not ( connection.features.supports_expression_indexes or "supports_expression_indexes" in cls._meta.required_db_features ) and any(index.contains_expressions for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes on expressions." % connection.display_name, hint=( "An index won't be created. Silence this warning " "if you don't care about it." ), obj=cls, id="models.W043", ) ) fields = [ field for index in cls._meta.indexes for field, _ in index.fields_orders ] fields += [include for index in cls._meta.indexes for include in index.include] fields += references errors.extend(cls._check_local_fields(fields, "indexes")) return errors @classmethod def _check_local_fields(cls, fields, option): from django.db import models # In order to avoid hitting the relation tree prematurely, we use our # own fields_map instead of using get_field() forward_fields_map = {} for field in cls._meta._get_fields(reverse=False): forward_fields_map[field.name] = field if hasattr(field, "attname"): forward_fields_map[field.attname] = field errors = [] for field_name in fields: try: field = forward_fields_map[field_name] except KeyError: errors.append( checks.Error( "'%s' refers to the nonexistent field '%s'." % ( option, field_name, ), obj=cls, id="models.E012", ) ) else: if isinstance(field.remote_field, models.ManyToManyRel): errors.append( checks.Error( "'%s' refers to a ManyToManyField '%s', but " "ManyToManyFields are not permitted in '%s'." % ( option, field_name, option, ), obj=cls, id="models.E013", ) ) elif field not in cls._meta.local_fields: errors.append( checks.Error( "'%s' refers to field '%s' which is not local to model " "'%s'." % (option, field_name, cls._meta.object_name), hint="This issue may be caused by multi-table inheritance.", obj=cls, id="models.E016", ) ) return errors @classmethod def _check_ordering(cls): """ Check "ordering" option -- is it a list of strings and do all fields exist? """ if cls._meta._ordering_clash: return [ checks.Error( "'ordering' and 'order_with_respect_to' cannot be used together.", obj=cls, id="models.E021", ), ] if cls._meta.order_with_respect_to or not cls._meta.ordering: return [] if not isinstance(cls._meta.ordering, (list, tuple)): return [ checks.Error( "'ordering' must be a tuple or list (even if you want to order by " "only one field).", obj=cls, id="models.E014", ) ] errors = [] fields = cls._meta.ordering # Skip expressions and '?' fields. fields = (f for f in fields if isinstance(f, str) and f != "?") # Convert "-field" to "field". fields = (f.removeprefix("-") for f in fields) # Separate related fields and non-related fields. _fields = [] related_fields = [] for f in fields: if LOOKUP_SEP in f: related_fields.append(f) else: _fields.append(f) fields = _fields # Check related fields. for field in related_fields: _cls = cls fld = None for part in field.split(LOOKUP_SEP): try: # pk is an alias that won't be found by opts.get_field. if part == "pk": fld = _cls._meta.pk else: fld = _cls._meta.get_field(part) if fld.is_relation: _cls = fld.path_infos[-1].to_opts.model else: _cls = None except (FieldDoesNotExist, AttributeError): if fld is None or ( fld.get_transform(part) is None and fld.get_lookup(part) is None ): errors.append( checks.Error( "'ordering' refers to the nonexistent field, " "related field, or lookup '%s'." % field, obj=cls, id="models.E015", ) ) # Skip ordering on pk. This is always a valid order_by field # but is an alias and therefore won't be found by opts.get_field. fields = {f for f in fields if f != "pk"} # Check for invalid or nonexistent fields in ordering. invalid_fields = [] # Any field name that is not present in field_names does not exist. # Also, ordering by m2m fields is not allowed. opts = cls._meta valid_fields = set( chain.from_iterable( (f.name, f.attname) if not (f.auto_created and not f.concrete) else (f.field.related_query_name(),) for f in chain(opts.fields, opts.related_objects) ) ) invalid_fields.extend(fields - valid_fields) for invalid_field in invalid_fields: errors.append( checks.Error( "'ordering' refers to the nonexistent field, related " "field, or lookup '%s'." % invalid_field, obj=cls, id="models.E015", ) ) return errors @classmethod def _check_long_column_names(cls, databases): """ Check that any auto-generated column names are shorter than the limits for each database in which the model will be created. """ if not databases: return [] errors = [] allowed_len = None db_alias = None # Find the minimum max allowed length among all specified db_aliases. for db in databases: # skip databases where the model won't be created if not router.allow_migrate_model(db, cls): continue connection = connections[db] max_name_length = connection.ops.max_name_length() if max_name_length is None or connection.features.truncates_names: continue else: if allowed_len is None: allowed_len = max_name_length db_alias = db elif max_name_length < allowed_len: allowed_len = max_name_length db_alias = db if allowed_len is None: return errors for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Check if auto-generated name for the field is too long # for the database. if ( f.db_column is None and column_name is not None and len(column_name) > allowed_len ): errors.append( checks.Error( 'Autogenerated column name too long for field "%s". ' 'Maximum length is "%s" for database "%s".' % (column_name, allowed_len, db_alias), hint="Set the column name manually using 'db_column'.", obj=cls, id="models.E018", ) ) for f in cls._meta.local_many_to_many: # Skip nonexistent models. if isinstance(f.remote_field.through, str): continue # Check if auto-generated name for the M2M field is too long # for the database. for m2m in f.remote_field.through._meta.local_fields: _, rel_name = m2m.get_attname_column() if ( m2m.db_column is None and rel_name is not None and len(rel_name) > allowed_len ): errors.append( checks.Error( "Autogenerated column name too long for M2M field " '"%s". Maximum length is "%s" for database "%s".' % (rel_name, allowed_len, db_alias), hint=( "Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'." ), obj=cls, id="models.E019", ) ) return errors @classmethod def _get_expr_references(cls, expr): if isinstance(expr, Q): for child in expr.children: if isinstance(child, tuple): lookup, value = child yield tuple(lookup.split(LOOKUP_SEP)) yield from cls._get_expr_references(value) else: yield from cls._get_expr_references(child) elif isinstance(expr, F): yield tuple(expr.name.split(LOOKUP_SEP)) elif hasattr(expr, "get_source_expressions"): for src_expr in expr.get_source_expressions(): yield from cls._get_expr_references(src_expr) @classmethod def _check_constraints(cls, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, cls): continue connection = connections[db] if not ( connection.features.supports_table_check_constraints or "supports_table_check_constraints" in cls._meta.required_db_features ) and any( isinstance(constraint, CheckConstraint) for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support check constraints." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W027", ) ) if not ( connection.features.supports_partial_indexes or "supports_partial_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.condition is not None for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints with " "conditions." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W036", ) ) if not ( connection.features.supports_deferrable_unique_constraints or "supports_deferrable_unique_constraints" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.deferrable is not None for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support deferrable unique constraints." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W038", ) ) if not ( connection.features.supports_covering_indexes or "supports_covering_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.include for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints with non-key " "columns." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W039", ) ) if not ( connection.features.supports_expression_indexes or "supports_expression_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.contains_expressions for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints on " "expressions." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W044", ) ) fields = set( chain.from_iterable( (*constraint.fields, *constraint.include) for constraint in cls._meta.constraints if isinstance(constraint, UniqueConstraint) ) ) references = set() for constraint in cls._meta.constraints: if isinstance(constraint, UniqueConstraint): if ( connection.features.supports_partial_indexes or "supports_partial_indexes" not in cls._meta.required_db_features ) and isinstance(constraint.condition, Q): references.update( cls._get_expr_references(constraint.condition) ) if ( connection.features.supports_expression_indexes or "supports_expression_indexes" not in cls._meta.required_db_features ) and constraint.contains_expressions: for expression in constraint.expressions: references.update(cls._get_expr_references(expression)) elif isinstance(constraint, CheckConstraint): if ( connection.features.supports_table_check_constraints or "supports_table_check_constraints" not in cls._meta.required_db_features ): if isinstance(constraint.check, Q): references.update( cls._get_expr_references(constraint.check) ) if any( isinstance(expr, RawSQL) for expr in constraint.check.flatten() ): errors.append( checks.Warning( f"Check constraint {constraint.name!r} contains " f"RawSQL() expression and won't be validated " f"during the model full_clean().", hint=( "Silence this warning if you don't care about " "it." ), obj=cls, id="models.W045", ), ) for field_name, *lookups in references: # pk is an alias that won't be found by opts.get_field. if field_name != "pk": fields.add(field_name) if not lookups: # If it has no lookups it cannot result in a JOIN. continue try: if field_name == "pk": field = cls._meta.pk else: field = cls._meta.get_field(field_name) if not field.is_relation or field.many_to_many or field.one_to_many: continue except FieldDoesNotExist: continue # JOIN must happen at the first lookup. first_lookup = lookups[0] if ( hasattr(field, "get_transform") and hasattr(field, "get_lookup") and field.get_transform(first_lookup) is None and field.get_lookup(first_lookup) is None ): errors.append( checks.Error( "'constraints' refers to the joined field '%s'." % LOOKUP_SEP.join([field_name] + lookups), obj=cls, id="models.E041", ) ) errors.extend(cls._check_local_fields(fields, "constraints")) return errors ############################################ # HELPER FUNCTIONS (CURRIED MODEL METHODS) # ############################################ # ORDERING METHODS ######################### def method_set_order(self, ordered_obj, id_list, using=None): order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update( [ordered_obj(pk=pk, _order=order) for order, pk in enumerate(id_list)], ["_order"], ) def method_get_order(self, ordered_obj): order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) pk_name = ordered_obj._meta.pk.name return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True) def make_foreign_order_accessors(model, related_model): setattr( related_model, "get_%s_order" % model.__name__.lower(), partialmethod(method_get_order, model), ) setattr( related_model, "set_%s_order" % model.__name__.lower(), partialmethod(method_set_order, model), ) ######## # MISC # ######## def model_unpickle(model_id): """Used to unpickle Model subclasses with deferred fields.""" if isinstance(model_id, tuple): model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id return model.__new__(model) model_unpickle.__safe_for_unpickle__ = True
dd17557a7d5045884399977a05df72dbd7ccbf941637d4e23f02716472b452ca
import copy import datetime import functools import inspect from collections import defaultdict from decimal import Decimal from types import NoneType from uuid import UUID from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError, connection from django.db.models import fields from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import Q from django.utils.deconstruct import deconstructible from django.utils.functional import cached_property from django.utils.hashable import make_hashable class SQLiteNumericMixin: """ Some expressions with output_field=DecimalField() must be cast to numeric to be properly filtered. """ def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) try: if self.output_field.get_internal_type() == "DecimalField": sql = "CAST(%s AS NUMERIC)" % sql except FieldError: pass return sql, params class Combinable: """ Provide the ability to combine one or two objects with some connector. For example F('foo') + F('bar'). """ # Arithmetic connectors ADD = "+" SUB = "-" MUL = "*" DIV = "/" POW = "^" # The following is a quoted % operator - it is quoted because it can be # used in strings that also have parameter substitution. MOD = "%%" # Bitwise operators - note that these are generated by .bitand() # and .bitor(), the '&' and '|' are reserved for boolean operator # usage. BITAND = "&" BITOR = "|" BITLEFTSHIFT = "<<" BITRIGHTSHIFT = ">>" BITXOR = "#" def _combine(self, other, connector, reversed): if not hasattr(other, "resolve_expression"): # everything must be resolvable to an expression other = Value(other) if reversed: return CombinedExpression(other, connector, self) return CombinedExpression(self, connector, other) ############# # OPERATORS # ############# def __neg__(self): return self._combine(-1, self.MUL, False) def __add__(self, other): return self._combine(other, self.ADD, False) def __sub__(self, other): return self._combine(other, self.SUB, False) def __mul__(self, other): return self._combine(other, self.MUL, False) def __truediv__(self, other): return self._combine(other, self.DIV, False) def __mod__(self, other): return self._combine(other, self.MOD, False) def __pow__(self, other): return self._combine(other, self.POW, False) def __and__(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 bitand(self, other): return self._combine(other, self.BITAND, False) def bitleftshift(self, other): return self._combine(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) def __or__(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 bitor(self, other): return self._combine(other, self.BITOR, False) def __radd__(self, other): return self._combine(other, self.ADD, True) def __rsub__(self, other): return self._combine(other, self.SUB, True) def __rmul__(self, other): return self._combine(other, self.MUL, True) def __rtruediv__(self, other): return self._combine(other, self.DIV, True) def __rmod__(self, other): return self._combine(other, self.MOD, True) def __rpow__(self, other): return self._combine(other, self.POW, True) def __rand__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __ror__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __rxor__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __invert__(self): return NegatedExpression(self) class BaseExpression: """Base class for all query expressions.""" empty_result_set_value = NotImplemented # aggregate specific fields is_summary = False _output_field_resolved_to_none = False # Can the expression be used in a WHERE clause? filterable = True # Can the expression can be used as a source expression in Window? window_compatible = False # Can the expression be used as a database default value? allowed_default = False def __init__(self, output_field=None): if output_field is not None: self.output_field = output_field def __getstate__(self): state = self.__dict__.copy() state.pop("convert_value", None) return state def get_db_converters(self, connection): return ( [] if self.convert_value is self._convert_value_noop else [self.convert_value] ) + self.output_field.get_db_converters(connection) def get_source_expressions(self): return [] def set_source_expressions(self, exprs): assert not exprs def _parse_expressions(self, *expressions): return [ arg if hasattr(arg, "resolve_expression") else (F(arg) if isinstance(arg, str) else Value(arg)) for arg in expressions ] def as_sql(self, compiler, connection): """ Responsible for returning a (sql, [params]) tuple to be included in the current query. Different backends can provide their own implementation, by providing an `as_{vendor}` method and patching the Expression: ``` def override_as_sql(self, compiler, connection): # custom logic return super().as_sql(compiler, connection) setattr(Expression, 'as_' + connection.vendor, override_as_sql) ``` Arguments: * compiler: the query compiler responsible for generating the query. Must have a compile method, returning a (sql, [params]) tuple. Calling compiler(value) will return a quoted `value`. * connection: the database connection used for the current query. Return: (sql, params) Where `sql` is a string containing ordered sql parameters to be replaced with the elements of the list `params`. """ raise NotImplementedError("Subclasses must implement as_sql()") @cached_property def contains_aggregate(self): return any( expr and expr.contains_aggregate for expr in self.get_source_expressions() ) @cached_property def contains_over_clause(self): return any( expr and expr.contains_over_clause for expr in self.get_source_expressions() ) @cached_property def contains_column_references(self): return any( expr and expr.contains_column_references for expr in self.get_source_expressions() ) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): """ Provide the chance to do any preprocessing or validation before being added to the query. Arguments: * query: the backend query implementation * allow_joins: boolean allowing or denying use of joins in this query * reuse: a set of reusable joins for multijoins * summarize: a terminal aggregate clause * for_save: whether this expression about to be used in a save or update Return: an Expression to be added to the query. """ c = self.copy() c.is_summary = summarize c.set_source_expressions( [ expr.resolve_expression(query, allow_joins, reuse, summarize) if expr else None for expr in c.get_source_expressions() ] ) return c @property def conditional(self): return isinstance(self.output_field, fields.BooleanField) @property def field(self): return self.output_field @cached_property def output_field(self): """Return the output type of this expressions.""" output_field = self._resolve_output_field() if output_field is None: self._output_field_resolved_to_none = True raise FieldError("Cannot resolve expression type, unknown output_field") return output_field @cached_property def _output_field_or_none(self): """ Return the output field of this expression, or None if _resolve_output_field() didn't return an output type. """ try: return self.output_field except FieldError: if not self._output_field_resolved_to_none: raise def _resolve_output_field(self): """ Attempt to infer the output type of the expression. As a guess, if the output fields of all source fields match then simply infer the same type here. If a source's output field resolves to None, exclude it from this check. If all sources are None, then an error is raised higher up the stack in the output_field property. """ # This guess is mostly a bad idea, but there is quite a lot of code # (especially 3rd party Func subclasses) that depend on it, we'd need a # deprecation path to fix it. sources_iter = ( source for source in self.get_source_fields() if source is not None ) for output_field in sources_iter: for source in sources_iter: if not isinstance(output_field, source.__class__): raise FieldError( "Expression contains mixed types: %s, %s. You must " "set output_field." % ( output_field.__class__.__name__, source.__class__.__name__, ) ) return output_field @staticmethod def _convert_value_noop(value, expression, connection): return value @cached_property def convert_value(self): """ Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns. """ field = self.output_field internal_type = field.get_internal_type() if internal_type == "FloatField": return ( lambda value, expression, connection: None if value is None else float(value) ) elif internal_type.endswith("IntegerField"): return ( lambda value, expression, connection: None if value is None else int(value) ) elif internal_type == "DecimalField": return ( lambda value, expression, connection: None if value is None else Decimal(value) ) return self._convert_value_noop def get_lookup(self, lookup): return self.output_field.get_lookup(lookup) def get_transform(self, name): return self.output_field.get_transform(name) def relabeled_clone(self, change_map): clone = self.copy() clone.set_source_expressions( [ e.relabeled_clone(change_map) if e is not None else None for e in self.get_source_expressions() ] ) return clone def replace_expressions(self, replacements): if replacement := replacements.get(self): return replacement clone = self.copy() source_expressions = clone.get_source_expressions() clone.set_source_expressions( [ expr.replace_expressions(replacements) if expr else None for expr in source_expressions ] ) return clone def get_refs(self): refs = set() for expr in self.get_source_expressions(): refs |= expr.get_refs() return refs def copy(self): return copy.copy(self) def prefix_references(self, prefix): clone = self.copy() clone.set_source_expressions( [ F(f"{prefix}{expr.name}") if isinstance(expr, F) else expr.prefix_references(prefix) for expr in self.get_source_expressions() ] ) return clone def get_group_by_cols(self): if not self.contains_aggregate: return [self] cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def get_source_fields(self): """Return the underlying field types used by this aggregate.""" return [e._output_field_or_none for e in self.get_source_expressions()] def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def reverse_ordering(self): return self def flatten(self): """ Recursively yield this expression and all subexpressions, in depth-first order. """ yield self for expr in self.get_source_expressions(): if expr: if hasattr(expr, "flatten"): yield from expr.flatten() else: yield expr def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, EXISTS expressions need to be wrapped in CASE WHEN on Oracle. """ if hasattr(self.output_field, "select_format"): return self.output_field.select_format(compiler, sql, params) return sql, params @deconstructible class Expression(BaseExpression, Combinable): """An expression that can be combined with other expressions.""" @cached_property def identity(self): constructor_signature = inspect.signature(self.__init__) args, kwargs = self._constructor_args signature = constructor_signature.bind_partial(*args, **kwargs) signature.apply_defaults() arguments = signature.arguments.items() identity = [self.__class__] for arg, value in arguments: if isinstance(value, fields.Field): if value.name and value.model: value = (value.model._meta.label, value.name) else: value = type(value) else: value = make_hashable(value) identity.append((arg, value)) return tuple(identity) def __eq__(self, other): if not isinstance(other, Expression): return NotImplemented return other.identity == self.identity def __hash__(self): return hash(self.identity) # Type inference for CombinedExpression.output_field. # Missing items will result in FieldError, by design. # # The current approach for NULL is based on lowest common denominator behavior # i.e. if one of the supported databases is raising an error (rather than # return NULL) for `val <op> NULL`, then Django raises FieldError. _connector_combinations = [ # Numeric operations - operands of same type. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), (fields.FloatField, fields.FloatField, fields.FloatField), (fields.DecimalField, fields.DecimalField, fields.DecimalField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, # Behavior for DIV with integer arguments follows Postgres/SQLite, # not MySQL/Oracle. Combinable.DIV, Combinable.MOD, Combinable.POW, ) }, # Numeric operations - operands of different type. { connector: [ (fields.IntegerField, fields.DecimalField, fields.DecimalField), (fields.DecimalField, fields.IntegerField, fields.DecimalField), (fields.IntegerField, fields.FloatField, fields.FloatField), (fields.FloatField, fields.IntegerField, fields.FloatField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, ) }, # Bitwise operators. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), ] for connector in ( Combinable.BITAND, Combinable.BITOR, Combinable.BITLEFTSHIFT, Combinable.BITRIGHTSHIFT, Combinable.BITXOR, ) }, # Numeric with NULL. { connector: [ (field_type, NoneType, field_type), (NoneType, field_type, field_type), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, Combinable.POW, ) for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField) }, # Date/DateTimeField/DurationField/TimeField. { Combinable.ADD: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DurationField, fields.DateField, fields.DateTimeField), (fields.DurationField, fields.DateTimeField, fields.DateTimeField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.DurationField, fields.TimeField, fields.TimeField), ], }, { Combinable.SUB: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DateField, fields.DateField, fields.DurationField), (fields.DateField, fields.DateTimeField, fields.DurationField), (fields.DateTimeField, fields.DateField, fields.DurationField), (fields.DateTimeField, fields.DateTimeField, fields.DurationField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.TimeField, fields.TimeField, fields.DurationField), ], }, ] _connector_combinators = defaultdict(list) def register_combinable_fields(lhs, connector, rhs, result): """ Register combinable types: lhs <connector> rhs -> result e.g. register_combinable_fields( IntegerField, Combinable.ADD, FloatField, FloatField ) """ _connector_combinators[connector].append((lhs, rhs, result)) for d in _connector_combinations: for connector, field_types in d.items(): for lhs, rhs, result in field_types: register_combinable_fields(lhs, connector, rhs, result) @functools.lru_cache(maxsize=128) def _resolve_combined_type(connector, lhs_type, rhs_type): combinators = _connector_combinators.get(connector, ()) for combinator_lhs_type, combinator_rhs_type, combined_type in combinators: if issubclass(lhs_type, combinator_lhs_type) and issubclass( rhs_type, combinator_rhs_type ): return combined_type class CombinedExpression(SQLiteNumericMixin, Expression): def __init__(self, lhs, connector, rhs, output_field=None): super().__init__(output_field=output_field) self.connector = connector self.lhs = lhs self.rhs = rhs def __repr__(self): return "<{}: {}>".format(self.__class__.__name__, self) def __str__(self): return "{} {} {}".format(self.lhs, self.connector, self.rhs) def get_source_expressions(self): return [self.lhs, self.rhs] def set_source_expressions(self, exprs): self.lhs, self.rhs = exprs def _resolve_output_field(self): # We avoid using super() here for reasons given in # Expression._resolve_output_field() combined_type = _resolve_combined_type( self.connector, type(self.lhs._output_field_or_none), type(self.rhs._output_field_or_none), ) if combined_type is None: raise FieldError( f"Cannot infer type of {self.connector!r} expression involving these " f"types: {self.lhs.output_field.__class__.__name__}, " f"{self.rhs.output_field.__class__.__name__}. You must set " f"output_field." ) return combined_type() def as_sql(self, compiler, connection): expressions = [] expression_params = [] sql, params = compiler.compile(self.lhs) expressions.append(sql) expression_params.extend(params) sql, params = compiler.compile(self.rhs) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not isinstance(self, (DurationExpression, TemporalSubtraction)): try: lhs_type = lhs.output_field.get_internal_type() except (AttributeError, FieldError): lhs_type = None try: rhs_type = rhs.output_field.get_internal_type() except (AttributeError, FieldError): rhs_type = None if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type: return DurationExpression( self.lhs, self.connector, self.rhs ).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) datetime_fields = {"DateField", "DateTimeField", "TimeField"} if ( self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type ): return TemporalSubtraction(self.lhs, self.rhs).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) c = self.copy() c.is_summary = summarize c.lhs = lhs c.rhs = rhs return c @cached_property def allowed_default(self): return self.lhs.allowed_default and self.rhs.allowed_default class DurationExpression(CombinedExpression): def compile(self, side, compiler, connection): try: output = side.output_field except FieldError: pass else: if output.get_internal_type() == "DurationField": sql, params = compiler.compile(side) return connection.ops.format_for_duration_arithmetic(sql), params return compiler.compile(side) def as_sql(self, compiler, connection): if connection.features.has_native_duration_field: return super().as_sql(compiler, connection) connection.ops.check_expression_support(self) expressions = [] expression_params = [] sql, params = self.compile(self.lhs, compiler, connection) expressions.append(sql) expression_params.extend(params) sql, params = self.compile(self.rhs, compiler, connection) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_duration_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) if self.connector in {Combinable.MUL, Combinable.DIV}: try: lhs_type = self.lhs.output_field.get_internal_type() rhs_type = self.rhs.output_field.get_internal_type() except (AttributeError, FieldError): pass else: allowed_fields = { "DecimalField", "DurationField", "FloatField", "IntegerField", } if lhs_type not in allowed_fields or rhs_type not in allowed_fields: raise DatabaseError( f"Invalid arguments for operator {self.connector}." ) return sql, params class TemporalSubtraction(CombinedExpression): output_field = fields.DurationField() def __init__(self, lhs, rhs): super().__init__(lhs, self.SUB, rhs) def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) lhs = compiler.compile(self.lhs) rhs = compiler.compile(self.rhs) return connection.ops.subtract_temporals( self.lhs.output_field.get_internal_type(), lhs, rhs ) @deconstructible(path="django.db.models.F") class F(Combinable): """An object capable of resolving references to existing query objects.""" allowed_default = False def __init__(self, name): """ Arguments: * name: the name of the field this expression references """ self.name = name def __repr__(self): return "{}({})".format(self.__class__.__name__, self.name) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): return query.resolve_ref(self.name, allow_joins, reuse, summarize) def replace_expressions(self, replacements): return replacements.get(self, self) def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def __eq__(self, other): return self.__class__ == other.__class__ and self.name == other.name def __hash__(self): return hash(self.name) def copy(self): return copy.copy(self) class ResolvedOuterRef(F): """ An object that contains a reference to an outer query. In this case, the reference to the outer query has been resolved because the inner query has been used as a subquery. """ contains_aggregate = False contains_over_clause = False def as_sql(self, *args, **kwargs): raise ValueError( "This queryset contains a reference to an outer query and may " "only be used in a subquery." ) def resolve_expression(self, *args, **kwargs): col = super().resolve_expression(*args, **kwargs) if col.contains_over_clause: raise NotSupportedError( f"Referencing outer query window expression is not supported: " f"{self.name}." ) # FIXME: Rename possibly_multivalued to multivalued and fix detection # for non-multivalued JOINs (e.g. foreign key fields). This should take # into account only many-to-many and one-to-many relationships. col.possibly_multivalued = LOOKUP_SEP in self.name return col def relabeled_clone(self, relabels): return self def get_group_by_cols(self): return [] class OuterRef(F): contains_aggregate = False def resolve_expression(self, *args, **kwargs): if isinstance(self.name, self.__class__): return self.name return ResolvedOuterRef(self.name) def relabeled_clone(self, relabels): return self @deconstructible(path="django.db.models.Func") class Func(SQLiteNumericMixin, Expression): """An SQL function call.""" function = None template = "%(function)s(%(expressions)s)" arg_joiner = ", " arity = None # The number of arguments the function accepts. def __init__(self, *expressions, output_field=None, **extra): if self.arity is not None and len(expressions) != self.arity: raise TypeError( "'%s' takes exactly %s %s (%s given)" % ( self.__class__.__name__, self.arity, "argument" if self.arity == 1 else "arguments", len(expressions), ) ) super().__init__(output_field=output_field) self.source_expressions = self._parse_expressions(*expressions) self.extra = extra def __repr__(self): args = self.arg_joiner.join(str(arg) for arg in self.source_expressions) extra = {**self.extra, **self._get_repr_options()} if extra: extra = ", ".join( str(key) + "=" + str(val) for key, val in sorted(extra.items()) ) return "{}({}, {})".format(self.__class__.__name__, args, extra) return "{}({})".format(self.__class__.__name__, args) def _get_repr_options(self): """Return a dict of extra __init__() options to include in the repr.""" return {} def get_source_expressions(self): return self.source_expressions def set_source_expressions(self, exprs): self.source_expressions = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, arg in enumerate(c.source_expressions): c.source_expressions[pos] = arg.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql( self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context, ): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: try: arg_sql, arg_params = compiler.compile(arg) except EmptyResultSet: empty_result_set_value = getattr( arg, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: raise arg_sql, arg_params = compiler.compile(Value(empty_result_set_value)) except FullResultSet: arg_sql, arg_params = compiler.compile(Value(True)) sql_parts.append(arg_sql) params.extend(arg_params) data = {**self.extra, **extra_context} # Use the first supplied value in this order: the parameter to this # method, a value supplied in __init__()'s **extra (the value in # `data`), or the value defined on the class. if function is not None: data["function"] = function else: data.setdefault("function", self.function) template = template or data.get("template", self.template) arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner) data["expressions"] = data["field"] = arg_joiner.join(sql_parts) return template % data, params def copy(self): copy = super().copy() copy.source_expressions = self.source_expressions[:] copy.extra = self.extra.copy() return copy @cached_property def allowed_default(self): return all(expression.allowed_default for expression in self.source_expressions) @deconstructible(path="django.db.models.Value") class Value(SQLiteNumericMixin, Expression): """Represent a wrapped value as a node within an expression.""" # Provide a default value for `for_save` in order to allow unresolved # instances to be compiled until a decision is taken in #25425. for_save = False allowed_default = True def __init__(self, value, output_field=None): """ Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted. * output_field: an instance of the model field type that this expression will return, such as IntegerField() or CharField(). """ super().__init__(output_field=output_field) self.value = value def __repr__(self): return f"{self.__class__.__name__}({self.value!r})" def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) val = self.value output_field = self._output_field_or_none if output_field is not None: if self.for_save: val = output_field.get_db_prep_save(val, connection=connection) else: val = output_field.get_db_prep_value(val, connection=connection) if hasattr(output_field, "get_placeholder"): return output_field.get_placeholder(val, compiler, connection), [val] if val is None: # cx_Oracle does not always convert None to the appropriate # NULL type (like in case expressions using numbers), so we # use a literal SQL NULL return "NULL", [] return "%s", [val] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) c.for_save = for_save return c def get_group_by_cols(self): return [] def _resolve_output_field(self): if isinstance(self.value, str): return fields.CharField() if isinstance(self.value, bool): return fields.BooleanField() if isinstance(self.value, int): return fields.IntegerField() if isinstance(self.value, float): return fields.FloatField() if isinstance(self.value, datetime.datetime): return fields.DateTimeField() if isinstance(self.value, datetime.date): return fields.DateField() if isinstance(self.value, datetime.time): return fields.TimeField() if isinstance(self.value, datetime.timedelta): return fields.DurationField() if isinstance(self.value, Decimal): return fields.DecimalField() if isinstance(self.value, bytes): return fields.BinaryField() if isinstance(self.value, UUID): return fields.UUIDField() @property def empty_result_set_value(self): return self.value class RawSQL(Expression): allowed_default = True def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super().__init__(output_field=output_field) def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params) def as_sql(self, compiler, connection): return "(%s)" % self.sql, self.params def get_group_by_cols(self): return [self] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # Resolve parents fields used in raw SQL. if query.model: for parent in query.model._meta.get_parent_list(): for parent_field in parent._meta.local_fields: _, column_name = parent_field.get_attname_column() if column_name.lower() in self.sql.lower(): query.resolve_ref( parent_field.name, allow_joins, reuse, summarize ) break return super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) class Star(Expression): def __repr__(self): return "'*'" def as_sql(self, compiler, connection): return "*", [] class DatabaseDefault(Expression): """Placeholder expression for the database default in an insert query.""" def as_sql(self, compiler, connection): return "DEFAULT", [] class Col(Expression): contains_column_references = True possibly_multivalued = False def __init__(self, alias, target, output_field=None): if output_field is None: output_field = target super().__init__(output_field=output_field) self.alias, self.target = alias, target def __repr__(self): alias, target = self.alias, self.target identifiers = (alias, str(target)) if alias else (str(target),) return "{}({})".format(self.__class__.__name__, ", ".join(identifiers)) def as_sql(self, compiler, connection): alias, column = self.alias, self.target.column identifiers = (alias, column) if alias else (column,) sql = ".".join(map(compiler.quote_name_unless_alias, identifiers)) return sql, [] def relabeled_clone(self, relabels): if self.alias is None: return self return self.__class__( relabels.get(self.alias, self.alias), self.target, self.output_field ) def get_group_by_cols(self): return [self] def get_db_converters(self, connection): if self.target == self.output_field: return self.output_field.get_db_converters(connection) return self.output_field.get_db_converters( connection ) + self.target.get_db_converters(connection) class Ref(Expression): """ Reference to column alias of the query. For example, Ref('sum_cost') in qs.annotate(sum_cost=Sum('cost')) query. """ def __init__(self, refs, source): super().__init__() self.refs, self.source = refs, source def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source) def get_source_expressions(self): return [self.source] def set_source_expressions(self, exprs): (self.source,) = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # The sub-expression `source` has already been resolved, as this is # just a reference to the name of `source`. return self def get_refs(self): return {self.refs} def relabeled_clone(self, relabels): return self def as_sql(self, compiler, connection): return connection.ops.quote_name(self.refs), [] def get_group_by_cols(self): return [self] class ExpressionList(Func): """ An expression containing multiple expressions. Can be used to provide a list of expressions as an argument to another expression, like a partition clause. """ template = "%(expressions)s" def __init__(self, *expressions, **extra): if not expressions: raise ValueError( "%s requires at least one expression." % self.__class__.__name__ ) super().__init__(*expressions, **extra) def __str__(self): return self.arg_joiner.join(str(arg) for arg in self.source_expressions) def as_sqlite(self, compiler, connection, **extra_context): # Casting to numeric is unnecessary. return self.as_sql(compiler, connection, **extra_context) class OrderByList(Func): allowed_default = False template = "ORDER BY %(expressions)s" def __init__(self, *expressions, **extra): expressions = ( ( OrderBy(F(expr[1:]), descending=True) if isinstance(expr, str) and expr[0] == "-" else expr ) for expr in expressions ) super().__init__(*expressions, **extra) def as_sql(self, *args, **kwargs): if not self.source_expressions: return "", () return super().as_sql(*args, **kwargs) def get_group_by_cols(self): group_by_cols = [] for order_by in self.get_source_expressions(): group_by_cols.extend(order_by.get_group_by_cols()) return group_by_cols @deconstructible(path="django.db.models.ExpressionWrapper") class ExpressionWrapper(SQLiteNumericMixin, Expression): """ An expression that can wrap another expression so that it can provide extra context to the inner expression, such as the output_field. """ def __init__(self, expression, output_field): super().__init__(output_field=output_field) self.expression = expression def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def get_group_by_cols(self): if isinstance(self.expression, Expression): expression = self.expression.copy() expression.output_field = self.output_field return expression.get_group_by_cols() # For non-expressions e.g. an SQL WHERE clause, the entire # `expression` must be included in the GROUP BY clause. return super().get_group_by_cols() def as_sql(self, compiler, connection): return compiler.compile(self.expression) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.expression) @property def allowed_default(self): return self.expression.allowed_default class NegatedExpression(ExpressionWrapper): """The logical negation of a conditional expression.""" def __init__(self, expression): super().__init__(expression, output_field=fields.BooleanField()) def __invert__(self): return self.expression.copy() def as_sql(self, compiler, connection): try: sql, params = super().as_sql(compiler, connection) except EmptyResultSet: features = compiler.connection.features if not features.supports_boolean_expr_in_select_clause: return "1=1", () return compiler.compile(Value(True)) ops = compiler.connection.ops # Some database backends (e.g. Oracle) don't allow EXISTS() and filters # to be compared to another expression unless they're wrapped in a CASE # WHEN. if not ops.conditional_expression_supported_in_where_clause(self.expression): return f"CASE WHEN {sql} = 0 THEN 1 ELSE 0 END", params return f"NOT {sql}", params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): resolved = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not getattr(resolved.expression, "conditional", False): raise TypeError("Cannot negate non-conditional expressions.") return resolved def select_format(self, compiler, sql, params): # Wrap boolean expressions with a CASE WHEN expression if a database # backend (e.g. Oracle) doesn't support boolean expression in SELECT or # GROUP BY list. expression_supported_in_where_clause = ( compiler.connection.ops.conditional_expression_supported_in_where_clause ) if ( not compiler.connection.features.supports_boolean_expr_in_select_clause # Avoid double wrapping. and expression_supported_in_where_clause(self.expression) ): sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.When") class When(Expression): template = "WHEN %(condition)s THEN %(result)s" # This isn't a complete conditional expression, must be used in Case(). conditional = False def __init__(self, condition=None, then=None, **lookups): if lookups: if condition is None: condition, lookups = Q(**lookups), None elif getattr(condition, "conditional", False): condition, lookups = Q(condition, **lookups), None if condition is None or not getattr(condition, "conditional", False) or lookups: raise TypeError( "When() supports a Q object, a boolean expression, or lookups " "as a condition." ) if isinstance(condition, Q) and not condition: raise ValueError("An empty Q() can't be used as a When() condition.") super().__init__(output_field=None) self.condition = condition self.result = self._parse_expressions(then)[0] def __str__(self): return "WHEN %r THEN %r" % (self.condition, self.result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return [self.condition, self.result] def set_source_expressions(self, exprs): self.condition, self.result = exprs def get_source_fields(self): # We're only interested in the fields of the result expressions. return [self.result._output_field_or_none] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize if hasattr(c.condition, "resolve_expression"): c.condition = c.condition.resolve_expression( query, allow_joins, reuse, summarize, False ) c.result = c.result.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = extra_context sql_params = [] condition_sql, condition_params = compiler.compile(self.condition) template_params["condition"] = condition_sql result_sql, result_params = compiler.compile(self.result) template_params["result"] = result_sql template = template or self.template return template % template_params, ( *sql_params, *condition_params, *result_params, ) def get_group_by_cols(self): # This is not a complete expression and cannot be used in GROUP BY. cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols @cached_property def allowed_default(self): return self.condition.allowed_default and self.result.allowed_default @deconstructible(path="django.db.models.Case") class Case(SQLiteNumericMixin, Expression): """ An SQL searched CASE expression: CASE WHEN n > 0 THEN 'positive' WHEN n < 0 THEN 'negative' ELSE 'zero' END """ template = "CASE %(cases)s ELSE %(default)s END" case_joiner = " " def __init__(self, *cases, default=None, output_field=None, **extra): if not all(isinstance(case, When) for case in cases): raise TypeError("Positional arguments must all be When objects.") super().__init__(output_field) self.cases = list(cases) self.default = self._parse_expressions(default)[0] self.extra = extra def __str__(self): return "CASE %s, ELSE %r" % ( ", ".join(str(c) for c in self.cases), self.default, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return self.cases + [self.default] def set_source_expressions(self, exprs): *self.cases, self.default = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, case in enumerate(c.cases): c.cases[pos] = case.resolve_expression( query, allow_joins, reuse, summarize, for_save ) c.default = c.default.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def copy(self): c = super().copy() c.cases = c.cases[:] return c def as_sql( self, compiler, connection, template=None, case_joiner=None, **extra_context ): connection.ops.check_expression_support(self) if not self.cases: return compiler.compile(self.default) template_params = {**self.extra, **extra_context} case_parts = [] sql_params = [] default_sql, default_params = compiler.compile(self.default) for case in self.cases: try: case_sql, case_params = compiler.compile(case) except EmptyResultSet: continue except FullResultSet: default_sql, default_params = compiler.compile(case.result) break case_parts.append(case_sql) sql_params.extend(case_params) if not case_parts: return default_sql, default_params case_joiner = case_joiner or self.case_joiner template_params["cases"] = case_joiner.join(case_parts) template_params["default"] = default_sql sql_params.extend(default_params) template = template or template_params.get("template", self.template) sql = template % template_params if self._output_field_or_none is not None: sql = connection.ops.unification_cast_sql(self.output_field) % sql return sql, sql_params def get_group_by_cols(self): if not self.cases: return self.default.get_group_by_cols() return super().get_group_by_cols() @cached_property def allowed_default(self): return self.default.allowed_default and all( case_.allowed_default for case_ in self.cases ) class Subquery(BaseExpression, Combinable): """ An explicit subquery. It may contain OuterRef() references to the outer query which will be resolved when it is applied to that query. """ template = "(%(subquery)s)" contains_aggregate = False empty_result_set_value = None def __init__(self, queryset, output_field=None, **extra): # Allow the usage of both QuerySet and sql.Query objects. self.query = getattr(queryset, "query", queryset).clone() self.query.subquery = True self.extra = extra super().__init__(output_field) def get_source_expressions(self): return [self.query] def set_source_expressions(self, exprs): self.query = exprs[0] def _resolve_output_field(self): return self.query.output_field def copy(self): clone = super().copy() clone.query = clone.query.clone() return clone @property def external_aliases(self): return self.query.external_aliases def get_external_cols(self): return self.query.get_external_cols() def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = {**self.extra, **extra_context} subquery_sql, sql_params = self.query.as_sql(compiler, connection) template_params["subquery"] = subquery_sql[1:-1] template = template or template_params.get("template", self.template) sql = template % template_params return sql, sql_params def get_group_by_cols(self): return self.query.get_group_by_cols(wrapper=self) class Exists(Subquery): template = "EXISTS(%(subquery)s)" output_field = fields.BooleanField() empty_result_set_value = False def __init__(self, queryset, **kwargs): super().__init__(queryset, **kwargs) self.query = self.query.exists() def select_format(self, compiler, sql, params): # Wrap EXISTS() with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.OrderBy") class OrderBy(Expression): template = "%(expression)s %(ordering)s" conditional = False def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None): if nulls_first and nulls_last: raise ValueError("nulls_first and nulls_last are mutually exclusive") if nulls_first is False or nulls_last is False: raise ValueError("nulls_first and nulls_last values must be True or None.") self.nulls_first = nulls_first self.nulls_last = nulls_last self.descending = descending if not hasattr(expression, "resolve_expression"): raise ValueError("expression must be an expression type") self.expression = expression def __repr__(self): return "{}({}, descending={})".format( self.__class__.__name__, self.expression, self.descending ) def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def as_sql(self, compiler, connection, template=None, **extra_context): template = template or self.template if connection.features.supports_order_by_nulls_modifier: if self.nulls_last: template = "%s NULLS LAST" % template elif self.nulls_first: template = "%s NULLS FIRST" % template else: if self.nulls_last and not ( self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NULL, %s" % template elif self.nulls_first and not ( not self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NOT NULL, %s" % template connection.ops.check_expression_support(self) expression_sql, params = compiler.compile(self.expression) placeholders = { "expression": expression_sql, "ordering": "DESC" if self.descending else "ASC", **extra_context, } params *= template.count("%(expression)s") return (template % placeholders).rstrip(), params def as_oracle(self, compiler, connection): # Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped # in a CASE WHEN. if connection.ops.conditional_expression_supported_in_where_clause( self.expression ): copy = self.copy() copy.expression = Case( When(self.expression, then=True), default=False, ) return copy.as_sql(compiler, connection) return self.as_sql(compiler, connection) def get_group_by_cols(self): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def reverse_ordering(self): self.descending = not self.descending if self.nulls_first: self.nulls_last = True self.nulls_first = None elif self.nulls_last: self.nulls_first = True self.nulls_last = None return self def asc(self): self.descending = False def desc(self): self.descending = True class Window(SQLiteNumericMixin, Expression): template = "%(expression)s OVER (%(window)s)" # Although the main expression may either be an aggregate or an # expression with an aggregate function, the GROUP BY that will # be introduced in the query as a result is not desired. contains_aggregate = False contains_over_clause = True def __init__( self, expression, partition_by=None, order_by=None, frame=None, output_field=None, ): self.partition_by = partition_by self.order_by = order_by self.frame = frame if not getattr(expression, "window_compatible", False): raise ValueError( "Expression '%s' isn't compatible with OVER clauses." % expression.__class__.__name__ ) if self.partition_by is not None: if not isinstance(self.partition_by, (tuple, list)): self.partition_by = (self.partition_by,) self.partition_by = ExpressionList(*self.partition_by) if self.order_by is not None: if isinstance(self.order_by, (list, tuple)): self.order_by = OrderByList(*self.order_by) elif isinstance(self.order_by, (BaseExpression, str)): self.order_by = OrderByList(self.order_by) else: raise ValueError( "Window.order_by must be either a string reference to a " "field, an expression, or a list or tuple of them." ) super().__init__(output_field=output_field) self.source_expression = self._parse_expressions(expression)[0] def _resolve_output_field(self): return self.source_expression.output_field def get_source_expressions(self): return [self.source_expression, self.partition_by, self.order_by, self.frame] def set_source_expressions(self, exprs): self.source_expression, self.partition_by, self.order_by, self.frame = exprs def as_sql(self, compiler, connection, template=None): connection.ops.check_expression_support(self) if not connection.features.supports_over_clause: raise NotSupportedError("This backend does not support window expressions.") expr_sql, params = compiler.compile(self.source_expression) window_sql, window_params = [], () if self.partition_by is not None: sql_expr, sql_params = self.partition_by.as_sql( compiler=compiler, connection=connection, template="PARTITION BY %(expressions)s", ) window_sql.append(sql_expr) window_params += tuple(sql_params) if self.order_by is not None: order_sql, order_params = compiler.compile(self.order_by) window_sql.append(order_sql) window_params += tuple(order_params) if self.frame: frame_sql, frame_params = compiler.compile(self.frame) window_sql.append(frame_sql) window_params += tuple(frame_params) template = template or self.template return ( template % {"expression": expr_sql, "window": " ".join(window_sql).strip()}, (*params, *window_params), ) def as_sqlite(self, compiler, connection): if isinstance(self.output_field, fields.DecimalField): # Casting to numeric must be outside of the window expression. copy = self.copy() source_expressions = copy.get_source_expressions() source_expressions[0].output_field = fields.FloatField() copy.set_source_expressions(source_expressions) return super(Window, copy).as_sqlite(compiler, connection) return self.as_sql(compiler, connection) def __str__(self): return "{} OVER ({}{}{})".format( str(self.source_expression), "PARTITION BY " + str(self.partition_by) if self.partition_by else "", str(self.order_by or ""), str(self.frame or ""), ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): group_by_cols = [] if self.partition_by: group_by_cols.extend(self.partition_by.get_group_by_cols()) if self.order_by is not None: group_by_cols.extend(self.order_by.get_group_by_cols()) return group_by_cols class WindowFrame(Expression): """ Model the frame clause in window expressions. There are two types of frame clauses which are subclasses, however, all processing and validation (by no means intended to be complete) is done here. Thus, providing an end for a frame is optional (the default is UNBOUNDED FOLLOWING, which is the last row in the frame). """ template = "%(frame_type)s BETWEEN %(start)s AND %(end)s" def __init__(self, start=None, end=None): self.start = Value(start) self.end = Value(end) def set_source_expressions(self, exprs): self.start, self.end = exprs def get_source_expressions(self): return [self.start, self.end] def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) start, end = self.window_frame_start_end( connection, self.start.value, self.end.value ) return ( self.template % { "frame_type": self.frame_type, "start": start, "end": end, }, [], ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): return [] def __str__(self): if self.start.value is not None and self.start.value < 0: start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING) elif self.start.value is not None and self.start.value == 0: start = connection.ops.CURRENT_ROW else: start = connection.ops.UNBOUNDED_PRECEDING if self.end.value is not None and self.end.value > 0: end = "%d %s" % (self.end.value, connection.ops.FOLLOWING) elif self.end.value is not None and self.end.value == 0: end = connection.ops.CURRENT_ROW else: end = connection.ops.UNBOUNDED_FOLLOWING return self.template % { "frame_type": self.frame_type, "start": start, "end": end, } def window_frame_start_end(self, connection, start, end): raise NotImplementedError("Subclasses must implement window_frame_start_end().") class RowRange(WindowFrame): frame_type = "ROWS" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_rows_start_end(start, end) class ValueRange(WindowFrame): frame_type = "RANGE" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_range_start_end(start, end)
ffb01d913a3795db839b06bf4c393c25e5ce52375ce850181f5ab57c27a46f6e
import itertools import math from django.core.exceptions import EmptyResultSet, FullResultSet from django.db.models.expressions import Case, Expression, Func, Value, When from django.db.models.fields import ( BooleanField, CharField, DateTimeField, Field, IntegerField, UUIDField, ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet from django.utils.functional import cached_property from django.utils.hashable import make_hashable class Lookup(Expression): lookup_name = None prepare_rhs = True can_use_none_as_rhs = False def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs self.rhs = self.get_prep_lookup() self.lhs = 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 # a bilateral transformation on a nested QuerySet: that won't work. from django.db.models.sql.query import Query # avoid circular import if isinstance(rhs, Query): raise NotImplementedError( "Bilateral transformations on nested querysets are not implemented." ) self.bilateral_transforms = bilateral_transforms def apply_bilateral_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_process_rhs(self, compiler, connection, rhs=None): if rhs is None: rhs = self.rhs if self.bilateral_transforms: sqls, sqls_params = [], [] for p in rhs: value = Value(p, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) sql, sql_params = compiler.compile(value) sqls.append(sql) sqls_params.extend(sql_params) else: _, params = self.get_db_prep_lookup(rhs, connection) sqls, sqls_params = ["%s"] * len(params), params return sqls, sqls_params def get_source_expressions(self): if self.rhs_is_direct_value(): return [self.lhs] return [self.lhs, self.rhs] def set_source_expressions(self, new_exprs): if len(new_exprs) == 1: self.lhs = new_exprs[0] else: self.lhs, self.rhs = new_exprs def get_prep_lookup(self): if not self.prepare_rhs or hasattr(self.rhs, "resolve_expression"): return self.rhs if hasattr(self.lhs, "output_field"): if hasattr(self.lhs.output_field, "get_prep_value"): return self.lhs.output_field.get_prep_value(self.rhs) elif self.rhs_is_direct_value(): return Value(self.rhs) return self.rhs def get_prep_lhs(self): if hasattr(self.lhs, "resolve_expression"): return self.lhs return Value(self.lhs) def get_db_prep_lookup(self, value, connection): return ("%s", [value]) def process_lhs(self, compiler, connection, lhs=None): lhs = lhs or self.lhs if hasattr(lhs, "resolve_expression"): lhs = lhs.resolve_expression(compiler.query) sql, params = compiler.compile(lhs) if isinstance(lhs, Lookup): # Wrapped in parentheses to respect operator precedence. sql = f"({sql})" return sql, params def process_rhs(self, compiler, connection): value = self.rhs if self.bilateral_transforms: if self.rhs_is_direct_value(): # Do not call get_db_prep_lookup here as the value will be # transformed before being used for lookup value = Value(value, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) if hasattr(value, "as_sql"): sql, params = compiler.compile(value) # Ensure expression is wrapped in parentheses to respect operator # precedence but avoid double wrapping as it can be misinterpreted # on some backends (e.g. subqueries on SQLite). if sql and sql[0] != "(": sql = "(%s)" % sql return sql, params else: return self.get_db_prep_lookup(value, connection) def rhs_is_direct_value(self): return not hasattr(self.rhs, "as_sql") def get_group_by_cols(self): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def as_oracle(self, compiler, connection): # Oracle doesn't allow EXISTS() and filters to be compared to another # expression unless they're wrapped in a CASE WHEN. wrapped = False exprs = [] for expr in (self.lhs, self.rhs): if connection.ops.conditional_expression_supported_in_where_clause(expr): expr = Case(When(expr, then=True), default=False) wrapped = True exprs.append(expr) lookup = type(self)(*exprs) if wrapped else self return lookup.as_sql(compiler, connection) @cached_property def output_field(self): return BooleanField() @property def identity(self): return self.__class__, self.lhs, self.rhs def __eq__(self, other): if not isinstance(other, Lookup): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(make_hashable(self.identity)) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize c.lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if hasattr(self.rhs, "resolve_expression"): c.rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def select_format(self, compiler, sql, params): # Wrap filters with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END" return sql, params @cached_property def allowed_default(self): return self.lhs.allowed_default and self.rhs.allowed_default class Transform(RegisterLookupMixin, Func): """ RegisterLookupMixin() is first so that get_lookup() and get_transform() first examine self and then check output_field. """ bilateral = False arity = 1 @property def lhs(self): return self.get_source_expressions()[0] def get_bilateral_transforms(self): if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if self.bilateral: bilateral_transforms.append(self.__class__) return bilateral_transforms class BuiltinLookup(Lookup): def process_lhs(self, compiler, connection, lhs=None): lhs_sql, params = super().process_lhs(compiler, connection, lhs) field_internal_type = self.lhs.output_field.get_internal_type() db_type = self.lhs.output_field.db_type(connection=connection) lhs_sql = connection.ops.field_cast_sql(db_type, field_internal_type) % lhs_sql lhs_sql = ( connection.ops.lookup_cast(self.lookup_name, field_internal_type) % lhs_sql ) return lhs_sql, list(params) def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) rhs_sql = self.get_rhs_op(connection, rhs_sql) return "%s %s" % (lhs_sql, rhs_sql), params def get_rhs_op(self, connection, rhs): return connection.operators[self.lookup_name] % rhs class FieldGetDbPrepValueMixin: """ Some lookups require Field.get_db_prep_value() to be called on their inputs. """ get_db_prep_lookup_value_is_iterable = False def get_db_prep_lookup(self, value, connection): # For relational fields, use the 'target_field' attribute of the # output_field. field = getattr(self.lhs.output_field, "target_field", None) get_db_prep_value = ( getattr(field, "get_db_prep_value", None) or self.lhs.output_field.get_db_prep_value ) return ( "%s", [get_db_prep_value(v, connection, prepared=True) for v in value] if self.get_db_prep_lookup_value_is_iterable else [get_db_prep_value(value, connection, prepared=True)], ) class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin): """ Some lookups require Field.get_db_prep_value() to be called on each value in an iterable. """ get_db_prep_lookup_value_is_iterable = True def get_prep_lookup(self): if hasattr(self.rhs, "resolve_expression"): return self.rhs prepared_values = [] for rhs_value in self.rhs: if hasattr(rhs_value, "resolve_expression"): # An expression will be handled by the database but can coexist # alongside real values. pass elif self.prepare_rhs and hasattr(self.lhs.output_field, "get_prep_value"): rhs_value = self.lhs.output_field.get_prep_value(rhs_value) prepared_values.append(rhs_value) return prepared_values def process_rhs(self, compiler, connection): if self.rhs_is_direct_value(): # rhs should be an iterable of values. Use batch_process_rhs() # to prepare/transform those values. return self.batch_process_rhs(compiler, connection) else: return super().process_rhs(compiler, connection) def resolve_expression_parameter(self, compiler, connection, sql, param): params = [param] if hasattr(param, "resolve_expression"): param = param.resolve_expression(compiler.query) if hasattr(param, "as_sql"): sql, params = compiler.compile(param) return sql, params def batch_process_rhs(self, compiler, connection, rhs=None): pre_processed = super().batch_process_rhs(compiler, connection, rhs) # The params list may contain expressions which compile to a # sql/param pair. Zip them to get sql and param pairs that refer to the # same argument and attempt to replace them with the result of # compiling the param step. sql, params = zip( *( self.resolve_expression_parameter(compiler, connection, sql, param) for sql, param in zip(*pre_processed) ) ) params = itertools.chain.from_iterable(params) return sql, tuple(params) class PostgresOperatorLookup(Lookup): """Lookup defined by operators on PostgreSQL.""" postgres_operator = None def as_postgresql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = tuple(lhs_params) + tuple(rhs_params) return "%s %s %s" % (lhs, self.postgres_operator, rhs), params @Field.register_lookup class Exact(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "exact" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): if self.rhs.has_limit_one(): if not self.rhs.has_select_fields: self.rhs.clear_select_clause() self.rhs.add_fields(["pk"]) else: raise ValueError( "The QuerySet value for an exact lookup must be limited to " "one result using slicing." ) return super().get_prep_lookup() def as_sql(self, compiler, connection): # Avoid comparison against direct rhs if lhs is a boolean value. That # turns "boolfield__exact=True" into "WHERE boolean_field" instead of # "WHERE boolean_field = True" when allowed. if ( isinstance(self.rhs, bool) and getattr(self.lhs, "conditional", False) and connection.ops.conditional_expression_supported_in_where_clause( self.lhs ) ): lhs_sql, params = self.process_lhs(compiler, connection) template = "%s" if self.rhs else "NOT %s" return template % lhs_sql, params return super().as_sql(compiler, connection) @Field.register_lookup class IExact(BuiltinLookup): lookup_name = "iexact" prepare_rhs = False def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if params: params[0] = connection.ops.prep_for_iexact_query(params[0]) return rhs, params @Field.register_lookup class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gt" @Field.register_lookup class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gte" @Field.register_lookup class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lt" @Field.register_lookup class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lte" class IntegerFieldOverflow: underflow_exception = EmptyResultSet overflow_exception = EmptyResultSet def process_rhs(self, compiler, connection): rhs = self.rhs if isinstance(rhs, int): field_internal_type = self.lhs.output_field.get_internal_type() min_value, max_value = connection.ops.integer_field_range( field_internal_type ) if min_value is not None and rhs < min_value: raise self.underflow_exception if max_value is not None and rhs > max_value: raise self.overflow_exception return super().process_rhs(compiler, connection) class IntegerFieldFloatRounding: """ Allow floats to work as query values for IntegerField. Without this, the decimal portion of the float would always be discarded. """ def get_prep_lookup(self): if isinstance(self.rhs, float): self.rhs = math.ceil(self.rhs) return super().get_prep_lookup() @IntegerField.register_lookup class IntegerFieldExact(IntegerFieldOverflow, Exact): pass @IntegerField.register_lookup class IntegerGreaterThan(IntegerFieldOverflow, GreaterThan): underflow_exception = FullResultSet @IntegerField.register_lookup class IntegerGreaterThanOrEqual( IntegerFieldOverflow, IntegerFieldFloatRounding, GreaterThanOrEqual ): underflow_exception = FullResultSet @IntegerField.register_lookup class IntegerLessThan(IntegerFieldOverflow, IntegerFieldFloatRounding, LessThan): overflow_exception = FullResultSet @IntegerField.register_lookup class IntegerLessThanOrEqual(IntegerFieldOverflow, LessThanOrEqual): overflow_exception = FullResultSet @Field.register_lookup class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "in" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): self.rhs.clear_ordering(clear_default=True) if not self.rhs.has_select_fields: self.rhs.clear_select_clause() self.rhs.add_fields(["pk"]) return super().get_prep_lookup() def process_rhs(self, compiler, connection): db_rhs = getattr(self.rhs, "_db", None) if db_rhs is not None and db_rhs != connection.alias: raise ValueError( "Subqueries aren't allowed across different databases. Force " "the inner query to be evaluated using `list(inner_query)`." ) if self.rhs_is_direct_value(): # Remove None from the list as NULL is never equal to anything. try: rhs = OrderedSet(self.rhs) rhs.discard(None) except TypeError: # Unhashable items in self.rhs rhs = [r for r in self.rhs if r is not None] if not rhs: raise EmptyResultSet # rhs should be an iterable; use batch_process_rhs() to # prepare/transform those values. sqls, sqls_params = self.batch_process_rhs(compiler, connection, rhs) placeholder = "(" + ", ".join(sqls) + ")" return (placeholder, sqls_params) return super().process_rhs(compiler, connection) def get_rhs_op(self, connection, rhs): return "IN %s" % rhs def as_sql(self, compiler, connection): max_in_list_size = connection.ops.max_in_list_size() if ( self.rhs_is_direct_value() and max_in_list_size and len(self.rhs) > max_in_list_size ): return self.split_parameter_list_as_sql(compiler, connection) return super().as_sql(compiler, connection) def split_parameter_list_as_sql(self, compiler, connection): # This is a special case for databases which limit the number of # elements which can appear in an 'IN' clause. max_in_list_size = connection.ops.max_in_list_size() lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.batch_process_rhs(compiler, connection) in_clause_elements = ["("] params = [] for offset in range(0, len(rhs_params), max_in_list_size): if offset > 0: in_clause_elements.append(" OR ") in_clause_elements.append("%s IN (" % lhs) params.extend(lhs_params) sqls = rhs[offset : offset + max_in_list_size] sqls_params = rhs_params[offset : offset + max_in_list_size] param_group = ", ".join(sqls) in_clause_elements.append(param_group) in_clause_elements.append(")") params.extend(sqls_params) in_clause_elements.append(")") return "".join(in_clause_elements), params class PatternLookup(BuiltinLookup): param_pattern = "%%%s%%" prepare_rhs = False def get_rhs_op(self, connection, rhs): # Assume we are in startswith. We need to produce SQL like: # col LIKE %s, ['thevalue%'] # For python values we can (and should) do that directly in Python, # but if the value is for example reference to other column, then # we need to add the % pattern match to the lookup by something like # col LIKE othercol || '%%' # So, for Python values we don't need any special pattern, but for # SQL reference values or SQL transformations we need the correct # pattern added. if hasattr(self.rhs, "as_sql") or self.bilateral_transforms: pattern = connection.pattern_ops[self.lookup_name].format( connection.pattern_esc ) return pattern.format(rhs) else: return super().get_rhs_op(connection, rhs) def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if self.rhs_is_direct_value() and params and not self.bilateral_transforms: params[0] = self.param_pattern % connection.ops.prep_for_like_query( params[0] ) return rhs, params @Field.register_lookup class Contains(PatternLookup): lookup_name = "contains" @Field.register_lookup class IContains(Contains): lookup_name = "icontains" @Field.register_lookup class StartsWith(PatternLookup): lookup_name = "startswith" param_pattern = "%s%%" @Field.register_lookup class IStartsWith(StartsWith): lookup_name = "istartswith" @Field.register_lookup class EndsWith(PatternLookup): lookup_name = "endswith" param_pattern = "%%%s" @Field.register_lookup class IEndsWith(EndsWith): lookup_name = "iendswith" @Field.register_lookup class Range(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "range" def get_rhs_op(self, connection, rhs): return "BETWEEN %s AND %s" % (rhs[0], rhs[1]) @Field.register_lookup class IsNull(BuiltinLookup): lookup_name = "isnull" prepare_rhs = False def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise ValueError( "The QuerySet value for an isnull lookup must be True or False." ) sql, params = self.process_lhs(compiler, connection) if self.rhs: return "%s IS NULL" % sql, params else: return "%s IS NOT NULL" % sql, params @Field.register_lookup class Regex(BuiltinLookup): lookup_name = "regex" prepare_rhs = False def as_sql(self, compiler, connection): if self.lookup_name in connection.operators: return super().as_sql(compiler, connection) else: lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) sql_template = connection.ops.regex_lookup(self.lookup_name) return sql_template % (lhs, rhs), lhs_params + rhs_params @Field.register_lookup class IRegex(Regex): lookup_name = "iregex" class YearLookup(Lookup): def year_lookup_bounds(self, connection, year): from django.db.models.functions import ExtractIsoYear iso_year = isinstance(self.lhs, ExtractIsoYear) output_field = self.lhs.lhs.output_field if isinstance(output_field, DateTimeField): bounds = connection.ops.year_lookup_bounds_for_datetime_field( year, iso_year=iso_year, ) else: bounds = connection.ops.year_lookup_bounds_for_date_field( year, iso_year=iso_year, ) return bounds def as_sql(self, compiler, connection): # Avoid the extract operation if the rhs is a direct value to allow # indexes to be used. if self.rhs_is_direct_value(): # Skip the extract part by directly using the originating field, # that is self.lhs.lhs. lhs_sql, params = self.process_lhs(compiler, connection, self.lhs.lhs) rhs_sql, _ = self.process_rhs(compiler, connection) rhs_sql = self.get_direct_rhs_sql(connection, rhs_sql) start, finish = self.year_lookup_bounds(connection, self.rhs) params.extend(self.get_bound_params(start, finish)) return "%s %s" % (lhs_sql, rhs_sql), params return super().as_sql(compiler, connection) def get_direct_rhs_sql(self, connection, rhs): return connection.operators[self.lookup_name] % rhs def get_bound_params(self, start, finish): raise NotImplementedError( "subclasses of YearLookup must provide a get_bound_params() method" ) class YearExact(YearLookup, Exact): def get_direct_rhs_sql(self, connection, rhs): return "BETWEEN %s AND %s" def get_bound_params(self, start, finish): return (start, finish) class YearGt(YearLookup, GreaterThan): def get_bound_params(self, start, finish): return (finish,) class YearGte(YearLookup, GreaterThanOrEqual): def get_bound_params(self, start, finish): return (start,) class YearLt(YearLookup, LessThan): def get_bound_params(self, start, finish): return (start,) class YearLte(YearLookup, LessThanOrEqual): def get_bound_params(self, start, finish): return (finish,) class UUIDTextMixin: """ Strip hyphens from a value when filtering a UUIDField on backends without a native datatype for UUID. """ def process_rhs(self, qn, connection): if not connection.features.has_native_uuid_field: from django.db.models.functions import Replace if self.rhs_is_direct_value(): self.rhs = Value(self.rhs) self.rhs = Replace( self.rhs, Value("-"), Value(""), output_field=CharField() ) rhs, params = super().process_rhs(qn, connection) return rhs, params @UUIDField.register_lookup class UUIDIExact(UUIDTextMixin, IExact): pass @UUIDField.register_lookup class UUIDContains(UUIDTextMixin, Contains): pass @UUIDField.register_lookup class UUIDIContains(UUIDTextMixin, IContains): pass @UUIDField.register_lookup class UUIDStartsWith(UUIDTextMixin, StartsWith): pass @UUIDField.register_lookup class UUIDIStartsWith(UUIDTextMixin, IStartsWith): pass @UUIDField.register_lookup class UUIDEndsWith(UUIDTextMixin, EndsWith): pass @UUIDField.register_lookup class UUIDIEndsWith(UUIDTextMixin, IEndsWith): pass
75eb44dcca0cae3a56cef7f2997933e6dc193e7a094745609ae4c78d12ec586b
from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.state import ModelState from django.db.migrations.utils import field_references, resolve_relation from django.db.models.options import normalize_together from django.utils.functional import cached_property from .fields import AddField, AlterField, FieldOperation, RemoveField, RenameField def _check_for_duplicates(arg_name, objs): used_vals = set() for val in objs: if val in used_vals: raise ValueError( "Found duplicate value %s in CreateModel %s argument." % (val, arg_name) ) used_vals.add(val) class ModelOperation(Operation): def __init__(self, name): self.name = name @cached_property def name_lower(self): return self.name.lower() def references_model(self, name, app_label): return name.lower() == self.name_lower def reduce(self, operation, app_label): return super().reduce(operation, app_label) or self.can_reduce_through( operation, app_label ) def can_reduce_through(self, operation, app_label): return not operation.references_model(self.name, app_label) class CreateModel(ModelOperation): """Create a model's table.""" serialization_expand_args = ["fields", "options", "managers"] def __init__(self, name, fields, options=None, bases=None, managers=None): self.fields = fields self.options = options 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 isinstance(base, str) else base for base in self.bases ), ) _check_for_duplicates("managers", (name for name, _ in self.managers)) def deconstruct(self): 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 if self.managers and self.managers != [("objects", models.Manager())]: kwargs["managers"] = self.managers return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.add_model( ModelState( app_label, self.name, list(self.fields), dict(self.options), tuple(self.bases), list(self.managers), ) ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def describe(self): return "Create %smodel %s" % ( "proxy " if self.options.get("proxy", False) else "", self.name, ) @property def migration_name_fragment(self): return self.name_lower def references_model(self, name, app_label): name_lower = name.lower() if name_lower == self.name_lower: return True # Check we didn't inherit from the model reference_model_tuple = (app_label, name_lower) for base in self.bases: if ( base is not models.Model and isinstance(base, (models.base.ModelBase, str)) and resolve_relation(base, app_label) == reference_model_tuple ): return True # Check we have no FKs/M2Ms with it for _name, field in self.fields: if field_references( (app_label, self.name_lower), field, reference_model_tuple ): return True return False def reduce(self, operation, app_label): if ( isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False) ): return [] elif ( isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower ): return [ CreateModel( operation.new_name, fields=self.fields, options=self.options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower ): options = {**self.options, **operation.options} for key in operation.ALTER_OPTION_KEYS: if key not in operation.options: options.pop(key, None) return [ CreateModel( self.name, fields=self.fields, options=options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelManagers) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options=self.options, bases=self.bases, managers=operation.managers, ), ] elif ( isinstance(operation, AlterTogetherOptionOperation) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, **{operation.option_name: operation.option_value}, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterOrderWithRespectTo) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "order_with_respect_to": operation.order_with_respect_to, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower ): if isinstance(operation, AddField): return [ CreateModel( self.name, fields=self.fields + [(operation.name, operation.field)], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterField): return [ CreateModel( self.name, fields=[ (n, operation.field if n == operation.name else v) for n, v in self.fields ], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.pop(option_name, None) if option: option = set( filter( bool, ( tuple( f for f in fields if f != operation.name_lower ) for fields in option ), ) ) if option: options[option_name] = option order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.name_lower: del options["order_with_respect_to"] return [ CreateModel( self.name, fields=[ (n, v) for n, v in self.fields if n.lower() != operation.name_lower ], options=options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.get(option_name) if option: options[option_name] = { tuple( operation.new_name if f == operation.old_name else f for f in fields ) for fields in option } order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.old_name: options["order_with_respect_to"] = operation.new_name return [ CreateModel( self.name, fields=[ (operation.new_name if n == operation.old_name else n, v) for n, v in self.fields ], options=options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, IndexOperation) and self.name_lower == operation.model_name_lower ): if isinstance(operation, AddIndex): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "indexes": [ *self.options.get("indexes", []), operation.index, ], }, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveIndex): options_indexes = [ index for index in self.options.get("indexes", []) if index.name != operation.name ] return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "indexes": options_indexes, }, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameIndex) and operation.old_fields: options_index_together = { fields for fields in self.options.get("index_together", []) if fields != operation.old_fields } if options_index_together: self.options["index_together"] = options_index_together else: self.options.pop("index_together", None) return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "indexes": [ *self.options.get("indexes", []), models.Index( fields=operation.old_fields, name=operation.new_name ), ], }, bases=self.bases, managers=self.managers, ), ] return super().reduce(operation, app_label) class DeleteModel(ModelOperation): """Drop a model's table.""" def deconstruct(self): kwargs = { "name": self.name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.remove_model(app_label, self.name_lower) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def references_model(self, name, app_label): # The deleted model could be referencing the specified model through # related fields. return True def describe(self): return "Delete model %s" % self.name @property def migration_name_fragment(self): return "delete_%s" % self.name_lower class RenameModel(ModelOperation): """Rename a model.""" def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name super().__init__(old_name) @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "old_name": self.old_name, "new_name": self.new_name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.rename_model(app_label, self.old_name, self.new_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) # Move the main table schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model: model = new_model related_key = (app_label, self.new_name_lower) else: model = related_object.related_model related_key = ( related_object.related_model._meta.app_label, related_object.related_model._meta.model_name, ) to_field = to_state.apps.get_model(*related_key)._meta.get_field( related_object.field.name ) schema_editor.alter_field( model, related_object.field, to_field, ) # Rename M2M fields whose name is based on this model's name. fields = zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ) for old_field, new_field in fields: # Skip self-referential fields as these are renamed above. if ( new_field.model == new_field.related_model or not new_field.remote_field.through._meta.auto_created ): continue # Rename columns and the M2M table. schema_editor._alter_many_to_many( new_model, old_field, new_field, strict=False, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def references_model(self, name, app_label): return ( name.lower() == self.old_name_lower or name.lower() == self.new_name_lower ) def describe(self): return "Rename model %s to %s" % (self.old_name, self.new_name) @property def migration_name_fragment(self): return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) def reduce(self, operation, app_label): if ( isinstance(operation, RenameModel) and self.new_name_lower == operation.old_name_lower ): return [ RenameModel( self.old_name, operation.new_name, ), ] # Skip `ModelOperation.reduce` as we want to run `references_model` # against self.new_name. return super(ModelOperation, self).reduce( operation, app_label ) or not operation.references_model(self.new_name, app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, app_label): if ( isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower ): return [operation] return super().reduce(operation, app_label) class AlterModelTable(ModelOptionOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table": self.table, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options(app_label, self.name_lower, {"db_table": self.table}) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Rename M2M fields whose name is based on this model's db_table for old_field, new_field in zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ): if new_field.remote_field.through._meta.auto_created: schema_editor.alter_db_table( new_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Rename table for %s to %s" % ( self.name, self.table if self.table is not None else "(default)", ) @property def migration_name_fragment(self): return "alter_%s_table" % self.name_lower class AlterModelTableComment(ModelOptionOperation): def __init__(self, name, table_comment): self.table_comment = table_comment super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table_comment": self.table_comment, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {"db_table_comment": self.table_comment} ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table_comment( new_model, old_model._meta.db_table_comment, new_model._meta.db_table_comment, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return f"Alter {self.name} table comment" @property def migration_name_fragment(self): return f"alter_{self.name_lower}_table_comment" class AlterTogetherOptionOperation(ModelOptionOperation): option_name = None def __init__(self, name, option_value): if option_value: option_value = set(normalize_together(option_value)) setattr(self, self.option_name, option_value) super().__init__(name) @cached_property def option_value(self): return getattr(self, self.option_name) def deconstruct(self): kwargs = { "name": self.name, self.option_name: self.option_value, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.option_value}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) alter_together = getattr(schema_editor, "alter_%s" % self.option_name) alter_together( new_model, getattr(old_model._meta, self.option_name, set()), getattr(new_model._meta, self.option_name, set()), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( not self.option_value or any((name in fields) for fields in self.option_value) ) def describe(self): return "Alter %s for %s (%s constraint(s))" % ( self.option_name, self.name, len(self.option_value or ""), ) @property def migration_name_fragment(self): return "alter_%s_%s" % (self.name_lower, self.option_name) def can_reduce_through(self, operation, app_label): return super().can_reduce_through(operation, app_label) or ( isinstance(operation, AlterTogetherOptionOperation) and type(operation) is not type(self) ) class AlterUniqueTogether(AlterTogetherOptionOperation): """ Change the value of unique_together to the target one. Input value of unique_together must be a set of tuples. """ option_name = "unique_together" def __init__(self, name, unique_together): super().__init__(name, unique_together) class AlterIndexTogether(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" def __init__(self, name, index_together): super().__init__(name, index_together) class AlterOrderWithRespectTo(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = "order_with_respect_to" def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "order_with_respect_to": self.order_with_respect_to, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.order_with_respect_to}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.name) # Remove a field if we need to if ( from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to ): schema_editor.remove_field( from_model, from_model._meta.get_field("_order") ) # Add a field if we need to (altering the column is untouched as # it's likely a rename) elif ( to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to ): field = to_model._meta.get_field("_order") if not field.has_default(): field.default = 0 schema_editor.add_field( from_model, field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( self.order_with_respect_to is None or name == self.order_with_respect_to ) def describe(self): return "Set order_with_respect_to on %s to %s" % ( self.name, self.order_with_respect_to, ) @property def migration_name_fragment(self): return "alter_%s_order_with_respect_to" % self.name_lower class AlterModelOptions(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "default_related_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "options": self.options, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, self.options, self.ALTER_OPTION_KEYS, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_options" % self.name_lower class AlterModelManagers(ModelOptionOperation): """Alter the model's managers.""" serialization_expand_args = ["managers"] def __init__(self, name, managers): self.managers = managers super().__init__(name) def deconstruct(self): return (self.__class__.__qualname__, [self.name, self.managers], {}) def state_forwards(self, app_label, state): state.alter_model_managers(app_label, self.name_lower, self.managers) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change managers on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_managers" % self.name_lower class IndexOperation(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower() class AddIndex(IndexOperation): """Add an index on a model.""" def __init__(self, model_name, index): self.model_name = model_name if not index.name: raise ValueError( "Indexes passed to AddIndex operations require a name " "argument. %r doesn't have one." % index ) self.index = index def state_forwards(self, app_label, state): state.add_index(app_label, self.model_name_lower, self.index) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index) def deconstruct(self): kwargs = { "model_name": self.model_name, "index": self.index, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): if self.index.expressions: return "Create index %s on %s on model %s" % ( self.index.name, ", ".join([str(expression) for expression in self.index.expressions]), self.model_name, ) return "Create index %s on field(s) %s of model %s" % ( self.index.name, ", ".join(self.index.fields), self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.index.name.lower()) def reduce(self, operation, app_label): if isinstance(operation, RemoveIndex) and self.index.name == operation.name: return [] if isinstance(operation, RenameIndex) and self.index.name == operation.old_name: self.index.name = operation.new_name return [AddIndex(model_name=self.model_name, index=self.index)] return super().reduce(operation, app_label) class RemoveIndex(IndexOperation): """Remove an index from a model.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_index(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index) def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return "Remove index %s from %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower()) class RenameIndex(IndexOperation): """Rename an index.""" def __init__(self, model_name, new_name, old_name=None, old_fields=None): if not old_name and not old_fields: raise ValueError( "RenameIndex requires one of old_name and old_fields arguments to be " "set." ) if old_name and old_fields: raise ValueError( "RenameIndex.old_name and old_fields are mutually exclusive." ) self.model_name = model_name self.new_name = new_name self.old_name = old_name self.old_fields = old_fields @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "model_name": self.model_name, "new_name": self.new_name, } if self.old_name: kwargs["old_name"] = self.old_name if self.old_fields: kwargs["old_fields"] = self.old_fields return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): if self.old_fields: state.add_index( app_label, self.model_name_lower, models.Index(fields=self.old_fields, name=self.new_name), ) state.remove_model_options( app_label, self.model_name_lower, AlterIndexTogether.option_name, self.old_fields, ) else: state.rename_index( app_label, self.model_name_lower, self.old_name, self.new_name ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if not self.allow_migrate_model(schema_editor.connection.alias, model): return if self.old_fields: from_model = from_state.apps.get_model(app_label, self.model_name) columns = [ from_model._meta.get_field(field).column for field in self.old_fields ] matching_index_name = schema_editor._constraint_names( from_model, column_names=columns, index=True ) if len(matching_index_name) != 1: raise ValueError( "Found wrong number (%s) of indexes for %s(%s)." % ( len(matching_index_name), from_model._meta.db_table, ", ".join(columns), ) ) old_index = models.Index( fields=self.old_fields, name=matching_index_name[0], ) else: from_model_state = from_state.models[app_label, self.model_name_lower] old_index = from_model_state.get_index_by_name(self.old_name) # Don't alter when the index name is not changed. if old_index.name == self.new_name: return to_model_state = to_state.models[app_label, self.model_name_lower] new_index = to_model_state.get_index_by_name(self.new_name) schema_editor.rename_index(model, old_index, new_index) def database_backwards(self, app_label, schema_editor, from_state, to_state): if self.old_fields: # Backward operation with unnamed index is a no-op. return self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def describe(self): if self.old_name: return ( f"Rename index {self.old_name} on {self.model_name} to {self.new_name}" ) return ( f"Rename unnamed index for {self.old_fields} on {self.model_name} to " f"{self.new_name}" ) @property def migration_name_fragment(self): if self.old_name: return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) return "rename_%s_%s_%s" % ( self.model_name_lower, "_".join(self.old_fields), self.new_name_lower, ) def reduce(self, operation, app_label): if ( isinstance(operation, RenameIndex) and self.model_name_lower == operation.model_name_lower and operation.old_name and self.new_name_lower == operation.old_name_lower ): return [ RenameIndex( self.model_name, new_name=operation.new_name, old_name=self.old_name, old_fields=self.old_fields, ) ] return super().reduce(operation, app_label) class AddConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, constraint): self.model_name = model_name self.constraint = constraint def state_forwards(self, app_label, state): state.add_constraint(app_label, self.model_name_lower, self.constraint) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_constraint(model, self.constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_constraint(model, self.constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "constraint": self.constraint, }, ) def describe(self): return "Create constraint %s on model %s" % ( self.constraint.name, self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.constraint.name.lower()) def reduce(self, operation, app_label): if ( isinstance(operation, RemoveConstraint) and self.model_name_lower == operation.model_name_lower and self.constraint.name == operation.name ): return [] return super().reduce(operation, app_label) class RemoveConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_constraint(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] constraint = from_model_state.get_constraint_by_name(self.name) schema_editor.remove_constraint(model, constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] constraint = to_model_state.get_constraint_by_name(self.name) schema_editor.add_constraint(model, constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "name": self.name, }, ) def describe(self): return "Remove constraint %s from model %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower())
12e95eddfe41424b05d291cf34ca4199be963d7c44fb1f28779cfe2fd7fff9bc
import collections.abc import copy import datetime import decimal import operator import uuid import warnings from base64 import b64decode, b64encode from functools import partialmethod, total_ordering from django import forms from django.apps import apps from django.conf import settings from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP from django.db.models.enums import ChoicesMeta from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property from django.utils.ipv6 import clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ __all__ = [ "AutoField", "BLANK_CHOICE_DASH", "BigAutoField", "BigIntegerField", "BinaryField", "BooleanField", "CharField", "CommaSeparatedIntegerField", "DateField", "DateTimeField", "DecimalField", "DurationField", "EmailField", "Empty", "Field", "FilePathField", "FloatField", "GenericIPAddressField", "IPAddressField", "IntegerField", "NOT_PROVIDED", "NullBooleanField", "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", "SlugField", "SmallAutoField", "SmallIntegerField", "TextField", "TimeField", "URLField", "UUIDField", ] class Empty: pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # 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) # These 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_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."), "blank": _("This field cannot be blank."), "unique": _("%(model_name)s with this %(field_label)s already exists."), "unique_for_date": _( # Translators: The 'lookup_type' is one of 'date', 'year' or # 'month'. Eg: "Title must be unique for pub_date year" "%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s." ), } system_check_deprecated_details = None system_check_removed_details = None # Attributes that don't affect a column definition. # These attributes are ignored when altering the field. non_db_attrs = ( "blank", "choices", "db_column", "editable", "error_messages", "help_text", "limit_choices_to", # Database-level options are not supported, see #21961. "on_delete", "related_name", "related_query_name", "validators", "verbose_name", ) # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None descriptor_class = DeferredAttribute # Generic field type description, usually overridden by subclasses def _description(self): return _("Field of type: %(field_type)s") % { "field_type": self.__class__.__name__ } description = property(_description) def __init__( self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text="", db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None, db_comment=None, db_default=NOT_PROVIDED, ): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.remote_field = rel self.is_relation = self.remote_field is not None self.default = default if db_default is not NOT_PROVIDED and not hasattr( db_default, "resolve_expression" ): from django.db.models.expressions import Value db_default = Value(db_default) self.db_default = db_default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year if isinstance(choices, ChoicesMeta): choices = choices.choices if isinstance(choices, collections.abc.Iterator): choices = list(choices) self.choices = choices self.help_text = help_text self.db_index = db_index self.db_column = db_column self.db_comment = db_comment self._db_tablespace = db_tablespace self.auto_created = auto_created # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = list(validators) # Store for deconstruction later self._error_messages = error_messages # Store for deconstruction later def __str__(self): """ Return "app_label.model_label.field_name" for fields attached to models. """ if not hasattr(self, "model"): return super().__str__() model = self.model return "%s.%s" % (model._meta.label, self.name) def __repr__(self): """Display the module, class, and name of the field.""" path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) name = getattr(self, "name", None) if name is not None: return "<%s: %s>" % (path, name) return "<%s>" % path def check(self, **kwargs): return [ *self._check_field_name(), *self._check_choices(), *self._check_db_default(**kwargs), *self._check_db_index(), *self._check_db_comment(**kwargs), *self._check_null_allowed_for_primary_keys(), *self._check_backend_specific_checks(**kwargs), *self._check_validators(), *self._check_deprecation_details(), ] def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] elif LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % LOOKUP_SEP, obj=self, id="fields.E002", ) ] elif self.name == "pk": return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", obj=self, id="fields.E003", ) ] else: return [] @classmethod def _choices_is_value(cls, value): return isinstance(value, (str, Promise)) or not is_iterable(value) def _check_choices(self): if not self.choices: return [] if not is_iterable(self.choices) or isinstance(self.choices, str): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=self, id="fields.E004", ) ] choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: group_name, group_choices = choices_group except (TypeError, ValueError): # Containing non-pairs break try: if not all( self._choices_is_value(value) and self._choices_is_value(human_name) for value, human_name in group_choices ): break if self.max_length is not None and group_choices: choice_max_length = max( [ choice_max_length, *( len(value) for value, _ in group_choices if isinstance(value, str) ), ] ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not self._choices_is_value(value) or not self._choices_is_value( human_name ): break if self.max_length is not None and isinstance(value, str): choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: if self.max_length is not None and choice_max_length > self.max_length: return [ checks.Error( "'max_length' is too small to fit the longest value " "in 'choices' (%d characters)." % choice_max_length, obj=self, id="fields.E009", ), ] return [] return [ checks.Error( "'choices' must be an iterable containing " "(actual value, human readable name) tuples.", obj=self, id="fields.E005", ) ] def _check_db_default(self, databases=None, **kwargs): from django.db.models.expressions import Value if ( self.db_default is NOT_PROVIDED or isinstance(self.db_default, Value) or databases is None ): return [] errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not getattr(self.db_default, "allowed_default", False) and ( connection.features.supports_expression_defaults ): msg = f"{self.db_default} cannot be used in db_default." errors.append(checks.Error(msg, obj=self, id="fields.E012")) if not ( connection.features.supports_expression_defaults or "supports_expression_defaults" in self.model._meta.required_db_features ): msg = ( f"{connection.display_name} does not support default database " "values with expressions (db_default)." ) errors.append(checks.Error(msg, obj=self, id="fields.E011")) return errors def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", obj=self, id="fields.E006", ) ] else: return [] def _check_db_comment(self, databases=None, **kwargs): if not self.db_comment or not databases: return [] errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( connection.features.supports_comments or "supports_comments" in self.model._meta.required_db_features ): errors.append( checks.Warning( f"{connection.display_name} does not support comments on " f"columns (db_comment).", obj=self, id="fields.W163", ) ) return errors def _check_null_allowed_for_primary_keys(self): if ( self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls ): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( "Primary keys must not have null=True.", hint=( "Set null=False on the field, or " "remove primary_key=True argument." ), obj=self, id="fields.E007", ) ] else: return [] def _check_backend_specific_checks(self, databases=None, **kwargs): if databases is None: return [] errors = [] for alias in databases: if router.allow_migrate_model(alias, self.model): errors.extend(connections[alias].validation.check_field(self, **kwargs)) return errors def _check_validators(self): errors = [] for i, validator in enumerate(self.validators): if not callable(validator): errors.append( checks.Error( "All 'validators' must be callable.", hint=( "validators[{i}] ({repr}) isn't a function or " "instance of a validator class.".format( i=i, repr=repr(validator), ) ), obj=self, id="fields.E008", ) ) return errors def _check_deprecation_details(self): if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( "msg", "%s has been removed except for support in historical " "migrations." % self.__class__.__name__, ), hint=self.system_check_removed_details.get("hint"), obj=self, id=self.system_check_removed_details.get("id", "fields.EXXX"), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( "msg", "%s has been deprecated." % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get("hint"), obj=self, id=self.system_check_deprecated_details.get("id", "fields.WXXX"), ) ] return [] def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col from django.db.models.expressions import Col return Col(alias, self, output_field) @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Return enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class() has been run. * The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better. * A list of positional arguments. * A dict of keyword arguments. Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "db_default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": None, "help_text": "", "db_column": None, "db_comment": None, "db_tablespace": None, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", "db_tablespace": "_db_tablespace", } equals_comparison = {"choices", "validators"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.abc.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") elif path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") elif path.startswith("django.db.models.fields.json"): path = path.replace("django.db.models.fields.json", "django.db.models") elif path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") elif path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return (self.name, path, [], keywords) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter and getattr( self, "model", None ) == getattr(other, "model", None) return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. # Order by creation_counter first for backward compatibility. if isinstance(other, Field): if ( self.creation_counter != other.creation_counter or not hasattr(self, "model") and not hasattr(other, "model") ): return self.creation_counter < other.creation_counter elif hasattr(self, "model") != hasattr(other, "model"): return not hasattr(self, "model") # Order no-model fields first else: # creation_counter's are equal, compare only models. return (self.model._meta.app_label, self.model._meta.model_name) < ( other.model._meta.app_label, other.model._meta.model_name, ) return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.remote_field: obj.remote_field = copy.copy(self.remote_field) if hasattr(self.remote_field, "field") and self.remote_field.field is self: obj.remote_field.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back. """ if not hasattr(self, "model"): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. state = self.__dict__.copy() # The _get_default cached_property can't be pickled due to lambda # usage. state.pop("_get_default", None) return _empty, (self.__class__,), state return _load_field, ( self.model._meta.app_label, self.model._meta.object_name, self.name, ) def get_pk_value_on_save(self, instance): """ Hook to generate new PK values on save. This method is called when saving instances with no primary key value set. If this method returns something else than None, then the returned value is used when saving the new instance. """ if self.default: return self.get_default() return None def to_python(self, value): """ Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this. """ return value @cached_property def error_messages(self): messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(self._error_messages or {}) return messages @cached_property def validators(self): """ Some validators can't be created at field initialization time. This method provides a way to delay their creation until required. """ return [*self.default_validators, *self._validators] def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self.choices is not None and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages["null"], code="null") if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type_parameters(self, connection): return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") def db_check(self, connection): """ Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field. """ data = self.db_type_parameters(connection) try: return ( connection.data_type_check_constraints[self.get_internal_type()] % data ) except KeyError: return None def db_type(self, connection): """ Return the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = self.db_type_parameters(connection) try: column_type = connection.data_types[self.get_internal_type()] except KeyError: return None else: # column_type is either a single-parameter function or a string. if callable(column_type): return column_type(data) return column_type % data def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type. """ return self.db_type(connection) def cast_db_type(self, connection): """Return the data type to use in the Cast() function.""" db_type = connection.ops.cast_data_types.get(self.get_internal_type()) if db_type: return db_type % self.db_type_parameters(connection) return self.db_type(connection) def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ type_string = self.db_type(connection) check_string = self.db_check(connection) return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, "from_db_value"): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key @property def db_tablespace(self): return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE @property def db_returning(self): """Private API intended only to be used by Django itself.""" return ( self.db_default is not NOT_PROVIDED and connection.features.can_return_columns_from_insert ) def set_attributes_from_name(self, name): self.name = self.name or name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace("_", " ") def contribute_to_class(self, cls, name, private_only=False): """ Register the field with the model class it belongs to. If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model. """ self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self, private=private_only) if self.column: setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: # Don't override a get_FOO_display() method defined explicitly on # this class, but don't check methods derived from inheritance, to # allow overriding inherited choices. For more complex inheritance # structures users should override contribute_to_class(). if "get_%s_display" % self.name not in cls.__dict__: setattr( cls, "get_%s_display" % self.name, partialmethod(cls._get_FIELD_display, field=self), ) def get_filter_kwargs_for_object(self, obj): """ Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has. """ return {self.name: getattr(obj, self.attname)} def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """Return field's value just before saving.""" value = getattr(model_instance, self.attname) if not connection.features.supports_default_keyword_in_insert: from django.db.models.expressions import DatabaseDefault if isinstance(value, DatabaseDefault): return self.db_default return value def get_prep_value(self, value): """Perform preliminary non-db specific value checks and conversions.""" if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """ Return field's value prepared for interacting with the database backend. Used by the default implementations of get_db_prep_save(). """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """Return field's value prepared for saving into a database.""" if hasattr(value, "as_sql"): return value return self.get_db_prep_value(value, connection=connection, prepared=False) def has_default(self): """Return a boolean of whether this field has a default value.""" return self.default is not NOT_PROVIDED def get_default(self): """Return the default value for this field.""" return self._get_default() @cached_property def _get_default(self): if self.has_default(): if callable(self.default): return self.default return lambda: self.default if self.db_default is not NOT_PROVIDED: from django.db.models.expressions import DatabaseDefault return DatabaseDefault if ( not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls ): return return_None return str # return empty string def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. """ if self.choices is not None: choices = list(self.choices) if include_blank: blank_defined = any( choice in ("", None) for choice, _ in self.flatchoices ) if not blank_defined: choices = blank_choice + choices return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() choice_func = operator.attrgetter( self.remote_field.get_related_field().attname if hasattr(self.remote_field, "get_related_field") else "pk" ) qs = rel_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [ (choice_func(x), str(x)) for x in qs ] def value_to_string(self, obj): """ Return a string value of this field from the passed obj. This is used by the serialization framework. """ return str(self.value_from_object(obj)) def _get_flatchoices(self): """Flattened version of choices tuple.""" if self.choices is None: return [] flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = { "required": not self.blank, "label": capfirst(self.verbose_name), "help_text": self.help_text, } if self.has_default(): if callable(self.default): defaults["initial"] = self.default defaults["show_hidden_initial"] = True else: defaults["initial"] = self.get_default() if self.choices is not None: # Fields with choices get special treatment. include_blank = self.blank or not ( self.has_default() or "initial" in kwargs ) defaults["choices"] = self.get_choices(include_blank=include_blank) defaults["coerce"] = self.to_python if self.null: defaults["empty_value"] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ( "coerce", "empty_value", "choices", "required", "widget", "label", "initial", "help_text", "error_messages", "show_hidden_initial", "disabled", ): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """Return the value of this field in the given model instance.""" return getattr(obj, self.attname) class BooleanField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be either True or False."), "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), } description = _("Boolean (Either True or False)") def get_internal_type(self): return "BooleanField" def to_python(self, value): if self.null and value in self.empty_values: return None if value in (True, False): # 1/0 are equal to True/False. bool() converts former to latter. return bool(value) if value in ("t", "True", "1"): return True if value in ("f", "False", "0"): return False raise exceptions.ValidationError( self.error_messages["invalid_nullable" if self.null else "invalid"], code="invalid", params={"value": value}, ) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return self.to_python(value) def formfield(self, **kwargs): if self.choices is not None: include_blank = not (self.has_default() or "initial" in kwargs) defaults = {"choices": self.get_choices(include_blank=include_blank)} else: form_class = forms.NullBooleanField if self.null else forms.BooleanField # In HTML checkboxes, 'required' means "must be checked" which is # different from the choices case ("must select some value"). # required=False allows unchecked checkboxes. defaults = {"form_class": form_class, "required": False} return super().formfield(**{**defaults, **kwargs}) class CharField(Field): def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) @property def description(self): if self.max_length is not None: return _("String (up to %(max_length)s)") else: return _("String (unlimited)") def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), *self._check_max_length_attribute(**kwargs), ] def _check_max_length_attribute(self, **kwargs): if self.max_length is None: if ( connection.features.supports_unlimited_charfield or "supports_unlimited_charfield" in self.model._meta.required_db_features ): return [] return [ checks.Error( "CharFields must define a 'max_length' attribute.", obj=self, id="fields.E120", ) ] elif ( not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0 ): return [ checks.Error( "'max_length' must be a positive integer.", obj=self, id="fields.E121", ) ] else: return [] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_charfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_charfield ): errors.append( checks.Error( "%s does not support a database collation on " "CharFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def cast_db_type(self, connection): if self.max_length is None: return connection.ops.cast_char_field_without_max_length return super().cast_db_type(connection) def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {"max_length": self.max_length} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.timezone.utc) return value def _get_naive_now(): return _to_naive(timezone.now()) class DateTimeCheckMixin: def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_mutually_exclusive_options(), *self._check_fix_default_value(), ] def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [ self.auto_now_add, self.auto_now, self.has_default(), ] enabled_options = [ option not in (None, False) for option in mutually_exclusive_options ].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=self, id="fields.E160", ) ] else: return [] def _check_fix_default_value(self): return [] # Concrete subclasses use this in their implementations of # _check_fix_default_value(). def _check_if_value_fixed(self, value, now=None): """ Check if the given value appears to have been provided as a "fixed" time value, and include a warning in the returned list if it does. The value argument must be a date object or aware/naive datetime object. If now is provided, it must be a naive datetime object. """ if now is None: now = _get_naive_now() offset = datetime.timedelta(seconds=10) lower = now - offset upper = now + offset if isinstance(value, datetime.datetime): value = _to_naive(value) else: assert isinstance(value, datetime.date) lower = lower.date() upper = upper.date() if lower <= value <= upper: return [ checks.Warning( "Fixed default value provided.", hint=( "It seems you set a fixed date / time / datetime " "value as default for this field. This may not be " "what you want. If you want to have the current date " "as default, use `django.utils.timezone.now`" ), obj=self, id="fields.W161", ) ] return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid date format. It must be " "in YYYY-MM-DD format." ), "invalid_date": _( "“%(value)s” value has the correct format (YYYY-MM-DD) " "but it is an invalid date." ), } description = _("Date (without time)") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): value = _to_naive(value).date() elif isinstance(value, datetime.date): pass else: # No explicit date / datetime value -- no checks necessary return [] # At this point, value is a date object. return self._check_if_value_fixed(value) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs["auto_now"] = True if self.auto_now_add: kwargs["auto_now_add"] = True if self.auto_now or self.auto_now_add: del kwargs["editable"] del kwargs["blank"] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, "get_next_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=True ), ) setattr( cls, "get_previous_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=False ), ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateField, **kwargs, } ) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." ), "invalid_date": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date." ), "invalid_datetime": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time." ), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, (datetime.datetime, datetime.date)): return self._check_if_value_fixed(value) # No explicit date / datetime value -- no checks necessary. return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn( "DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_datetime"], code="invalid_datetime", params={"value": value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = "%s.%s" % (self.model.__name__, self.name) except AttributeError: name = "(unbound)" warnings.warn( "DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datetimefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateTimeField, **kwargs, } ) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a decimal number."), } description = _("Decimal number") def __init__( self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super().check(**kwargs) digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ] if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", obj=self, id="fields.E130", ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", obj=self, id="fields.E131", ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", obj=self, id="fields.E132", ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", obj=self, id="fields.E133", ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=self, id="fields.E134", ) ] return [] @cached_property def validators(self): return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] @cached_property def context(self): return decimal.Context(prec=self.max_digits) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs["max_digits"] = self.max_digits if self.decimal_places is not None: kwargs["decimal_places"] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value try: if isinstance(value, float): decimal_value = self.context.create_decimal_from_float(value) else: decimal_value = decimal.Decimal(value) except (decimal.InvalidOperation, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if not decimal_value.is_finite(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return decimal_value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) if hasattr(value, "as_sql"): return value return connection.ops.adapt_decimalfield_value( value, self.max_digits, self.decimal_places ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): return super().formfield( **{ "max_digits": self.max_digits, "decimal_places": self.decimal_places, "form_class": forms.DecimalField, **kwargs, } ) class DurationField(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "[DD] [[HH:]MM:]ss[.uuuuuu] format." ) } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return duration_microseconds(value) def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else duration_string(val) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DurationField, **kwargs, } ) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault("max_length", 254) super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield( **{ "form_class": forms.EmailField, **kwargs, } ) class FilePathField(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_allowing_files_or_folders(**kwargs), ] def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' " "set to True.", obj=self, id="fields.E140", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.path != "": kwargs["path"] = self.path if self.match is not None: kwargs["match"] = self.match if self.recursive is not False: kwargs["recursive"] = self.recursive if self.allow_files is not True: kwargs["allow_files"] = self.allow_files if self.allow_folders is not False: kwargs["allow_folders"] = self.allow_folders if kwargs.get("max_length") == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def formfield(self, **kwargs): return super().formfield( **{ "path": self.path() if callable(self.path) else self.path, "match": self.match, "recursive": self.recursive, "form_class": forms.FilePathField, "allow_files": self.allow_files, "allow_folders": self.allow_folders, **kwargs, } ) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return float(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FloatField, **kwargs, } ) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be an integer."), } description = _("Integer") def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_max_length_warning(), ] def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with %s." % self.__class__.__name__, hint="Remove 'max_length' from field", obj=self, id="fields.W122", ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None and not any( ( isinstance(validator, validators.MinValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) >= min_value ) for validator in validators_ ): validators_.append(validators.MinValueValidator(min_value)) if max_value is not None and not any( ( isinstance(validator, validators.MaxValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) <= max_value ) for validator in validators_ ): validators_.append(validators.MaxValueValidator(max_value)) return validators_ def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) return connection.ops.adapt_integerfield_value(value, self.get_internal_type()) def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.IntegerField, **kwargs, } ) class BigIntegerField(IntegerField): description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": -BigIntegerField.MAX_BIGINT - 1, "max_value": BigIntegerField.MAX_BIGINT, **kwargs, } ) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_removed_details = { "msg": ( "IPAddressField has been removed except for support in " "historical migrations." ), "hint": "Use GenericIPAddressField instead.", "id": "fields.E900", } def __init__(self, *args, **kwargs): kwargs["max_length"] = 15 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def get_internal_type(self): return "IPAddressField" class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__( self, verbose_name=None, name=None, protocol="both", unpack_ipv4=False, *args, **kwargs, ): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol ( self.default_validators, invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message kwargs["max_length"] = 39 super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_blank_and_null_values(**kwargs), ] def _check_blank_and_null_values(self, **kwargs): if not getattr(self, "null", False) and getattr(self, "blank", False): return [ checks.Error( "GenericIPAddressFields cannot have blank=True if null=False, " "as blank values are stored as nulls.", obj=self, id="fields.E150", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol if kwargs.get("max_length") == 39: del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value is None: return None if not isinstance(value, str): value = str(value) value = value.strip() if ":" in value: return clean_ipv6_address( value, self.unpack_ipv4, self.error_messages["invalid"] ) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None if value and ":" in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return str(value) def formfield(self, **kwargs): return super().formfield( **{ "protocol": self.protocol, "form_class": forms.GenericIPAddressField, **kwargs, } ) class NullBooleanField(BooleanField): default_error_messages = { "invalid": _("“%(value)s” value must be either None, True or False."), "invalid_nullable": _("“%(value)s” value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") system_check_removed_details = { "msg": ( "NullBooleanField is removed except for support in historical " "migrations." ), "hint": "Use BooleanField(null=True, blank=True) instead.", "id": "fields.E903", } def __init__(self, *args, **kwargs): kwargs["null"] = True kwargs["blank"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["null"] del kwargs["blank"] return name, path, args, kwargs class PositiveIntegerRelDbTypeMixin: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not hasattr(cls, "integer_field_class"): cls.integer_field_class = next( ( parent for parent in cls.__mro__[1:] if issubclass(parent, IntegerField) ), None, ) def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. In most cases, a foreign key pointing to a positive integer primary key will have an integer column data type but some databases (e.g. MySQL) have an unsigned integer type. In that case (related_fields_match_type=True), the primary key should return its db_type. """ if connection.features.related_fields_match_type: return self.db_type(connection) else: return self.integer_field_class().db_type(connection=connection) class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): description = _("Positive big integer") def get_internal_type(self): return "PositiveBigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__( self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs ): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs["max_length"] if self.db_index is False: kwargs["db_index"] = False else: del kwargs["db_index"] if self.allow_unicode is not False: kwargs["allow_unicode"] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.SlugField, "allow_unicode": self.allow_unicode, **kwargs, } ) class TextField(Field): description = _("Text") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), ] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_textfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_textfield ): errors.append( checks.Error( "%s does not support a database collation on " "TextFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "TextField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). return super().formfield( **{ "max_length": self.max_length, **({} if self.choices is not None else {"widget": forms.Textarea}), **kwargs, } ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format." ), "invalid_time": _( "“%(value)s” value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." ), } description = _("Time") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): now = None elif isinstance(value, datetime.time): now = _get_naive_now() # This will not use the right date in the race condition where now # is just before the date change and value is just past 0:00. value = datetime.datetime.combine(now.date(), value) else: # No explicit time / datetime value -- no checks necessary return [] # At this point, value is a datetime object. return self._check_if_value_fixed(value, now=now) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs["blank"] del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_time"], code="invalid_time", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_timefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.TimeField, **kwargs, } ) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs["max_length"] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield( **{ "form_class": forms.URLField, **kwargs, } ) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b""] def __init__(self, *args, **kwargs): kwargs.setdefault("editable", False) super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): return [*super().check(**kwargs), *self._check_str_default_value()] def _check_str_default_value(self): if self.has_default() and isinstance(self.default, str): return [ checks.Error( "BinaryField's default cannot be a string. Use bytes " "content instead.", obj=self, id="fields.E170", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: kwargs["editable"] = True else: del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super().get_default() if default == "": return b"" return default def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(self.value_from_object(obj)).decode("ascii") def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, str): return memoryview(b64decode(value.encode("ascii"))) return value class UUIDField(Field): default_error_messages = { "invalid": _("“%(value)s” is not a valid UUID."), } description = _("Universally unique identifier") empty_strings_allowed = False def __init__(self, verbose_name=None, **kwargs): kwargs["max_length"] = 32 super().__init__(verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "UUIDField" def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): value = self.to_python(value) if connection.features.has_native_uuid_field: return value return value.hex def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): input_form = "int" if isinstance(value, int) else "hex" try: return uuid.UUID(**{input_form: value}) except (AttributeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return value def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.UUIDField, **kwargs, } ) class AutoFieldMixin: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self): if not self.primary_key: return [ checks.Error( "AutoFields must set primary_key=True.", obj=self, id="fields.E100", ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["blank"] kwargs["primary_key"] = True return name, path, args, kwargs def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def contribute_to_class(self, cls, name, **kwargs): if cls._meta.auto_field: raise ValueError( "Model %s can't have more than one auto-generated field." % cls._meta.label ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): return None class AutoFieldMeta(type): """ Metaclass to maintain backward inheritance compatibility for AutoField. It is intended that AutoFieldMixin become public API when it is possible to create a non-integer automatically-generated field using column defaults stored in the database. In many areas Django also relies on using isinstance() to check for an automatically-generated field as a subclass of AutoField. A new flag needs to be implemented on Field to be used instead. When these issues have been addressed, this metaclass could be used to deprecate inheritance from AutoField and use of isinstance() with AutoField for detecting automatically-generated fields. """ @property def _subclasses(self): return (BigAutoField, SmallAutoField) def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__( instance ) def __subclasscheck__(self, subclass): return issubclass(subclass, self._subclasses) or super().__subclasscheck__( subclass ) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): def get_internal_type(self): return "AutoField" def rel_db_type(self, connection): return IntegerField().db_type(connection=connection) class BigAutoField(AutoFieldMixin, BigIntegerField): def get_internal_type(self): return "BigAutoField" def rel_db_type(self, connection): return BigIntegerField().db_type(connection=connection) class SmallAutoField(AutoFieldMixin, SmallIntegerField): def get_internal_type(self): return "SmallAutoField" def rel_db_type(self, connection): return SmallIntegerField().db_type(connection=connection)
c9dac63516ae377c718decfa681ce8b775e5e30f5d9bad28b7df74dfb9f4c486
import json import warnings from django import forms from django.core import checks, exceptions from django.db import NotSupportedError, connections, router from django.db.models import expressions, lookups from django.db.models.constants import LOOKUP_SEP from django.db.models.fields import TextField from django.db.models.lookups import ( FieldGetDbPrepValueMixin, PostgresOperatorLookup, Transform, ) from django.utils.deprecation import RemovedInDjango51Warning from django.utils.translation import gettext_lazy as _ from . import Field from .mixins import CheckFieldDefaultMixin __all__ = ["JSONField"] class JSONField(CheckFieldDefaultMixin, Field): empty_strings_allowed = False description = _("A JSON object") default_error_messages = { "invalid": _("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 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._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 = connections[db] if ( self.model._meta.required_db_vendor and self.model._meta.required_db_vendor != connection.vendor ): continue if not ( "supports_json_field" in self.model._meta.required_db_features or connection.features.supports_json_field ): errors.append( checks.Error( "%s does not support JSONFields." % connection.display_name, obj=self.model, id="fields.E180", ) ) return errors def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.encoder is not None: kwargs["encoder"] = self.encoder if self.decoder is not None: kwargs["decoder"] = self.decoder return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value # Some backends (SQLite at least) extract non-string values in their # SQL datatypes. if isinstance(expression, KeyTransform) and not isinstance(value, str): return value try: return json.loads(value, cls=self.decoder) except json.JSONDecodeError: return value def get_internal_type(self): return "JSONField" def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) # RemovedInDjango51Warning: When the deprecation ends, replace with: # if ( # isinstance(value, expressions.Value) # and isinstance(value.output_field, JSONField) # ): # value = value.value # elif hasattr(value, "as_sql"): ... if isinstance(value, expressions.Value): if isinstance(value.value, str) and not isinstance( value.output_field, JSONField ): try: value = json.loads(value.value, cls=self.decoder) except json.JSONDecodeError: value = value.value else: warnings.warn( "Providing an encoded JSON string via Value() is deprecated. " f"Use Value({value!r}, output_field=JSONField()) instead.", category=RemovedInDjango51Warning, ) elif isinstance(value.output_field, JSONField): value = value.value else: return value elif hasattr(value, "as_sql"): return value return connection.ops.adapt_json_value(value, self.encoder) def get_db_prep_save(self, value, connection): if value is None: return value return self.get_db_prep_value(value, connection) def get_transform(self, name): transform = super().get_transform(name) if transform: return transform return KeyTransformFactory(name) def validate(self, value, model_instance): super().validate(value, model_instance) try: json.dumps(value, cls=self.encoder) except TypeError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def value_to_string(self, obj): return self.value_from_object(obj) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.JSONField, "encoder": self.encoder, "decoder": self.decoder, **kwargs, } ) def compile_json_path(key_transforms, include_root=True): path = ["$"] if include_root else [] for key_transform in key_transforms: try: num = int(key_transform) except ValueError: # non-integer path.append(".") path.append(json.dumps(key_transform)) else: path.append("[%s]" % num) return "".join(path) class DataContains(FieldGetDbPrepValueMixin, PostgresOperatorLookup): lookup_name = "contains" postgres_operator = "@>" def as_sql(self, compiler, connection): if not connection.features.supports_json_field_contains: raise NotSupportedError( "contains lookup is not supported on this database backend." ) lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = tuple(lhs_params) + tuple(rhs_params) return "JSON_CONTAINS(%s, %s)" % (lhs, rhs), params class ContainedBy(FieldGetDbPrepValueMixin, PostgresOperatorLookup): lookup_name = "contained_by" postgres_operator = "<@" def as_sql(self, compiler, connection): if not connection.features.supports_json_field_contains: raise NotSupportedError( "contained_by lookup is not supported on this database backend." ) lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = tuple(rhs_params) + tuple(lhs_params) return "JSON_CONTAINS(%s, %s)" % (rhs, lhs), params class HasKeyLookup(PostgresOperatorLookup): logical_operator = None def compile_json_path_final_key(self, key_transform): # Compile the final key without interpreting ints as array elements. return ".%s" % json.dumps(key_transform) def as_sql(self, compiler, connection, template=None): # Process JSON path from the left-hand side. if isinstance(self.lhs, KeyTransform): lhs, lhs_params, lhs_key_transforms = self.lhs.preprocess_lhs( compiler, connection ) lhs_json_path = compile_json_path(lhs_key_transforms) else: lhs, lhs_params = self.process_lhs(compiler, connection) lhs_json_path = "$" sql = template % lhs # Process JSON path from the right-hand side. rhs = self.rhs rhs_params = [] if not isinstance(rhs, (list, tuple)): rhs = [rhs] for key in rhs: if isinstance(key, KeyTransform): *_, rhs_key_transforms = key.preprocess_lhs(compiler, connection) else: rhs_key_transforms = [key] *rhs_key_transforms, final_key = rhs_key_transforms rhs_json_path = compile_json_path(rhs_key_transforms, include_root=False) rhs_json_path += self.compile_json_path_final_key(final_key) rhs_params.append(lhs_json_path + rhs_json_path) # Add condition for each key. if self.logical_operator: sql = "(%s)" % self.logical_operator.join([sql] * len(rhs_params)) return sql, tuple(lhs_params) + tuple(rhs_params) def as_mysql(self, compiler, connection): return self.as_sql( compiler, connection, template="JSON_CONTAINS_PATH(%s, 'one', %%s)" ) def as_oracle(self, compiler, connection): sql, params = self.as_sql( compiler, connection, template="JSON_EXISTS(%s, '%%s')" ) # Add paths directly into SQL because path expressions cannot be passed # as bind variables on Oracle. return sql % tuple(params), [] def as_postgresql(self, compiler, connection): if isinstance(self.rhs, KeyTransform): *_, rhs_key_transforms = self.rhs.preprocess_lhs(compiler, connection) for key in rhs_key_transforms[:-1]: self.lhs = KeyTransform(key, self.lhs) self.rhs = rhs_key_transforms[-1] return super().as_postgresql(compiler, connection) def as_sqlite(self, compiler, connection): return self.as_sql( compiler, connection, template="JSON_TYPE(%s, %%s) IS NOT NULL" ) class HasKey(HasKeyLookup): lookup_name = "has_key" postgres_operator = "?" prepare_rhs = False class HasKeys(HasKeyLookup): lookup_name = "has_keys" postgres_operator = "?&" logical_operator = " AND " def get_prep_lookup(self): return [str(item) for item in self.rhs] class HasAnyKeys(HasKeys): lookup_name = "has_any_keys" postgres_operator = "?|" logical_operator = " OR " class HasKeyOrArrayIndex(HasKey): def compile_json_path_final_key(self, key_transform): return compile_json_path([key_transform], include_root=False) class CaseInsensitiveMixin: """ Mixin to allow case-insensitive comparison of JSON values on MySQL. MySQL handles strings used in JSON context using the utf8mb4_bin collation. Because utf8mb4_bin is a binary collation, comparison of JSON values is case-sensitive. """ def process_lhs(self, compiler, connection): lhs, lhs_params = super().process_lhs(compiler, connection) if connection.vendor == "mysql": return "LOWER(%s)" % lhs, lhs_params return lhs, lhs_params def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) if connection.vendor == "mysql": return "LOWER(%s)" % rhs, rhs_params return rhs, rhs_params class JSONExact(lookups.Exact): can_use_none_as_rhs = True def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) # Treat None lookup values as null. if rhs == "%s" and rhs_params == [None]: rhs_params = ["null"] if connection.vendor == "mysql": func = ["JSON_EXTRACT(%s, '$')"] * len(rhs_params) rhs %= tuple(func) return rhs, rhs_params class JSONIContains(CaseInsensitiveMixin, lookups.IContains): pass JSONField.register_lookup(DataContains) JSONField.register_lookup(ContainedBy) JSONField.register_lookup(HasKey) JSONField.register_lookup(HasKeys) JSONField.register_lookup(HasAnyKeys) JSONField.register_lookup(JSONExact) JSONField.register_lookup(JSONIContains) class KeyTransform(Transform): postgres_operator = "->" postgres_nested_operator = "#>" def __init__(self, key_name, *args, **kwargs): super().__init__(*args, **kwargs) self.key_name = str(key_name) def preprocess_lhs(self, compiler, connection): key_transforms = [self.key_name] previous = self.lhs while isinstance(previous, KeyTransform): key_transforms.insert(0, previous.key_name) previous = previous.lhs lhs, params = compiler.compile(previous) if connection.vendor == "oracle": # Escape string-formatting. key_transforms = [key.replace("%", "%%") for key in key_transforms] return lhs, params, key_transforms def as_mysql(self, compiler, connection): lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) json_path = compile_json_path(key_transforms) return "JSON_EXTRACT(%s, %%s)" % lhs, tuple(params) + (json_path,) def as_oracle(self, compiler, connection): lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) json_path = compile_json_path(key_transforms) return ( "COALESCE(JSON_QUERY(%s, '%s'), JSON_VALUE(%s, '%s'))" % ((lhs, json_path) * 2) ), tuple(params) * 2 def as_postgresql(self, compiler, connection): lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) if len(key_transforms) > 1: sql = "(%s %s %%s)" % (lhs, self.postgres_nested_operator) return sql, tuple(params) + (key_transforms,) try: lookup = int(self.key_name) except ValueError: lookup = self.key_name return "(%s %s %%s)" % (lhs, self.postgres_operator), tuple(params) + (lookup,) def as_sqlite(self, compiler, connection): lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) json_path = compile_json_path(key_transforms) datatype_values = ",".join( [repr(datatype) for datatype in connection.ops.jsonfield_datatype_values] ) return ( "(CASE WHEN JSON_TYPE(%s, %%s) IN (%s) " "THEN JSON_TYPE(%s, %%s) ELSE JSON_EXTRACT(%s, %%s) END)" ) % (lhs, datatype_values, lhs, lhs), (tuple(params) + (json_path,)) * 3 class KeyTextTransform(KeyTransform): postgres_operator = "->>" postgres_nested_operator = "#>>" output_field = TextField() def as_mysql(self, compiler, connection): if connection.mysql_is_mariadb: # MariaDB doesn't support -> and ->> operators (see MDEV-13594). sql, params = super().as_mysql(compiler, connection) return "JSON_UNQUOTE(%s)" % sql, params else: lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) json_path = compile_json_path(key_transforms) return "(%s ->> %%s)" % lhs, tuple(params) + (json_path,) @classmethod def from_lookup(cls, lookup): transform, *keys = lookup.split(LOOKUP_SEP) if not keys: raise ValueError("Lookup must contain key or index transforms.") for key in keys: transform = cls(key, transform) return transform KT = KeyTextTransform.from_lookup class KeyTransformTextLookupMixin: """ Mixin for combining with a lookup expecting a text lhs from a JSONField key lookup. On PostgreSQL, make use of the ->> operator instead of casting key values to text and performing the lookup on the resulting representation. """ def __init__(self, key_transform, *args, **kwargs): if not isinstance(key_transform, KeyTransform): raise TypeError( "Transform should be an instance of KeyTransform in order to " "use this lookup." ) key_text_transform = KeyTextTransform( key_transform.key_name, *key_transform.source_expressions, **key_transform.extra, ) super().__init__(key_text_transform, *args, **kwargs) class KeyTransformIsNull(lookups.IsNull): # key__isnull=False is the same as has_key='key' def as_oracle(self, compiler, connection): sql, params = HasKeyOrArrayIndex( self.lhs.lhs, self.lhs.key_name, ).as_oracle(compiler, connection) if not self.rhs: return sql, params # Column doesn't have a key or IS NULL. lhs, lhs_params, _ = self.lhs.preprocess_lhs(compiler, connection) return "(NOT %s OR %s IS NULL)" % (sql, lhs), tuple(params) + tuple(lhs_params) def as_sqlite(self, compiler, connection): template = "JSON_TYPE(%s, %%s) IS NULL" if not self.rhs: template = "JSON_TYPE(%s, %%s) IS NOT NULL" return HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name).as_sql( compiler, connection, template=template, ) class KeyTransformIn(lookups.In): def resolve_expression_parameter(self, compiler, connection, sql, param): sql, params = super().resolve_expression_parameter( compiler, connection, sql, param, ) if ( not hasattr(param, "as_sql") and not connection.features.has_native_json_field ): if connection.vendor == "oracle": value = json.loads(param) sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')" if isinstance(value, (list, dict)): sql %= "JSON_QUERY" else: sql %= "JSON_VALUE" elif connection.vendor == "mysql" or ( connection.vendor == "sqlite" and params[0] not in connection.ops.jsonfield_datatype_values ): sql = "JSON_EXTRACT(%s, '$')" if connection.vendor == "mysql" and connection.mysql_is_mariadb: sql = "JSON_UNQUOTE(%s)" % sql return sql, params class KeyTransformExact(JSONExact): def process_rhs(self, compiler, connection): if isinstance(self.rhs, KeyTransform): return super(lookups.Exact, self).process_rhs(compiler, connection) rhs, rhs_params = super().process_rhs(compiler, connection) if connection.vendor == "oracle": func = [] sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')" for value in rhs_params: value = json.loads(value) if isinstance(value, (list, dict)): func.append(sql % "JSON_QUERY") else: func.append(sql % "JSON_VALUE") rhs %= tuple(func) elif connection.vendor == "sqlite": func = [] for value in rhs_params: if value in connection.ops.jsonfield_datatype_values: func.append("%s") else: func.append("JSON_EXTRACT(%s, '$')") rhs %= tuple(func) return rhs, rhs_params def as_oracle(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) if rhs_params == ["null"]: # Field has key and it's NULL. has_key_expr = HasKeyOrArrayIndex(self.lhs.lhs, self.lhs.key_name) has_key_sql, has_key_params = has_key_expr.as_oracle(compiler, connection) is_null_expr = self.lhs.get_lookup("isnull")(self.lhs, True) is_null_sql, is_null_params = is_null_expr.as_sql(compiler, connection) return ( "%s AND %s" % (has_key_sql, is_null_sql), tuple(has_key_params) + tuple(is_null_params), ) return super().as_sql(compiler, connection) class KeyTransformIExact( CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IExact ): pass class KeyTransformIContains( CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IContains ): pass class KeyTransformStartsWith(KeyTransformTextLookupMixin, lookups.StartsWith): pass class KeyTransformIStartsWith( CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IStartsWith ): pass class KeyTransformEndsWith(KeyTransformTextLookupMixin, lookups.EndsWith): pass class KeyTransformIEndsWith( CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IEndsWith ): pass class KeyTransformRegex(KeyTransformTextLookupMixin, lookups.Regex): pass class KeyTransformIRegex( CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IRegex ): pass class KeyTransformNumericLookupMixin: def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) if not connection.features.has_native_json_field: rhs_params = [json.loads(value) for value in rhs_params] return rhs, rhs_params class KeyTransformLt(KeyTransformNumericLookupMixin, lookups.LessThan): pass class KeyTransformLte(KeyTransformNumericLookupMixin, lookups.LessThanOrEqual): pass class KeyTransformGt(KeyTransformNumericLookupMixin, lookups.GreaterThan): pass class KeyTransformGte(KeyTransformNumericLookupMixin, lookups.GreaterThanOrEqual): pass KeyTransform.register_lookup(KeyTransformIn) KeyTransform.register_lookup(KeyTransformExact) KeyTransform.register_lookup(KeyTransformIExact) KeyTransform.register_lookup(KeyTransformIsNull) KeyTransform.register_lookup(KeyTransformIContains) KeyTransform.register_lookup(KeyTransformStartsWith) KeyTransform.register_lookup(KeyTransformIStartsWith) KeyTransform.register_lookup(KeyTransformEndsWith) KeyTransform.register_lookup(KeyTransformIEndsWith) KeyTransform.register_lookup(KeyTransformRegex) KeyTransform.register_lookup(KeyTransformIRegex) KeyTransform.register_lookup(KeyTransformLt) KeyTransform.register_lookup(KeyTransformLte) KeyTransform.register_lookup(KeyTransformGt) KeyTransform.register_lookup(KeyTransformGte) class KeyTransformFactory: def __init__(self, key_name): self.key_name = key_name def __call__(self, *args, **kwargs): return KeyTransform(self.key_name, *args, **kwargs)
ca13ba673d2b0d9f47242e63ec84638105ffde189a3642c46a50b0bce2c6429b
import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import Storage, default_storage from django.core.files.utils import validate_file_name from django.db.models import signals from django.db.models.fields import Field from django.db.models.query_utils import DeferredAttribute from django.db.models.utils import AltersData from django.utils.translation import gettext_lazy as _ class FieldFile(File, AltersData): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = 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) # The standard File 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( "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.name, "rb") return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) @property def path(self): self._require_file() return self.storage.path(self.name) @property def url(self): self._require_file() return self.storage.url(self.name) @property def size(self): self._require_file() if not self._committed: return self.file.size return self.storage.size(self.name) def open(self, mode="rb"): self._require_file() if getattr(self, "_file", None) is None: self.file = self.storage.open(self.name, mode) else: self.file.open(mode) return self # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) self.name = self.storage.save(name, content, max_length=self.field.max_length) setattr(self.instance, self.field.attname, self.name) self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): if not self: return # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, "_file"): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.attname, self.name) self._committed = False if save: self.instance.save() delete.alters_data = True @property def closed(self): file = getattr(self, "_file", None) return file is None or file.closed def close(self): file = getattr(self, "_file", None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field, an instance and # the file's name. Everything else will be restored later, by # FileDescriptor below. return { "name": self.name, "closed": False, "_committed": True, "_file": None, "instance": self.instance, "field": self.field, } def __setstate__(self, state): self.__dict__.update(state) self.storage = self.field.storage class FileDescriptor(DeferredAttribute): """ The descriptor for the file attribute on the model instance. Return a FieldFile when accessed so you can write code like:: >>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size Assign a file object on assignment so you can do:: >>> with open('/path/to/hello.world') as f: ... instance.file = File(f) """ def __get__(self, instance, cls=None): if instance is None: return self # This is slightly complicated, so worth an explanation. # instance.file needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = super().__get__(instance, cls) # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, str) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.attname] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to them. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.attname] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, "field"): file.instance = instance file.field = self.field file.storage = self.field.storage # Make sure that the instance is correct. elif isinstance(file, FieldFile) and instance is not file.instance: file.instance = instance # That was fun, wasn't it? return instance.__dict__[self.field.attname] def __set__(self, instance, value): instance.__dict__[self.field.attname] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File") def __init__( self, verbose_name=None, name=None, upload_to="", storage=None, **kwargs ): self._primary_key_set_explicitly = "primary_key" in kwargs self.storage = storage or default_storage if callable(self.storage): # Hold a reference to the callable for deconstruct(). self._storage_callable = self.storage self.storage = self.storage() if not isinstance(self.storage, Storage): raise TypeError( "%s.storage must be a subclass/instance of %s.%s" % ( self.__class__.__qualname__, Storage.__module__, Storage.__qualname__, ) ) self.upload_to = upload_to kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), *self._check_upload_to(), ] def _check_primary_key(self): if self._primary_key_set_explicitly: return [ checks.Error( "'primary_key' is not a valid argument for a %s." % self.__class__.__name__, obj=self, id="fields.E201", ) ] else: return [] def _check_upload_to(self): if isinstance(self.upload_to, str) and self.upload_to.startswith("/"): return [ checks.Error( "%s's 'upload_to' argument must be a relative path, not an " "absolute path." % self.__class__.__name__, obj=self, id="fields.E202", hint="Remove the leading slash.", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 100: del kwargs["max_length"] kwargs["upload_to"] = self.upload_to storage = getattr(self, "_storage_callable", self.storage) if storage is not default_storage: kwargs["storage"] = storage return name, path, args, kwargs def get_internal_type(self): return "FileField" def get_prep_value(self, value): value = super().get_prep_value(value) # Need to convert File objects provided via a form to string for # database insertion. if value is None: return None return str(value) def pre_save(self, model_instance, add): file = super().pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file.file, save=False) return file def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) setattr(cls, self.attname, self.descriptor_class(self)) def generate_filename(self, instance, filename): """ Apply (if callable) or prepend (if a string) upload_to to the filename, then delegate further processing of the name to the storage backend. Until the storage layer, all file paths are expected to be Unix style (with forward slashes). """ if callable(self.upload_to): filename = self.upload_to(instance, filename) else: dirname = datetime.datetime.now().strftime(str(self.upload_to)) filename = posixpath.join(dirname, filename) filename = validate_file_name(filename, allow_relative_path=True) return self.storage.generate_filename(filename) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to str and stored in the # database, so leaving False as-is is not acceptable. setattr(instance, self.name, data or "") def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FileField, "max_length": self.max_length, **kwargs, } ) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.attname) super().__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, "_dimensions_cache"): del self._dimensions_cache super().delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__( self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs, ): self.width_field, self.height_field = width_field, height_field super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_image_library_installed(), ] def _check_image_library_installed(self): try: from PIL import Image # NOQA except ImportError: return [ checks.Error( "Cannot use ImageField because Pillow is not installed.", hint=( "Get Pillow at https://pypi.org/project/Pillow/ " 'or run command "python -m pip install Pillow".' ), obj=self, id="fields.E210", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.width_field: kwargs["width_field"] = self.width_field if self.height_field: kwargs["height_field"] = self.height_field return name, path, args, kwargs def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. # Only run post-initialization dimension update on non-abstract models # with width_field/height_field. if not cls._meta.abstract and (self.width_field or self.height_field): signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Update field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field is deferred. if self.attname not in instance.__dict__: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not ( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.ImageField, **kwargs, } )
c2904210e8afe7bdd94667b0f7d183be5d892a02c988bad8cc6c224cdaa31927
from django.db import NotSupportedError from django.db.models.expressions import Func, Value from django.db.models.fields import CharField, IntegerField, TextField from django.db.models.functions import Cast, Coalesce from django.db.models.lookups import Transform class MySQLSHA2Mixin: def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="SHA2(%%(expressions)s, %s)" % self.function[3:], **extra_context, ) class OracleHashMixin: def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template=( "LOWER(RAWTOHEX(STANDARD_HASH(UTL_I18N.STRING_TO_RAW(" "%(expressions)s, 'AL32UTF8'), '%(function)s')))" ), **extra_context, ) class PostgreSQLSHAMixin: def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="ENCODE(DIGEST(%(expressions)s, '%(function)s'), 'hex')", function=self.function.lower(), **extra_context, ) class Chr(Transform): function = "CHR" lookup_name = "chr" output_field = CharField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function="CHAR", template="%(function)s(%(expressions)s USING utf16)", **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="%(function)s(%(expressions)s USING NCHAR_CS)", **extra_context, ) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="CHAR", **extra_context) class ConcatPair(Func): """ Concatenate two arguments together. This is used by `Concat` because not all backend databases support more than two arguments. """ function = "CONCAT" def as_sqlite(self, compiler, connection, **extra_context): coalesced = self.coalesce() return super(ConcatPair, coalesced).as_sql( compiler, connection, template="%(expressions)s", arg_joiner=" || ", **extra_context, ) def as_postgresql(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ Cast(expression, TextField()) for expression in copy.get_source_expressions() ] ) return super(ConcatPair, copy).as_sql( compiler, connection, **extra_context, ) def as_mysql(self, compiler, connection, **extra_context): # Use CONCAT_WS with an empty separator so that NULLs are ignored. return super().as_sql( compiler, connection, function="CONCAT_WS", template="%(function)s('', %(expressions)s)", **extra_context, ) def coalesce(self): # null on either side results in null for expression, wrap with coalesce c = self.copy() c.set_source_expressions( [ Coalesce(expression, Value("")) for expression in c.get_source_expressions() ] ) return c class Concat(Func): """ Concatenate text fields together. Backends that result in an entire null expression when any arguments are null will wrap each argument in coalesce functions to ensure a non-null result. """ function = None template = "%(expressions)s" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Concat must take at least two expressions") paired = self._paired(expressions) super().__init__(paired, **extra) def _paired(self, expressions): # wrap pairs of expressions in successive concat functions # exp = [a, b, c, d] # -> ConcatPair(a, ConcatPair(b, ConcatPair(c, d)))) if len(expressions) == 2: return ConcatPair(*expressions) return ConcatPair(expressions[0], self._paired(expressions[1:])) class Left(Func): function = "LEFT" arity = 2 output_field = CharField() def __init__(self, expression, length, **extra): """ expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string """ if not hasattr(length, "resolve_expression"): if length < 1: raise ValueError("'length' must be greater than 0.") super().__init__(expression, length, **extra) def get_substr(self): return Substr(self.source_expressions[0], Value(1), self.source_expressions[1]) def as_oracle(self, compiler, connection, **extra_context): return self.get_substr().as_oracle(compiler, connection, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): return self.get_substr().as_sqlite(compiler, connection, **extra_context) class Length(Transform): """Return the number of characters in the expression.""" function = "LENGTH" lookup_name = "length" output_field = IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function="CHAR_LENGTH", **extra_context ) class Lower(Transform): function = "LOWER" lookup_name = "lower" class LPad(Func): function = "LPAD" output_field = CharField() def __init__(self, expression, length, fill_text=Value(" "), **extra): if ( not hasattr(length, "resolve_expression") and length is not None and length < 0 ): raise ValueError("'length' must be greater or equal to 0.") super().__init__(expression, length, fill_text, **extra) class LTrim(Transform): function = "LTRIM" lookup_name = "ltrim" class MD5(OracleHashMixin, Transform): function = "MD5" lookup_name = "md5" class Ord(Transform): function = "ASCII" lookup_name = "ord" output_field = IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="ORD", **extra_context) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="UNICODE", **extra_context) class Repeat(Func): function = "REPEAT" output_field = CharField() def __init__(self, expression, number, **extra): if ( not hasattr(number, "resolve_expression") and number is not None and number < 0 ): raise ValueError("'number' must be greater or equal to 0.") super().__init__(expression, number, **extra) def as_oracle(self, compiler, connection, **extra_context): expression, number = self.source_expressions length = None if number is None else Length(expression) * number rpad = RPad(expression, length, expression) return rpad.as_sql(compiler, connection, **extra_context) class Replace(Func): function = "REPLACE" def __init__(self, expression, text, replacement=Value(""), **extra): super().__init__(expression, text, replacement, **extra) class Reverse(Transform): function = "REVERSE" lookup_name = "reverse" def as_oracle(self, compiler, connection, **extra_context): # REVERSE in Oracle is undocumented and doesn't support multi-byte # strings. Use a special subquery instead. sql, params = super().as_sql( compiler, connection, template=( "(SELECT LISTAGG(s) WITHIN GROUP (ORDER BY n DESC) FROM " "(SELECT LEVEL n, SUBSTR(%(expressions)s, LEVEL, 1) s " "FROM DUAL CONNECT BY LEVEL <= LENGTH(%(expressions)s)) " "GROUP BY %(expressions)s)" ), **extra_context, ) return sql, params * 3 class Right(Left): function = "RIGHT" def get_substr(self): return Substr( self.source_expressions[0], self.source_expressions[1] * Value(-1) ) class RPad(LPad): function = "RPAD" class RTrim(Transform): function = "RTRIM" lookup_name = "rtrim" class SHA1(OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA1" lookup_name = "sha1" class SHA224(MySQLSHA2Mixin, PostgreSQLSHAMixin, Transform): function = "SHA224" lookup_name = "sha224" def as_oracle(self, compiler, connection, **extra_context): raise NotSupportedError("SHA224 is not supported on Oracle.") class SHA256(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA256" lookup_name = "sha256" class SHA384(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA384" lookup_name = "sha384" class SHA512(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA512" lookup_name = "sha512" class StrIndex(Func): """ Return a positive integer corresponding to the 1-indexed position of the first occurrence of a substring inside another string, or 0 if the substring is not found. """ function = "INSTR" arity = 2 output_field = IntegerField() def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="STRPOS", **extra_context) class Substr(Func): function = "SUBSTRING" output_field = CharField() def __init__(self, expression, pos, length=None, **extra): """ expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return """ if not hasattr(pos, "resolve_expression"): if pos < 1: raise ValueError("'pos' must be greater than 0") expressions = [expression, pos] if length is not None: expressions.append(length) super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="SUBSTR", **extra_context) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="SUBSTR", **extra_context) class Trim(Transform): function = "TRIM" lookup_name = "trim" class Upper(Transform): function = "UPPER" lookup_name = "upper"
22809a1a5ad7eff2593b2971d3153945a12204c04f9e861eac02e05f34cd726b
"""Database functions that do comparisons or type conversions.""" from django.db import NotSupportedError from django.db.models.expressions import Func, Value from django.db.models.fields import TextField from django.db.models.fields.json import JSONField from django.utils.regex_helper import _lazy_re_compile class Cast(Func): """Coerce 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_context): 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, %(expressions)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.insert(0, format_string) return sql, params elif db_type == "date": template = "date(%(expressions)s)" return super().as_sql( compiler, connection, template=template, **extra_context ) return self.as_sql(compiler, connection, **extra_context) def as_mysql(self, compiler, connection, **extra_context): template = None output_type = self.output_field.get_internal_type() # MySQL doesn't support explicit cast to float. if output_type == "FloatField": template = "(%(expressions)s + 0.0)" # MariaDB doesn't support explicit cast to JSON. elif output_type == "JSONField" and connection.mysql_is_mariadb: template = "JSON_EXTRACT(%(expressions)s, '$')" return self.as_sql(compiler, connection, template=template, **extra_context) def as_postgresql(self, compiler, connection, **extra_context): # CAST would be valid too, but the :: shortcut syntax is more readable. # 'expressions' is wrapped in parentheses in case it's a complex # expression. return self.as_sql( compiler, connection, template="(%(expressions)s)::%(db_type)s", **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): if self.output_field.get_internal_type() == "JSONField": # Oracle doesn't support explicit cast to JSON. template = "JSON_QUERY(%(expressions)s, '$')" return super().as_sql( compiler, connection, template=template, **extra_context ) return self.as_sql(compiler, connection, **extra_context) class Coalesce(Func): """Return, from left to right, the first non-null expression.""" function = "COALESCE" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Coalesce must take at least two expressions") super().__init__(*expressions, **extra) @property def empty_result_set_value(self): for expression in self.get_source_expressions(): result = expression.empty_result_set_value if result is NotImplemented or result is not None: return result return None def as_oracle(self, compiler, connection, **extra_context): # Oracle prohibits mixing TextField (NCLOB) and CharField (NVARCHAR2), # so convert all fields to NCLOB when that type is expected. if self.output_field.get_internal_type() == "TextField": clone = self.copy() clone.set_source_expressions( [ Func(expression, function="TO_NCLOB") for expression in self.get_source_expressions() ] ) return super(Coalesce, clone).as_sql(compiler, connection, **extra_context) return self.as_sql(compiler, connection, **extra_context) class Collate(Func): function = "COLLATE" template = "%(expressions)s %(function)s %(collation)s" allowed_default = False # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS collation_re = _lazy_re_compile(r"^[\w\-]+$") def __init__(self, expression, collation): if not (collation and self.collation_re.match(collation)): raise ValueError("Invalid collation name: %r." % collation) self.collation = collation super().__init__(expression) def as_sql(self, compiler, connection, **extra_context): extra_context.setdefault("collation", connection.ops.quote_name(self.collation)) return super().as_sql(compiler, connection, **extra_context) class Greatest(Func): """ Return the maximum expression. If any expression is null the return value is database-specific: On PostgreSQL, the maximum not-null expression is returned. On MySQL, Oracle, and SQLite, if any expression is null, null is returned. """ function = "GREATEST" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Greatest must take at least two expressions") super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection, **extra_context): """Use the MAX function on SQLite.""" return super().as_sqlite(compiler, connection, function="MAX", **extra_context) class JSONObject(Func): function = "JSON_OBJECT" output_field = JSONField() def __init__(self, **fields): expressions = [] for key, value in fields.items(): expressions.extend((Value(key), value)) super().__init__(*expressions) def as_sql(self, compiler, connection, **extra_context): if not connection.features.has_json_object_function: raise NotSupportedError( "JSONObject() is not supported on this database backend." ) return super().as_sql(compiler, connection, **extra_context) def as_postgresql(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ Cast(expression, TextField()) if index % 2 == 0 else expression for index, expression in enumerate(copy.get_source_expressions()) ] ) return super(JSONObject, copy).as_sql( compiler, connection, function="JSONB_BUILD_OBJECT", **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): class ArgJoiner: def join(self, args): args = [" VALUE ".join(arg) for arg in zip(args[::2], args[1::2])] return ", ".join(args) return self.as_sql( compiler, connection, arg_joiner=ArgJoiner(), template="%(function)s(%(expressions)s RETURNING CLOB)", **extra_context, ) class Least(Func): """ Return the minimum expression. If any expression is null the return value is database-specific: On PostgreSQL, return the minimum not-null expression. On MySQL, Oracle, and SQLite, if any expression is null, return null. """ function = "LEAST" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Least must take at least two expressions") super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection, **extra_context): """Use the MIN function on SQLite.""" return super().as_sqlite(compiler, connection, function="MIN", **extra_context) class NullIf(Func): function = "NULLIF" arity = 2 def as_oracle(self, compiler, connection, **extra_context): expression1 = self.get_source_expressions()[0] if isinstance(expression1, Value) and expression1.value is None: raise ValueError("Oracle does not allow Value(None) for expression1.") return super().as_sql(compiler, connection, **extra_context)
76a6923db1c1b585ff8ceacf33aca9cd92343db897f19275ef8f188cbd0f9be9
from datetime import datetime from django.conf import settings from django.db.models.expressions import Func from django.db.models.fields import ( DateField, DateTimeField, DurationField, Field, IntegerField, TimeField, ) from django.db.models.lookups import ( Transform, YearExact, YearGt, YearGte, YearLt, YearLte, ) from django.utils import timezone class TimezoneMixin: tzinfo = None 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 = timezone._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, **extra): 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) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) lhs_output_field = self.lhs.output_field if isinstance(lhs_output_field, DateTimeField): tzname = self.get_tzname() sql, params = connection.ops.datetime_extract_sql( self.lookup_name, sql, tuple(params), tzname ) elif self.tzinfo is not None: raise ValueError("tzinfo can only be used with DateTimeField.") elif isinstance(lhs_output_field, DateField): sql, params = connection.ops.date_extract_sql( self.lookup_name, sql, tuple(params) ) elif isinstance(lhs_output_field, TimeField): sql, params = connection.ops.time_extract_sql( self.lookup_name, sql, tuple(params) ) elif isinstance(lhs_output_field, DurationField): if not connection.features.has_native_duration_field: raise ValueError( "Extract requires native DurationField database support." ) sql, params = connection.ops.time_extract_sql( self.lookup_name, sql, tuple(params) ) else: # resolve_expression has already validated the output_field so this # assert should never be hit. assert False, "Tried to Extract from an invalid type." return sql, params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): copy = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) field = getattr(copy.lhs, "output_field", None) if field is None: return copy if not isinstance(field, (DateField, DateTimeField, TimeField, DurationField)): raise ValueError( "Extract input expression must be DateField, DateTimeField, " "TimeField, or DurationField." ) # Passing dates to functions expecting datetimes is most likely a mistake. if type(field) == DateField and copy.lookup_name in ( "hour", "minute", "second", ): raise ValueError( "Cannot extract time component '%s' from DateField '%s'." % (copy.lookup_name, field.name) ) if isinstance(field, DurationField) and copy.lookup_name in ( "year", "iso_year", "month", "week", "week_day", "iso_week_day", "quarter", ): raise ValueError( "Cannot extract component '%s' from DurationField '%s'." % (copy.lookup_name, field.name) ) return copy class ExtractYear(Extract): lookup_name = "year" class ExtractIsoYear(Extract): """Return the ISO-8601 week-numbering year.""" lookup_name = "iso_year" class ExtractMonth(Extract): lookup_name = "month" class ExtractDay(Extract): lookup_name = "day" class ExtractWeek(Extract): """ Return 1-52 or 53, based on ISO-8601, i.e., Monday is the first of the week. """ lookup_name = "week" class ExtractWeekDay(Extract): """ Return Sunday=1 through Saturday=7. To replicate this in Python: (mydatetime.isoweekday() % 7) + 1 """ lookup_name = "week_day" class ExtractIsoWeekDay(Extract): """Return Monday=1 through Sunday=7, based on ISO-8601.""" lookup_name = "iso_week_day" class ExtractQuarter(Extract): lookup_name = "quarter" class ExtractHour(Extract): lookup_name = "hour" class ExtractMinute(Extract): lookup_name = "minute" class ExtractSecond(Extract): lookup_name = "second" DateField.register_lookup(ExtractYear) DateField.register_lookup(ExtractMonth) DateField.register_lookup(ExtractDay) DateField.register_lookup(ExtractWeekDay) DateField.register_lookup(ExtractIsoWeekDay) DateField.register_lookup(ExtractWeek) DateField.register_lookup(ExtractIsoYear) DateField.register_lookup(ExtractQuarter) TimeField.register_lookup(ExtractHour) TimeField.register_lookup(ExtractMinute) TimeField.register_lookup(ExtractSecond) DateTimeField.register_lookup(ExtractHour) DateTimeField.register_lookup(ExtractMinute) DateTimeField.register_lookup(ExtractSecond) ExtractYear.register_lookup(YearExact) ExtractYear.register_lookup(YearGt) ExtractYear.register_lookup(YearGte) ExtractYear.register_lookup(YearLt) ExtractYear.register_lookup(YearLte) ExtractIsoYear.register_lookup(YearExact) ExtractIsoYear.register_lookup(YearGt) ExtractIsoYear.register_lookup(YearGte) ExtractIsoYear.register_lookup(YearLt) ExtractIsoYear.register_lookup(YearLte) class Now(Func): template = "CURRENT_TIMESTAMP" output_field = DateTimeField() def as_postgresql(self, compiler, connection, **extra_context): # PostgreSQL's CURRENT_TIMESTAMP means "the time at the start of the # transaction". Use STATEMENT_TIMESTAMP to be cross-compatible with # other databases. return self.as_sql( compiler, connection, template="STATEMENT_TIMESTAMP()", **extra_context ) def as_mysql(self, compiler, connection, **extra_context): return self.as_sql( compiler, connection, template="CURRENT_TIMESTAMP(6)", **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): return self.as_sql( compiler, connection, template="STRFTIME('%%%%Y-%%%%m-%%%%d %%%%H:%%%%M:%%%%f', 'NOW')", **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): return self.as_sql( compiler, connection, template="LOCALTIMESTAMP", **extra_context ) class TruncBase(TimezoneMixin, Transform): kind = None tzinfo = None def __init__( self, expression, output_field=None, tzinfo=None, **extra, ): self.tzinfo = tzinfo super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) tzname = None if isinstance(self.lhs.output_field, DateTimeField): tzname = self.get_tzname() elif self.tzinfo is not None: raise ValueError("tzinfo can only be used with DateTimeField.") if isinstance(self.output_field, DateTimeField): sql, params = connection.ops.datetime_trunc_sql( self.kind, sql, tuple(params), tzname ) elif isinstance(self.output_field, DateField): sql, params = connection.ops.date_trunc_sql( self.kind, sql, tuple(params), tzname ) elif isinstance(self.output_field, TimeField): sql, params = connection.ops.time_trunc_sql( self.kind, sql, tuple(params), tzname ) else: raise ValueError( "Trunc only valid on DateField, TimeField, or DateTimeField." ) return sql, params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): copy = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) field = copy.lhs.output_field # DateTimeField is a subclass of DateField so this works for both. if not isinstance(field, (DateField, TimeField)): raise TypeError( "%r isn't a DateField, TimeField, or DateTimeField." % field.name ) # If self.output_field was None, then accessing the field will trigger # the resolver to assign it to self.lhs.output_field. if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)): raise ValueError( "output_field must be either DateField, TimeField, or DateTimeField" ) # Passing dates or times to functions expecting datetimes is most # likely a mistake. class_output_field = ( self.__class__.output_field if isinstance(self.__class__.output_field, Field) else None ) output_field = class_output_field or copy.output_field has_explicit_output_field = ( class_output_field or field.__class__ is not copy.output_field.__class__ ) if type(field) == DateField and ( isinstance(output_field, DateTimeField) or copy.kind in ("hour", "minute", "second", "time") ): raise ValueError( "Cannot truncate DateField '%s' to %s." % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else "DateTimeField", ) ) elif isinstance(field, TimeField) and ( isinstance(output_field, DateTimeField) or copy.kind in ("year", "quarter", "month", "week", "day", "date") ): raise ValueError( "Cannot truncate TimeField '%s' to %s." % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else "DateTimeField", ) ) return copy def convert_value(self, value, expression, connection): if isinstance(self.output_field, DateTimeField): if not settings.USE_TZ: pass elif value is not None: value = value.replace(tzinfo=None) value = timezone.make_aware(value, self.tzinfo) elif not connection.features.has_zoneinfo_database: raise ValueError( "Database returned an invalid datetime value. Are time " "zone definitions for your database installed?" ) elif isinstance(value, datetime): if value is None: pass elif isinstance(self.output_field, DateField): value = value.date() elif isinstance(self.output_field, TimeField): value = value.time() return value class Trunc(TruncBase): def __init__( self, expression, kind, output_field=None, tzinfo=None, **extra, ): self.kind = kind super().__init__(expression, output_field=output_field, tzinfo=tzinfo, **extra) class TruncYear(TruncBase): kind = "year" class TruncQuarter(TruncBase): kind = "quarter" class TruncMonth(TruncBase): kind = "month" class TruncWeek(TruncBase): """Truncate to midnight on the Monday of the week.""" kind = "week" class TruncDay(TruncBase): kind = "day" class TruncDate(TruncBase): kind = "date" lookup_name = "date" output_field = DateField() def as_sql(self, compiler, connection): # Cast to date rather than truncate to date. sql, params = compiler.compile(self.lhs) tzname = self.get_tzname() return connection.ops.datetime_cast_date_sql(sql, tuple(params), tzname) class TruncTime(TruncBase): kind = "time" lookup_name = "time" output_field = TimeField() def as_sql(self, compiler, connection): # Cast to time rather than truncate to time. sql, params = compiler.compile(self.lhs) tzname = self.get_tzname() return connection.ops.datetime_cast_time_sql(sql, tuple(params), tzname) class TruncHour(TruncBase): kind = "hour" class TruncMinute(TruncBase): kind = "minute" class TruncSecond(TruncBase): kind = "second" DateTimeField.register_lookup(TruncDate) DateTimeField.register_lookup(TruncTime)
99c30cff1394069d271832d3dc8c866d75cfb6c667175c956c67ff94a3fbc45f
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child def rename_prefix_from_q(prefix, replacement, q): return Q.create( [ rename_prefix_from_q(prefix, replacement, c) if isinstance(c, Node) else (c[0].replace(prefix, replacement, 1), c[1]) for c in q.children ], q.connector, q.negated, ) JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False has_select_fields = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def get_aggregation(self, using, aggregate_exprs): """ Return the dictionary with the values of the existing aggregations. """ if not aggregate_exprs: return {} aggregates = {} for alias, aggregate_expr in aggregate_exprs.items(): self.check_alias(alias) aggregate = aggregate_expr.resolve_expression( self, allow_joins=True, reuse=None, summarize=True ) if not aggregate.contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) aggregates[alias] = aggregate # Existing usage of aggregation can be determined by the presence of # selected aggregates but also by filters against aliased aggregates. _, having, qualify = self.where.split_having_qualify() has_existing_aggregation = ( any( getattr(annotation, "contains_aggregate", True) for annotation in self.annotations.values() ) or having ) # Decide if we need to use a subquery. # # Existing aggregations would cause incorrect results as # get_aggregation() must produce just one result and thus must not use # GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or has_existing_aggregation or qualify or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. if inner_query.default_cols and has_existing_aggregation: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False if not qualify: # Mask existing annotations that are not referenced by # aggregates to be pushed to the outer query unless # filtering against window functions is involved as it # requires complex realising. annotation_mask = set() if isinstance(self.group_by, tuple): for expr in self.group_by: annotation_mask |= expr.get_refs() for aggregate in aggregates.values(): annotation_mask |= aggregate.get_refs() inner_query.set_annotation_mask(annotation_mask) # Add aggregates to the outer AggregateQuery. This requires making # sure all columns referenced by the aggregates are selected in the # inner query. It is achieved by retrieving all column references # by the aggregates, explicitly selecting them in the inner query, # and making sure the aggregates are repointed to them. col_refs = {} for alias, aggregate in aggregates.items(): replacements = {} for col in self._gen_cols([aggregate], resolve_refs=False): if not (col_ref := col_refs.get(col)): index = len(col_refs) + 1 col_alias = f"__col{index}" col_ref = Ref(col_alias, col) col_refs[col] = col_ref inner_query.annotations[col_alias] = col inner_query.append_annotation_mask([col_alias]) replacements[col] = col_ref outer_query.annotations[alias] = aggregate.replace_expressions( replacements ) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} if self.annotations: # Inline reference to existing annotations and mask them as # they are unnecessary given only the summarized aggregations # are requested. replacements = { Ref(alias, annotation): annotation for alias, annotation in self.annotations.items() } self.annotations = { alias: aggregate.replace_expressions(replacements) for alias, aggregate in aggregates.items() } else: self.annotations = aggregates self.set_annotation_mask(aggregates) empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result else: converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() return obj.get_aggregation(using, {"__count": Count("*")})["__count"] def has_filters(self): return self.where def exists(self, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": q.combined_queries = tuple( combined_query.exists(limit=False) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def _get_defer_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # All concrete fields that are not part of the defer mask must be # loaded. If a relational field is encountered it gets added to the # mask for it be considered if `select_related` and the cycle continues # by recursively calling this function. for field in opts.concrete_fields: field_mask = mask.pop(field.name, None) field_att_mask = mask.pop(field.attname, None) if field_mask is None and field_att_mask is None: select_mask.setdefault(field, {}) elif field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) field_select_mask = select_mask.setdefault(field, {}) related_model = field.remote_field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) # Remaining defer entries must be references to reverse relationships. # The following code is expected to raise FieldError if it encounters # a malformed defer entry. for field_name, field_mask in mask.items(): if filtered_relation := self._filtered_relations.get(field_name): relation = opts.get_field(filtered_relation.relation_name) field_select_mask = select_mask.setdefault((field_name, relation), {}) field = relation.field else: reverse_rel = opts.get_field(field_name) # While virtual fields such as many-to-many and generic foreign # keys cannot be effectively deferred we've historically # allowed them to be passed to QuerySet.defer(). Ignore such # field references until a layer of validation at mask # alteration time will be implemented eventually. if not hasattr(reverse_rel, "field"): continue field = reverse_rel.field field_select_mask = select_mask.setdefault(field, {}) related_model = field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def _get_only_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # Only include fields mentioned in the mask. for field_name, field_mask in mask.items(): field = opts.get_field(field_name) field_select_mask = select_mask.setdefault(field, {}) if field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) related_model = field.remote_field.model._meta.concrete_model self._get_only_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def get_select_mask(self): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. """ field_names, defer = self.deferred_loading if not field_names: return {} mask = {} for field_name in field_names: part_mask = mask for part in field_name.split(LOOKUP_SEP): part_mask = part_mask.setdefault(part, {}) opts = self.get_meta() if defer: return self._get_defer_select_mask(opts, mask) return self._get_only_select_mask(opts, mask) def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join if filtered_relation := join.filtered_relation: resolve_reuse = reuse if resolve_reuse is not None: resolve_reuse = set(reuse) | {alias} joins_len = len(self.alias_map) join.filtered_relation = filtered_relation.resolve_expression( self, reuse=resolve_reuse ) # Some joins were during expression resolving, they must be present # before the one we just added. if joins_len < len(self.alias_map): self.alias_map[alias] = self.alias_map.pop(alias) return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None) if select: self.append_annotation_mask([alias]) else: annotation_mask = ( value for value in dict.fromkeys(self.annotation_select) if value != alias ) self.set_annotation_mask(annotation_mask) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, wrapper=None): # If wrapper is referenced by an alias for an explicit GROUP BY through # values() a reference to this expression and not the self must be # returned to ensure external column references are not grouped against # as well. external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [wrapper or self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup, summarize=False): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: annotation, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if annotation: expression = self.annotations[annotation] if summarize: expression = Ref(annotation, expression) return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, lhs.output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, update_join_types=True, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, update_join_types=update_join_types, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression( self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize ) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, update_join_types=True, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, update_join_types=update_join_types, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) if update_join_types: needed_inner = joinpromoter.update_join_types(self) else: needed_inner = [] return target_clause, needed_inner def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) filtered_relation.condition = rename_prefix_from_q( filtered_relation.relation_name, alias, filtered_relation.condition, ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) final_transformer.has_transforms = True # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m else None alias = self.join(connection, reuse=reuse) joins.append(alias) return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False, resolve_refs=True): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): if not resolve_refs and isinstance(expr, Ref): continue yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, resolve_refs=resolve_refs, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue item = item.removeprefix("-") if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ if allow_aliases and self.values_select: # If grouping by aliases is allowed assign selected value aliases # by moving them to annotations. group_by_annotations = {} values_select = {} for alias, expr in zip(self.values_select, self.select): if isinstance(expr, Col): values_select[alias] = expr else: group_by_annotations[alias] = expr self.annotations = {**group_by_annotations, **self.annotations} self.append_annotation_mask(group_by_annotations) self.select = tuple(values_select.values()) self.values_select = tuple(values_select) group_by = list(self.select) for alias, annotation in self.annotation_select.items(): if not (group_by_cols := annotation.get_group_by_cols()): continue if allow_aliases and not annotation.contains_aggregate: group_by.append(Ref(alias, annotation)) else: group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = list(dict.fromkeys(names)) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask((*self.annotation_select_mask, *names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() self.has_select_fields = True if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) elif f in self.annotations: raise FieldError( f"Cannot select the '{f}' alias. Use annotate() to " "promote it." ) else: # Call `names_to_path` to ensure a FieldError including # annotations about to be masked as valid choices if # `f` is not resolvable. if self.annotation_select: self.names_to_path(f.split(LOOKUP_SEP), self.model._meta) field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: self.annotations[k] for k in self.annotation_select_mask if k in self.annotations } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == OR and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == AND or ( self.effective_connector == OR and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
71a6901f4c67f3ee5e331cf4f5448087d964361d9e8bfac041ed4d12bd1be15c
import collections import json import re from functools import partial from itertools import chain from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value from django.db.models.functions import Cast, Random from django.db.models.lookups import Lookup from django.db.models.query_utils import select_related_descend from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE, ) from django.db.models.sql.query import Query, get_order_dir from django.db.models.sql.where import AND from django.db.transaction import TransactionManagementError from django.utils.functional import cached_property from django.utils.hashable import make_hashable from django.utils.regex_helper import _lazy_re_compile class PositionRef(Ref): def __init__(self, ordinal, refs, source): self.ordinal = ordinal super().__init__(refs, source) def as_sql(self, compiler, connection): return str(self.ordinal), () class SQLCompiler: # Multiline ordering SQL clause may appear from RawSQL. ordering_parts = _lazy_re_compile( r"^(.*)\s(?:ASC|DESC).*", re.MULTILINE | re.DOTALL, ) def __init__(self, query, connection, using, elide_empty=True): self.query = query self.connection = connection self.using = using # Some queries, e.g. coalesced aggregation, need to be executed even if # they would return an empty result set. self.elide_empty = elide_empty self.quote_cache = {"*": "*"} # The select, klass_info, and annotations are needed by QuerySet.iterator() # these are set as a side-effect of executing the query. Note that we calculate # separately a list of extra select columns needed for grammatical correctness # of the query, but these columns are not included in self.select. self.select = None self.annotation_col_map = None self.klass_info = None self._meta_ordering = None def __repr__(self): return ( f"<{self.__class__.__qualname__} " f"model={self.query.model.__qualname__} " f"connection={self.connection!r} using={self.using!r}>" ) def setup_query(self, with_col_aliases=False): if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map): self.query.get_initial_alias() self.select, self.klass_info, self.annotation_col_map = self.get_select( with_col_aliases=with_col_aliases, ) self.col_count = len(self.select) def pre_sql_setup(self, with_col_aliases=False): """ Do any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ self.setup_query(with_col_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): """ 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 correct". """ # Some examples: # SomeModel.objects.annotate(Count('somecol')) # GROUP BY: all fields of the model # # SomeModel.objects.values('name').annotate(Count('somecol')) # GROUP BY: name # # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # # SomeModel.objects.values('name', 'pk') # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # In fact, the self.query.group_by is the minimal set to GROUP BY. It # can't be ever restricted to a smaller set, but additional columns in # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately # the end result is that it is impossible to force the query to have # a chosen GROUP BY clause - you can almost do this by using the form: # .values(*wanted_cols).annotate(AnAggregate()) # but any later annotations, extra selects, values calls that # refer some column outside of the wanted_cols, order_by, or even # filter calls can alter the GROUP BY clause. # The query.group_by is either None (no GROUP BY at all), True # (group by select fields), or a list of expressions to be added # to the group by. if self.query.group_by is None: return [] expressions = [] group_by_refs = set() if self.query.group_by is not True: # If the group by is set to a list (by .values() call most likely), # then we need to add everything in it to the GROUP BY clause. # Backwards compatibility hack for setting query.group_by. Remove # when we have public API way of forcing the GROUP BY clause. # Converts string references to expressions. for expr in self.query.group_by: if not hasattr(expr, "as_sql"): expr = self.query.resolve_ref(expr) if isinstance(expr, Ref): if expr.refs not in group_by_refs: group_by_refs.add(expr.refs) expressions.append(expr.source) else: expressions.append(expr) # Note that even if the group_by is set, it is only the minimal # set to group by. So, we need to add cols in select, order_by, and # having into the select in any case. selected_expr_positions = {} for ordinal, (expr, _, alias) in enumerate(select, start=1): if alias: selected_expr_positions[expr] = ordinal # Skip members of the select clause that are already explicitly # grouped against. if alias in group_by_refs: continue expressions.extend(expr.get_group_by_cols()) if not self._meta_ordering: for expr, (sql, params, is_ref) in order_by: # Skip references to the SELECT clause, as all expressions in # the SELECT clause are already part of the GROUP BY. if not is_ref: expressions.extend(expr.get_group_by_cols()) having_group_by = self.having.get_group_by_cols() if self.having else () for expr in having_group_by: expressions.append(expr) result = [] seen = set() expressions = self.collapse_group_by(expressions, having_group_by) allows_group_by_select_index = ( self.connection.features.allows_group_by_select_index ) for expr in expressions: try: sql, params = self.compile(expr) except (EmptyResultSet, FullResultSet): continue if ( allows_group_by_select_index and (position := selected_expr_positions.get(expr)) is not None ): sql, params = str(position), () else: sql, params = expr.select_format(self, sql, params) params_hash = make_hashable(params) if (sql, params_hash) not in seen: result.append((sql, params)) seen.add((sql, params_hash)) return result def collapse_group_by(self, expressions, having): # If the database supports group by functional dependence reduction, # then the expressions can be reduced to the set of selected table # primary keys as all other columns are functionally dependent on them. if self.connection.features.allows_group_by_selected_pks: # Filter out all expressions associated with a table's primary key # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. # Unmanaged models are excluded because they could be representing # database views on which the optimization might not be allowed. pks = { expr for expr in expressions if ( hasattr(expr, "target") and expr.target.primary_key and self.connection.features.allows_group_by_selected_pks_on_model( expr.target.model ) ) } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or expr in having or getattr(expr, "alias", None) not in aliases ] return expressions def get_select(self, with_col_aliases=False): """ Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_info structure contains the following information: - The base model of the query. - Which columns for that model are present in the query (by position of the select clause). - related_klass_infos: [f, klass_info] to descent into The annotations is a dictionary of {'attname': column position} values. """ select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += 1 assert not (self.query.select and self.query.default_cols) select_mask = self.query.get_select_mask() if self.query.default_cols: cols = self.get_default_columns(select_mask) else: # self.query.select is a special case. These columns never go to # any model. cols = self.query.select if cols: select_list = [] for col in cols: select_list.append(select_idx) select.append((col, None)) select_idx += 1 klass_info = { "model": self.query.model, "select_fields": select_list, } for alias, annotation in self.query.annotation_select.items(): annotations[alias] = select_idx select.append((annotation, alias)) select_idx += 1 if self.query.select_related: related_klass_infos = self.get_related_selections(select, select_mask) klass_info["related_klass_infos"] = related_klass_infos def get_select_from_parent(klass_info): for ki in klass_info["related_klass_infos"]: if ki["from_parent"]: ki["select_fields"] = ( klass_info["select_fields"] + ki["select_fields"] ) get_select_from_parent(ki) get_select_from_parent(klass_info) ret = [] col_idx = 1 for col, alias in select: try: sql, params = self.compile(col) except EmptyResultSet: empty_result_set_value = getattr( col, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: # Select a predicate that's always False. sql, params = "0", () else: sql, params = self.compile(Value(empty_result_set_value)) except FullResultSet: sql, params = self.compile(Value(True)) else: sql, params = col.select_format(self, sql, params) if alias is None and with_col_aliases: alias = f"col{col_idx}" col_idx += 1 ret.append((col, (sql, params), alias)) return ret, klass_info, annotations def _order_by_pairs(self): if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by elif self.query.order_by: ordering = self.query.order_by elif (meta := self.query.get_meta()) and meta.ordering: ordering = meta.ordering self._meta_ordering = ordering else: ordering = [] if self.query.standard_ordering: default_order, _ = ORDER_DIR["ASC"] else: default_order, _ = ORDER_DIR["DESC"] selected_exprs = {} # Avoid computing `selected_exprs` if there is no `ordering` as it's # relatively expensive. if ordering and (select := self.select): for ordinal, (expr, _, alias) in enumerate(select, start=1): pos_expr = PositionRef(ordinal, alias, expr) if alias: selected_exprs[alias] = pos_expr selected_exprs[expr] = pos_expr for field in ordering: if hasattr(field, "resolve_expression"): if isinstance(field, Value): # output_field must be resolved for constants. field = Cast(field, field.output_field) if not isinstance(field, OrderBy): field = field.asc() if not self.query.standard_ordering: field = field.copy() field.reverse_ordering() select_ref = selected_exprs.get(field.expression) if select_ref or ( isinstance(field.expression, F) and (select_ref := selected_exprs.get(field.expression.name)) ): # Emulation of NULLS (FIRST|LAST) cannot be combined with # the usage of ordering by position. if ( field.nulls_first is None and field.nulls_last is None ) or self.connection.features.supports_order_by_nulls_modifier: field = field.copy() field.expression = select_ref # Alias collisions are not possible when dealing with # combined queries so fallback to it if emulation of NULLS # handling is required. elif self.query.combinator: field = field.copy() field.expression = Ref(select_ref.refs, select_ref.source) yield field, select_ref is not None continue if field == "?": # random yield OrderBy(Random()), False continue col, order = get_order_dir(field, default_order) descending = order == "DESC" if select_ref := selected_exprs.get(col): # Reference to expression in SELECT clause yield ( OrderBy( select_ref, descending=descending, ), True, ) continue if col in self.query.annotations: # References to an expression which is masked out of the SELECT # clause. if self.query.combinator and self.select: # Don't use the resolved annotation because other # combinated queries might define it differently. expr = F(col) else: expr = self.query.annotations[col] if isinstance(expr, Value): # output_field must be resolved for constants. expr = Cast(expr, expr.output_field) yield OrderBy(expr, descending=descending), False continue if "." in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split(".", 1) yield ( OrderBy( RawSQL( "%s.%s" % (self.quote_name_unless_alias(table), col), [] ), descending=descending, ), False, ) continue if self.query.extra and col in self.query.extra: if col in self.query.extra_select: yield ( OrderBy( Ref(col, RawSQL(*self.query.extra[col])), descending=descending, ), True, ) else: yield ( OrderBy(RawSQL(*self.query.extra[col]), descending=descending), False, ) else: if self.query.combinator and self.select: # Don't use the first model's field because other # combinated queries might define it differently. yield OrderBy(F(col), descending=descending), False else: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. yield from self.find_ordering_name( field, self.query.get_meta(), default_order=default_order, ) def get_order_by(self): """ Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for the ORDER BY clause. The order_by clause can alter the select clause (for example it can add aliases to clauses that do not yet have one, or it can add totally new select clauses). """ result = [] seen = set() for expr, is_ref in self._order_by_pairs(): resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None) if not is_ref and self.query.combinator and self.select: src = resolved.expression expr_src = expr.expression for sel_expr, _, col_alias in self.select: if src == sel_expr: # When values() is used the exact alias must be used to # reference annotations. if ( self.query.has_select_fields and col_alias in self.query.annotation_select and not ( isinstance(expr_src, F) and col_alias == expr_src.name ) ): continue resolved.set_source_expressions( [Ref(col_alias if col_alias else src.target.column, src)] ) break else: # Add column used in ORDER BY clause to the selected # columns and to each combined query. order_by_idx = len(self.query.select) + 1 col_alias = f"__orderbycol{order_by_idx}" for q in self.query.combined_queries: # If fields were explicitly selected through values() # combined queries cannot be augmented. if q.has_select_fields: raise DatabaseError( "ORDER BY term does not match any column in " "the result set." ) q.add_annotation(expr_src, col_alias) self.query.add_select_col(resolved, col_alias) resolved.set_source_expressions([Ref(col_alias, src)]) sql, params = self.compile(resolved) # Don't add the same column twice, but the order direction is # not taken into account so we strip it. When this entire method # is refactored into expressions, then we can check each part as we # generate it. without_ordering = self.ordering_parts.search(sql)[1] params_hash = make_hashable(params) if (without_ordering, params_hash) in seen: continue seen.add((without_ordering, params_hash)) result.append((resolved, (sql, params, is_ref))) return result def get_extra_select(self, order_by, select): extra_select = [] if self.query.distinct and not self.query.distinct_fields: select_sql = [t[1] for t in select] for expr, (sql, params, is_ref) in order_by: without_ordering = self.ordering_parts.search(sql)[1] if not is_ref and (without_ordering, params) not in select_sql: extra_select.append((expr, (without_ordering, params), None)) return extra_select def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ( (name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select or ( self.query.external_aliases.get(name) and name not in self.query.table_map ) ): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def compile(self, node): vendor_impl = getattr(node, "as_" + self.connection.vendor, None) if vendor_impl: sql, params = vendor_impl(self, self.connection) else: sql, params = node.as_sql(self, self.connection) return sql, params def get_combinator_sql(self, combinator, all): features = self.connection.features compilers = [ query.get_compiler(self.using, self.connection, self.elide_empty) for query in self.query.combined_queries ] if not features.supports_slicing_ordering_in_compound: for compiler in compilers: if compiler.query.is_sliced: raise DatabaseError( "LIMIT/OFFSET not allowed in subqueries of compound statements." ) if compiler.get_order_by(): raise DatabaseError( "ORDER BY not allowed in subqueries of compound statements." ) elif self.query.is_sliced and combinator == "union": for compiler in compilers: # A sliced union cannot have its parts elided as some of them # might be sliced as well and in the event where only a single # part produces a non-empty resultset it might be impossible to # generate valid SQL. compiler.elide_empty = False parts = () for compiler in compilers: try: # If the columns list is limited, then all combined queries # must have the same columns list. Set the selects defined on # the query on all combined queries, if not already set. if not compiler.query.values_select and self.query.values_select: compiler.query = compiler.query.clone() compiler.query.set_values( ( *self.query.extra_select, *self.query.values_select, *self.query.annotation_select, ) ) part_sql, part_args = compiler.as_sql(with_col_aliases=True) if compiler.query.combinator: # Wrap in a subquery if wrapping in parentheses isn't # supported. if not features.supports_parentheses_in_compound: part_sql = "SELECT * FROM ({})".format(part_sql) # Add parentheses when combining with compound query if not # already added for all compound queries. elif ( self.query.subquery or not features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) elif ( self.query.subquery and features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) parts += ((part_sql, part_args),) except EmptyResultSet: # Omit the empty queryset with UNION and with DIFFERENCE if the # first queryset is nonempty. if combinator == "union" or (combinator == "difference" and parts): continue raise if not parts: raise EmptyResultSet combinator_sql = self.connection.ops.set_operators[combinator] if all and combinator == "union": combinator_sql += " ALL" braces = "{}" if not self.query.subquery and features.supports_slicing_ordering_in_compound: braces = "({})" sql_parts, args_parts = zip( *((braces.format(sql), args) for sql, args in parts) ) result = [" {} ".format(combinator_sql).join(sql_parts)] params = [] for part in args_parts: params.extend(part) return result, params def get_qualify_sql(self): where_parts = [] if self.where: where_parts.append(self.where) if self.having: where_parts.append(self.having) inner_query = self.query.clone() inner_query.subquery = True inner_query.where = inner_query.where.__class__(where_parts) # Augment the inner query with any window function references that # might have been masked via values() and alias(). If any masked # aliases are added they'll be masked again to avoid fetching # the data in the `if qual_aliases` branch below. select = { expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0] } select_aliases = set(select.values()) qual_aliases = set() replacements = {} def collect_replacements(expressions): while expressions: expr = expressions.pop() if expr in replacements: continue elif select_alias := select.get(expr): replacements[expr] = select_alias elif isinstance(expr, Lookup): expressions.extend(expr.get_source_expressions()) elif isinstance(expr, Ref): if expr.refs not in select_aliases: expressions.extend(expr.get_source_expressions()) else: num_qual_alias = len(qual_aliases) select_alias = f"qual{num_qual_alias}" qual_aliases.add(select_alias) inner_query.add_annotation(expr, select_alias) replacements[expr] = select_alias collect_replacements(list(self.qualify.leaves())) self.qualify = self.qualify.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) order_by = [] for order_by_expr, *_ in self.get_order_by(): collect_replacements(order_by_expr.get_source_expressions()) order_by.append( order_by_expr.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) ) inner_query_compiler = inner_query.get_compiler( self.using, connection=self.connection, elide_empty=self.elide_empty ) inner_sql, inner_params = inner_query_compiler.as_sql( # The limits must be applied to the outer query to avoid pruning # results too eagerly. with_limits=False, # Force unique aliasing of selected columns to avoid collisions # and make rhs predicates referencing easier. with_col_aliases=True, ) qualify_sql, qualify_params = self.compile(self.qualify) result = [ "SELECT * FROM (", inner_sql, ")", self.connection.ops.quote_name("qualify"), "WHERE", qualify_sql, ] if qual_aliases: # If some select aliases were unmasked for filtering purposes they # must be masked back. cols = [self.connection.ops.quote_name(alias) for alias in select.values()] result = [ "SELECT", ", ".join(cols), "FROM (", *result, ")", self.connection.ops.quote_name("qualify_mask"), ] params = list(inner_params) + qualify_params # As the SQL spec is unclear on whether or not derived tables # ordering must propagate it has to be explicitly repeated on the # outer-most query to ensure it's preserved. if order_by: ordering_sqls = [] for ordering in order_by: ordering_sql, ordering_params = self.compile(ordering) ordering_sqls.append(ordering_sql) params.extend(ordering_params) result.extend(["ORDER BY", ", ".join(ordering_sqls)]) return result, params def as_sql(self, with_limits=True, with_col_aliases=False): """ Create the SQL for this query. Return the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ refcounts_before = self.query.alias_refcount.copy() try: combinator = self.query.combinator extra_select, order_by, group_by = self.pre_sql_setup( with_col_aliases=with_col_aliases or bool(combinator), ) for_update_part = None # Is a LIMIT/OFFSET clause needed? with_limit_offset = with_limits and self.query.is_sliced combinator = self.query.combinator features = self.connection.features if combinator: if not getattr(features, "supports_select_{}".format(combinator)): raise NotSupportedError( "{} is not supported on this database backend.".format( combinator ) ) result, params = self.get_combinator_sql( combinator, self.query.combinator_all ) elif self.qualify: result, params = self.get_qualify_sql() order_by = None else: distinct_fields, distinct_params = self.get_distinct() # This must come after 'select', 'ordering', and 'distinct' # (see docstring of get_from_clause() for details). from_, f_params = self.get_from_clause() try: where, w_params = ( self.compile(self.where) if self.where is not None else ("", []) ) except EmptyResultSet: if self.elide_empty: raise # Use a predicate that's always False. where, w_params = "0 = 1", [] except FullResultSet: where, w_params = "", [] try: having, h_params = ( self.compile(self.having) if self.having is not None else ("", []) ) except FullResultSet: having, h_params = "", [] result = ["SELECT"] params = [] if self.query.distinct: distinct_result, distinct_params = self.connection.ops.distinct_sql( distinct_fields, distinct_params, ) result += distinct_result params += distinct_params out_cols = [] for _, (s_sql, s_params), alias in self.select + extra_select: if alias: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name(alias), ) params.extend(s_params) out_cols.append(s_sql) result += [", ".join(out_cols)] if from_: result += ["FROM", *from_] elif self.connection.features.bare_select_suffix: result += [self.connection.features.bare_select_suffix] params.extend(f_params) if self.query.select_for_update and features.has_select_for_update: if ( self.connection.get_autocommit() # Don't raise an exception when database doesn't # support transactions, as it's a noop. and features.supports_transactions ): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." ) if ( with_limit_offset and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " "select_for_update on this database backend." ) nowait = self.query.select_for_update_nowait skip_locked = self.query.select_for_update_skip_locked of = self.query.select_for_update_of no_key = self.query.select_for_no_key_update # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." ) for_update_part = self.connection.ops.for_update_sql( nowait=nowait, skip_locked=skip_locked, of=self.get_select_for_update_of_arguments(), no_key=no_key, ) if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: result.append("WHERE %s" % where) params.extend(w_params) grouping = [] for g_sql, g_params in group_by: grouping.append(g_sql) params.extend(g_params) if grouping: if distinct_fields: raise NotImplementedError( "annotate() + distinct(fields) is not implemented." ) order_by = order_by or self.connection.ops.force_no_ordering() result.append("GROUP BY %s" % ", ".join(grouping)) if self._meta_ordering: order_by = None if having: result.append("HAVING %s" % having) params.extend(h_params) if self.query.explain_info: result.insert( 0, self.connection.ops.explain_query_prefix( self.query.explain_info.format, **self.query.explain_info.options, ), ) if order_by: ordering = [] for _, (o_sql, o_params, _) in order_by: ordering.append(o_sql) params.extend(o_params) order_by_sql = "ORDER BY %s" % ", ".join(ordering) if combinator and features.requires_compound_order_by_subquery: result = ["SELECT * FROM (", *result, ")", order_by_sql] else: result.append(order_by_sql) if with_limit_offset: result.append( self.connection.ops.limit_offset_sql( self.query.low_mark, self.query.high_mark ) ) if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: # If the query is used as a subquery, the extra selects would # result in more columns than the left-hand side expression is # expecting. This can happen when a subquery uses a combination # of order_by() and distinct(), forcing the ordering expressions # to be selected as well. Wrap the query in another subquery # to exclude extraneous selects. sub_selects = [] sub_params = [] for index, (select, _, alias) in enumerate(self.select, start=1): if alias: sub_selects.append( "%s.%s" % ( self.connection.ops.quote_name("subquery"), self.connection.ops.quote_name(alias), ) ) else: select_clone = select.relabeled_clone( {select.alias: "subquery"} ) subselect, subparams = select_clone.as_sql( self, self.connection ) sub_selects.append(subselect) sub_params.extend(subparams) return "SELECT %s FROM (%s) subquery" % ( ", ".join(sub_selects), " ".join(result), ), tuple(sub_params + params) return " ".join(result), tuple(params) finally: # Finally do cleanup - get rid of the joins we created above. self.query.reset_refcounts(refcounts_before) def get_default_columns( self, select_mask, start_alias=None, opts=None, from_parent=None ): """ Compute the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Return a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, return a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: if (opts := self.query.get_meta()) is None: return result start_alias = start_alias or self.query.get_initial_alias() # The 'seen_models' is used to optimize checking the needed parent # alias for a given field. This also includes None -> start_alias to # be used by local fields. seen_models = {None: start_alias} for field in opts.concrete_fields: model = field.model._meta.concrete_model # A proxy model will have a different model and concrete_model. We # will assign None if the field belongs to this model. if model == opts.model: model = None if ( from_parent and model is not None and issubclass( from_parent._meta.concrete_model, model._meta.concrete_model ) ): # Avoid loading data for already loaded parents. # We end up here in the case select_related() resolution # proceeds from parent model to child model. In that case the # parent model data is already present in the SELECT clause, # and we want to avoid reloading the same data again. continue if select_mask and field not in select_mask: continue alias = self.query.join_parent_model(opts, model, start_alias, seen_models) column = field.get_col(alias) result.append(column) return result def get_distinct(self): """ Return a quoted list of fields to use in DISTINCT ON part of the query. This method can alter the tables in the query, and thus it must be called before get_from_clause(). """ result = [] params = [] opts = self.query.get_meta() for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) _, targets, alias, joins, path, _, transform_function = self._setup_joins( parts, opts, None ) targets, alias, _ = self.query.trim_joins(targets, joins, path) for target in targets: if name in self.query.annotation_select: result.append(self.connection.ops.quote_name(name)) else: r, p = self.compile(transform_function(target, alias)) result.append(r) params.append(p) return result, params def find_ordering_name( self, name, opts, alias=None, default_order="ASC", already_seen=None ): """ Return the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) descending = order == "DESC" pieces = name.split(LOOKUP_SEP) ( field, targets, alias, joins, path, opts, transform_function, ) = self._setup_joins(pieces, opts, alias) # If we get to this point and the field is a relation to another model, # append the default ordering for that model unless it is the pk # shortcut or the attribute name of the field that is specified or # there are transforms to process. if ( field.is_relation and opts.ordering and getattr(field, "attname", None) != pieces[-1] and name != "pk" and not getattr(transform_function, "has_transforms", False) ): # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple( getattr(self.query.alias_map[j], "join_cols", None) for j in joins ) if join_tuple in already_seen: raise FieldError("Infinite loop caused by ordering.") already_seen.add(join_tuple) results = [] for item in opts.ordering: if hasattr(item, "resolve_expression") and not isinstance( item, OrderBy ): item = item.desc() if descending else item.asc() if isinstance(item, OrderBy): results.append( (item.prefix_references(f"{name}{LOOKUP_SEP}"), False) ) continue results.extend( (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref) for expr, is_ref in self.find_ordering_name( item, opts, alias, order, already_seen ) ) return results targets, alias, _ = self.query.trim_joins(targets, joins, path) return [ (OrderBy(transform_function(t, alias), descending=descending), False) for t in targets ] def _setup_joins(self, pieces, opts, alias): """ Helper method for get_order_by() and get_distinct(). get_ordering() and get_distinct() must produce same target columns on same input, as the prefixes of get_ordering() and get_distinct() must match. Executing SQL where this is not true is an error. """ alias = alias or self.query.get_initial_alias() field, targets, opts, joins, path, transform_function = self.query.setup_joins( pieces, opts, alias ) alias = joins[-1] return field, targets, alias, joins, path, opts, transform_function def get_from_clause(self): """ Return a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Subclasses, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables that are needed. This means the select columns, ordering, and distinct must be done first. """ result = [] params = [] for alias in tuple(self.query.alias_map): if not self.query.alias_refcount[alias]: continue try: from_clause = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue clause_sql, clause_params = self.compile(from_clause) result.append(clause_sql) params.extend(clause_params) for t in self.query.extra_tables: alias, _ = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # call increments the refcount, so an alias refcount of one means # this is the only reference). if ( alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1 ): result.append(", %s" % self.quote_name_unless_alias(alias)) return result, params def get_related_selections( self, select, select_mask, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, ): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ def _get_field_choices(): direct_choices = (f.name for f in opts.fields if f.is_relation) reverse_choices = ( f.field.related_query_name() for f in opts.related_objects if f.field.unique ) return chain( direct_choices, reverse_choices, self.query._filtered_relations ) related_klass_infos = [] if not restricted and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return related_klass_infos if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() # Setup for the case when only particular related fields should be # included in the related selection. fields_found = set() if requested is None: restricted = isinstance(self.query.select_related, dict) if restricted: requested = self.query.select_related def get_related_klass_infos(klass_info, related_klass_infos): klass_info["related_klass_infos"] = related_klass_infos for f in opts.fields: fields_found.add(f.name) if restricted: next = requested.get(f.name, {}) if not f.is_relation: # If a non-related field is used like a relation, # or if a single non-relational field is given. if next or f.name in requested: raise FieldError( "Non-relational field given in select_related: '%s'. " "Choices are: %s" % ( f.name, ", ".join(_get_field_choices()) or "(none)", ) ) else: next = False if not select_related_descend(f, restricted, requested, select_mask): continue related_select_mask = select_mask.get(f) or {} klass_info = { "model": f.remote_field.model, "field": f, "reverse": False, "local_setter": f.set_cached_value, "remote_setter": f.remote_field.set_cached_value if f.unique else lambda x, y: None, "from_parent": False, } related_klass_infos.append(klass_info) select_fields = [] _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias) alias = joins[-1] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=f.remote_field.model._meta ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_klass_infos = self.get_related_selections( select, related_select_mask, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) if restricted: related_fields = [ (o.field, o.related_model) for o in opts.related_objects if o.field.unique and not o.many_to_many ] for related_field, model in related_fields: related_select_mask = select_mask.get(related_field) or {} if not select_related_descend( related_field, restricted, requested, related_select_mask, reverse=True, ): continue related_field_name = related_field.related_query_name() fields_found.add(related_field_name) join_info = self.query.setup_joins( [related_field_name], opts, root_alias ) alias = join_info.joins[-1] from_parent = issubclass(model, opts.model) and model is not opts.model klass_info = { "model": model, "field": related_field, "reverse": True, "local_setter": related_field.remote_field.set_cached_value, "remote_setter": related_field.set_cached_value, "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next = requested.get(related_field.related_query_name(), {}) next_klass_infos = self.get_related_selections( select, related_select_mask, model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) def local_setter(final_field, obj, from_obj): # Set a reverse fk object when relation is non-empty. if from_obj: final_field.remote_field.set_cached_value(from_obj, obj) def local_setter_noop(obj, from_obj): pass def remote_setter(name, obj, from_obj): setattr(from_obj, name, obj) for name in list(requested): # Filtered relations work only on the topmost level. if cur_depth > 1: break if name in self.query._filtered_relations: fields_found.add(name) final_field, _, join_opts, joins, _, _ = self.query.setup_joins( [name], opts, root_alias ) model = join_opts.model alias = joins[-1] from_parent = ( issubclass(model, opts.model) and model is not opts.model ) klass_info = { "model": model, "field": final_field, "reverse": True, "local_setter": ( partial(local_setter, final_field) if len(joins) <= 2 else local_setter_noop ), "remote_setter": partial(remote_setter, name), "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] field_select_mask = select_mask.get((name, final_field)) or {} columns = self.get_default_columns( field_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_requested = requested.get(name, {}) next_klass_infos = self.get_related_selections( select, field_select_mask, opts=model._meta, root_alias=alias, cur_depth=cur_depth + 1, requested=next_requested, restricted=restricted, ) get_related_klass_infos(klass_info, next_klass_infos) fields_not_found = set(requested).difference(fields_found) if fields_not_found: invalid_fields = ("'%s'" % s for s in fields_not_found) raise FieldError( "Invalid field name(s) given in select_related: %s. " "Choices are: %s" % ( ", ".join(invalid_fields), ", ".join(_get_field_choices()) or "(none)", ) ) return related_klass_infos def get_select_for_update_of_arguments(self): """ Return a quoted list of arguments for the SELECT FOR UPDATE OF part of the query. """ def _get_parent_klass_info(klass_info): concrete_model = klass_info["model"]._meta.concrete_model for parent_model, parent_link in concrete_model._meta.parents.items(): parent_list = parent_model._meta.get_parent_list() yield { "model": parent_model, "field": parent_link, "reverse": False, "select_fields": [ select_index for select_index in klass_info["select_fields"] # Selected columns from a model or its parents. if ( self.select[select_index][0].target.model == parent_model or self.select[select_index][0].target.model in parent_list ) ], } def _get_first_selected_col_from_model(klass_info): """ Find the first selected column from a model. If it doesn't exist, don't lock a model. select_fields is filled recursively, so it also contains fields from the parent models. """ concrete_model = klass_info["model"]._meta.concrete_model for select_index in klass_info["select_fields"]: if self.select[select_index][0].target.model == concrete_model: return self.select[select_index][0] def _get_field_choices(): """Yield all allowed field paths in breadth-first search order.""" queue = collections.deque([(None, self.klass_info)]) while queue: parent_path, klass_info = queue.popleft() if parent_path is None: path = [] yield "self" else: field = klass_info["field"] if klass_info["reverse"]: field = field.remote_field path = parent_path + [field.name] yield LOOKUP_SEP.join(path) queue.extend( (path, klass_info) for klass_info in _get_parent_klass_info(klass_info) ) queue.extend( (path, klass_info) for klass_info in klass_info.get("related_klass_infos", []) ) if not self.klass_info: return [] result = [] invalid_names = [] for name in self.query.select_for_update_of: klass_info = self.klass_info if name == "self": col = _get_first_selected_col_from_model(klass_info) else: for part in name.split(LOOKUP_SEP): klass_infos = ( *klass_info.get("related_klass_infos", []), *_get_parent_klass_info(klass_info), ) for related_klass_info in klass_infos: field = related_klass_info["field"] if related_klass_info["reverse"]: field = field.remote_field if field.name == part: klass_info = related_klass_info break else: klass_info = None break if klass_info is None: invalid_names.append(name) continue col = _get_first_selected_col_from_model(klass_info) if col is not None: if self.connection.features.select_for_update_of_column: result.append(self.compile(col)[0]) else: result.append(self.quote_name_unless_alias(col.alias)) if invalid_names: raise FieldError( "Invalid field name(s) given in select_for_update(of=(...)): %s. " "Only relational fields followed in the query are allowed. " "Choices are: %s." % ( ", ".join(invalid_names), ", ".join(_get_field_choices()), ) ) return result def get_converters(self, expressions): converters = {} for i, expression in enumerate(expressions): if expression: backend_converters = self.connection.ops.get_db_converters(expression) field_converters = expression.get_db_converters(self.connection) if backend_converters or field_converters: converters[i] = (backend_converters + field_converters, expression) return converters def apply_converters(self, rows, converters): connection = self.connection converters = list(converters.items()) for row in map(list, rows): for pos, (convs, expression) in converters: value = row[pos] for converter in convs: value = converter(value, expression, connection) row[pos] = value yield row def results_iter( self, results=None, tuple_expected=False, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE, ): """Return an iterator over the results from executing this query.""" if results is None: results = self.execute_sql( MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size ) fields = [s[0] for s in self.select[0 : self.col_count]] converters = self.get_converters(fields) rows = chain.from_iterable(results) if converters: rows = self.apply_converters(rows, converters) if tuple_expected: rows = map(tuple, rows) return rows def has_results(self): """ Backends (e.g. NoSQL) can override this in order to use optimized versions of "query has any results." """ return bool(self.execute_sql(SINGLE)) def execute_sql( self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return iter([]) else: return if chunked_fetch: cursor = self.connection.chunked_cursor() else: cursor = self.connection.cursor() try: cursor.execute(sql, params) except Exception: # Might fail for server-side cursors (e.g. connection closed) cursor.close() raise if result_type == CURSOR: # Give the caller the cursor to process and close. return cursor if result_type == SINGLE: try: val = cursor.fetchone() if val: return val[0 : self.col_count] return val finally: # done with the cursor cursor.close() if result_type == NO_RESULTS: cursor.close() return result = cursor_iter( cursor, self.connection.features.empty_fetchmany_value, self.col_count if self.has_extra_select else None, chunk_size, ) if not chunked_fetch or not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. Use chunked_fetch if requested, # unless the database doesn't support it. return list(result) return result def as_subquery_condition(self, alias, columns, compiler): qn = compiler.quote_name_unless_alias qn2 = self.connection.ops.quote_name for index, select_col in enumerate(self.query.select): lhs_sql, lhs_params = self.compile(select_col) rhs = "%s.%s" % (qn(alias), qn2(columns[index])) self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND) sql, params = self.as_sql() return "EXISTS (%s)" % sql, params def explain_query(self): result = list(self.execute_sql()) # Some backends return 1 item tuples with strings, and others return # tuples with integers and strings. Flatten them out into strings. format_ = self.query.explain_info.format output_formatter = json.dumps if format_ and format_.lower() == "json" else str for row in result[0]: if not isinstance(row, str): yield " ".join(output_formatter(c) for c in row) else: yield row class SQLInsertCompiler(SQLCompiler): returning_fields = None returning_params = () def field_as_sql(self, field, val): """ Take a field and a value intended to be saved on that field, and return placeholder SQL and accompanying params. Check for raw values, expressions, and fields with get_placeholder() defined in that order. When field is None, consider the value raw and use it as the placeholder, with no corresponding parameters returned. """ if field is None: # A field value of None means the value is raw. sql, params = val, [] elif hasattr(val, "as_sql"): # This is an expression, let's compile it. sql, params = self.compile(val) elif hasattr(field, "get_placeholder"): # Some fields (e.g. geo fields) need special munging before # they can be inserted. sql, params = field.get_placeholder(val, self, self.connection), [val] else: # Return the common case for the placeholder sql, params = "%s", [val] # The following hook is only used by Oracle Spatial, which sometimes # needs to yield 'NULL' and [] as its placeholder and params instead # of '%s' and [None]. The 'NULL' placeholder is produced earlier by # OracleOperations.get_geom_placeholder(). The following line removes # the corresponding None parameter. See ticket #10888. params = self.connection.ops.modify_insert_params(sql, params) return sql, params def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, "resolve_expression"): value = value.resolve_expression( self.query, allow_joins=False, for_save=True ) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' "can only be used to update, not to insert." % (value, field) ) if value.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, value) ) if value.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query (%s=%r)." % (field.name, value) ) return field.get_db_prep_save(value, connection=self.connection) def pre_save_val(self, field, obj): """ Get the given field's value off the given obj. pre_save() is used for things like auto_now on DateTimeField. Skip it if this is a raw query. """ if self.query.raw: return getattr(obj, field.attname) return field.pre_save(obj, add=True) def assemble_as_sql(self, fields, value_rows): """ Take a sequence of N fields and a sequence of M rows of values, and generate placeholder SQL and parameters for each field and value. Return a pair containing: * a sequence of M rows of N SQL placeholder strings, and * a sequence of M rows of corresponding parameter values. Each placeholder string may contain any number of '%s' interpolation strings, and each parameter row will contain exactly as many params as the total number of '%s's in the corresponding placeholder row. """ if not value_rows: return [], [] # list of (sql, [params]) tuples for each object to be saved # Shape: [n_objs][n_fields][2] rows_of_fields_as_sql = ( (self.field_as_sql(field, v) for field, v in zip(fields, row)) for row in value_rows ) # tuple like ([sqls], [[params]s]) for each object to be saved # Shape: [n_objs][2][n_fields] sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql) # Extract separate lists for placeholders and params. # Each of these has shape [n_objs][n_fields] placeholder_rows, param_rows = zip(*sql_and_param_pair_rows) # Params for each field are still lists, and need to be flattened. param_rows = [[p for ps in row for p in ps] for row in param_rows] return placeholder_rows, param_rows def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.get_meta() insert_statement = self.connection.ops.insert_statement( on_conflict=self.query.on_conflict, ) result = ["%s %s" % (insert_statement, qn(opts.db_table))] fields = self.query.fields or [opts.pk] result.append("(%s)" % ", ".join(qn(f.column) for f in fields)) if self.query.fields: value_rows = [ [ self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields ] for obj in self.query.objs ] else: # An empty object. value_rows = [ [self.connection.ops.pk_default_value()] for _ in self.query.objs ] fields = [None] # Currently the backends just accept values when generating bulk # queries and generate their own placeholders. Doing that isn't # necessary and it should be possible to use placeholders and # expressions in bulk inserts too. can_bulk = ( not self.returning_fields and self.connection.features.has_bulk_insert ) placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows) on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql( fields, self.query.on_conflict, (f.column for f in self.query.update_fields), (f.column for f in self.query.unique_fields), ) if ( self.returning_fields and self.connection.features.can_return_columns_from_insert ): if self.connection.features.can_return_rows_from_bulk_insert: result.append( self.connection.ops.bulk_insert_sql(fields, placeholder_rows) ) params = param_rows else: result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) params = [param_rows[0]] if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) # Skip empty r_sql to allow subclasses to customize behavior for # 3rd party backends. Refs #19096. r_sql, self.returning_params = self.connection.ops.return_insert_columns( self.returning_fields ) if r_sql: result.append(r_sql) params += [self.returning_params] return [(" ".join(result), tuple(chain.from_iterable(params)))] if can_bulk: result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows)) if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [(" ".join(result), tuple(p for ps in param_rows for p in ps))] else: if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [ (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals) for p, vals in zip(placeholder_rows, param_rows) ] def execute_sql(self, returning_fields=None): assert not ( returning_fields and len(self.query.objs) != 1 and not self.connection.features.can_return_rows_from_bulk_insert ) opts = self.query.get_meta() self.returning_fields = returning_fields with self.connection.cursor() as cursor: for sql, params in self.as_sql(): cursor.execute(sql, params) if not self.returning_fields: return [] if ( self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1 ): rows = self.connection.ops.fetch_returned_insert_rows(cursor) elif self.connection.features.can_return_columns_from_insert: assert len(self.query.objs) == 1 rows = [ self.connection.ops.fetch_returned_insert_columns( cursor, self.returning_params, ) ] else: rows = [ ( self.connection.ops.last_insert_id( cursor, opts.db_table, opts.pk.column, ), ) ] cols = [field.get_col(opts.db_table) for field in self.returning_fields] converters = self.get_converters(cols) if converters: rows = list(self.apply_converters(rows, converters)) return rows class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): # Ensure base table is in aliases. self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 @classmethod def _expr_refs_base_model(cls, expr, base_model): if isinstance(expr, Query): return expr.model == base_model if not hasattr(expr, "get_source_expressions"): return False return any( cls._expr_refs_base_model(source_expr, base_model) for source_expr in expr.get_source_expressions() ) @cached_property def contains_self_reference_subquery(self): return any( self._expr_refs_base_model(expr, self.query.model) for expr in chain( self.query.annotations.values(), self.query.where.children ) ) def _as_sql(self, query): delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table) try: where, params = self.compile(query.where) except FullResultSet: return delete, () return f"{delete} WHERE {where}", tuple(params) def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ if self.single_alias and ( self.connection.features.delete_can_self_reference_subquery or not self.contains_self_reference_subquery ): return self._as_sql(self.query) innerq = self.query.clone() innerq.__class__ = Query innerq.clear_select_clause() pk = self.query.model._meta.pk innerq.select = [pk.get_col(self.query.get_initial_alias())] outerq = Query(self.query.model) if not self.connection.features.update_can_self_select: # Force the materialization of the inner query to allow reference # to the target table on MySQL. sql, params = innerq.get_compiler(connection=self.connection).as_sql() innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params) outerq.add_filter("pk__in", innerq) return self._as_sql(outerq) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ self.pre_sql_setup() if not self.query.values: return "", () qn = self.quote_name_unless_alias values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, "resolve_expression"): val = val.resolve_expression( self.query, allow_joins=False, for_save=True ) if val.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, val) ) if val.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query " "(%s=%r)." % (field.name, val) ) elif hasattr(val, "prepare_database_save"): if field.remote_field: val = val.prepare_database_save(field) else: raise TypeError( "Tried to update field %s with a model instance, %r. " "Use a value compatible with %s." % (field, val, field.__class__.__name__) ) val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, "get_placeholder"): placeholder = field.get_placeholder(val, self, self.connection) else: placeholder = "%s" name = field.column if hasattr(val, "as_sql"): sql, params = self.compile(val) values.append("%s = %s" % (qn(name), placeholder % sql)) update_params.extend(params) elif val is not None: values.append("%s = %s" % (qn(name), placeholder)) update_params.append(val) else: values.append("%s = NULL" % qn(name)) table = self.query.base_table result = [ "UPDATE %s SET" % qn(table), ", ".join(values), ] try: where, params = self.compile(self.query.where) except FullResultSet: params = [] else: result.append("WHERE %s" % where) return " ".join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, munge the "where" conditions to match the format required for (portable) SQL updates. If multiple updates are required, pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ refcounts_before = self.query.alias_refcount.copy() # Ensure base table is in the query self.query.get_initial_alias() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return query = self.query.chain(klass=Query) query.select_related = False query.clear_ordering(force=True) query.extra = {} query.select = [] meta = query.get_meta() fields = [meta.pk.name] related_ids_index = [] for related in self.query.related_updates: if all( path.join_field.primary_key for path in meta.get_path_to_parent(related) ): # If a primary key chain exists to the targeted related update, # then the meta.pk value can be used for it. related_ids_index.append((related, 0)) else: # This branch will only be reached when updating a field of an # ancestor that is not part of the primary key chain of a MTI # tree. related_ids_index.append((related, len(fields))) fields.append(related._meta.pk.name) query.add_fields(fields) super().pre_sql_setup() must_pre_select = ( count > 1 and not self.connection.features.update_can_self_select ) # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.clear_where() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] related_ids = collections.defaultdict(list) for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend(r[0] for r in rows) for parent, index in related_ids_index: related_ids[parent].extend(r[index] for r in rows) self.query.add_filter("pk__in", idents) self.query.related_ids = related_ids else: # The fast path. Filters and updates in one query. self.query.add_filter("pk__in", query) self.query.reset_refcounts(refcounts_before) class SQLAggregateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ sql, params = [], [] for annotation in self.query.annotation_select.values(): ann_sql, ann_params = self.compile(annotation) ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params) sql.append(ann_sql) params.extend(ann_params) self.col_count = len(self.query.annotation_select) sql = ", ".join(sql) params = tuple(params) inner_query_sql, inner_query_params = self.query.inner_query.get_compiler( self.using, elide_empty=self.elide_empty, ).as_sql(with_col_aliases=True) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) params += inner_query_params return sql, params def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close()
85c50b5f1f2f35d1f63fe9696e519626c2a33e6d7126a16a1258385fb4de5f5f
from django.db import DatabaseError, InterfaceError from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (19,) # Oracle crashes with "ORA-00932: inconsistent datatypes: expected - got # BLOB" when grouping by LOBs (#24096). allows_group_by_lob = False allows_group_by_select_index = False interprets_empty_strings_as_nulls = True has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_skip_locked = True has_select_for_update_of = True select_for_update_of_column = True can_return_columns_from_insert = True supports_subqueries_in_group_by = False ignores_unnecessary_order_by_in_subqueries = False supports_transactions = True supports_timezones = False has_native_duration_field = True can_defer_constraint_checks = True supports_partially_nullable_unique_constraints = False supports_deferrable_unique_constraints = True truncates_names = True supports_comments = True supports_tablespaces = True supports_sequence_reset = False can_introspect_materialized_views = True atomic_transactions = False nulls_order_largest = True requires_literal_defaults = True supports_default_keyword_in_bulk_insert = False closed_cursor_error_class = InterfaceError bare_select_suffix = " FROM DUAL" # Select for update with limit can be achieved on Oracle, but not with the # current backend. supports_select_for_update_with_limit = False supports_temporal_subtraction = True # Oracle doesn't ignore quoted identifiers case but the current backend # does by uppercasing all identifiers. ignores_table_name_case = True supports_index_on_text_field = False create_test_procedure_without_params_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" AS V_I INTEGER; BEGIN V_I := 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" (P_I INTEGER) AS V_I INTEGER; BEGIN V_I := P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 NUMBER(11) NOT NULL, column_2 NUMBER(11) NOT NULL, PRIMARY KEY (column_1, column_2) ) """ supports_callproc_kwargs = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_ignore_conflicts = False max_query_params = 2**16 - 1 supports_partial_indexes = False can_rename_index = True supports_slicing_ordering_in_compound = True requires_compound_order_by_subquery = True allows_multiple_constraints_on_same_fields = False supports_boolean_expr_in_select_clause = False supports_comparing_boolean_expr = False supports_primitives_in_json_field = False supports_json_field_contains = False supports_collation_on_textfield = False test_collations = { "ci": "BINARY_CI", "cs": "BINARY", "non_default": "SWEDISH_CI", "swedish_ci": "SWEDISH_CI", } test_now_utc_template = "CURRENT_TIMESTAMP AT TIME ZONE 'UTC'" django_test_skips = { "Oracle doesn't support SHA224.": { "db_functions.text.test_sha224.SHA224Tests.test_basic", "db_functions.text.test_sha224.SHA224Tests.test_transform", }, "Oracle doesn't correctly calculate ISO 8601 week numbering before " "1583 (the Gregorian calendar was introduced in 1582).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_trunc_week_before_1000", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_trunc_week_before_1000", }, "Oracle extracts seconds including fractional seconds (#33517).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_extract_second_func_no_fractional", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_extract_second_func_no_fractional", }, "Oracle doesn't support bitwise XOR.": { "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor", "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor_null", "expressions.tests.ExpressionOperatorTests." "test_lefthand_bitwise_xor_right_null", }, "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't.": { "expressions_window.tests.WindowFunctionTests.test_row_number_no_ordering", }, "Raises ORA-00600: internal error code.": { "model_fields.test_jsonfield.TestQuerying.test_usage_in_subquery", }, "Oracle doesn't support changing collations on indexed columns (#33671).": { "migrations.test_operations.OperationTests." "test_alter_field_pk_fk_db_collation", }, "Oracle doesn't support comparing NCLOB to NUMBER.": { "generic_relations_regress.tests.GenericRelationTests.test_textlink_filter", }, } django_test_expected_failures = { # A bug in Django/cx_Oracle with respect to string handling (#23843). "annotations.tests.NonAggregateAnnotationTestCase.test_custom_functions", "annotations.tests.NonAggregateAnnotationTestCase." "test_custom_functions_can_ref_other_functions", } insert_test_table_with_defaults = ( "INSERT INTO {} VALUES (DEFAULT, DEFAULT, DEFAULT)" ) @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "GenericIPAddressField": "CharField", "PositiveBigIntegerField": "BigIntegerField", "PositiveIntegerField": "IntegerField", "PositiveSmallIntegerField": "IntegerField", "SmallIntegerField": "IntegerField", "TimeField": "DateTimeField", } @cached_property def supports_collation_on_charfield(self): with self.connection.cursor() as cursor: try: cursor.execute("SELECT CAST('a' AS VARCHAR2(4001)) FROM dual") except DatabaseError as e: if e.args[0].code == 910: return False raise return True
2c60f14bb8e6db243c30390e387f49de7a18f9e390c772345afc8428f5530e12
from collections import namedtuple import cx_Oracle from django.db import models from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo as BaseTableInfo from django.utils.functional import cached_property FieldInfo = namedtuple( "FieldInfo", BaseFieldInfo._fields + ("is_autofield", "is_json", "comment") ) TableInfo = namedtuple("TableInfo", BaseTableInfo._fields + ("comment",)) class DatabaseIntrospection(BaseDatabaseIntrospection): cache_bust_counter = 1 # Maps type objects to Django Field types. @cached_property def data_types_reverse(self): if self.connection.cx_oracle_version < (8,): return { cx_Oracle.BLOB: "BinaryField", cx_Oracle.CLOB: "TextField", cx_Oracle.DATETIME: "DateField", cx_Oracle.FIXED_CHAR: "CharField", cx_Oracle.FIXED_NCHAR: "CharField", cx_Oracle.INTERVAL: "DurationField", cx_Oracle.NATIVE_FLOAT: "FloatField", cx_Oracle.NCHAR: "CharField", cx_Oracle.NCLOB: "TextField", cx_Oracle.NUMBER: "DecimalField", cx_Oracle.STRING: "CharField", cx_Oracle.TIMESTAMP: "DateTimeField", } else: return { cx_Oracle.DB_TYPE_DATE: "DateField", cx_Oracle.DB_TYPE_BINARY_DOUBLE: "FloatField", cx_Oracle.DB_TYPE_BLOB: "BinaryField", cx_Oracle.DB_TYPE_CHAR: "CharField", cx_Oracle.DB_TYPE_CLOB: "TextField", cx_Oracle.DB_TYPE_INTERVAL_DS: "DurationField", cx_Oracle.DB_TYPE_NCHAR: "CharField", cx_Oracle.DB_TYPE_NCLOB: "TextField", cx_Oracle.DB_TYPE_NVARCHAR: "CharField", cx_Oracle.DB_TYPE_NUMBER: "DecimalField", cx_Oracle.DB_TYPE_TIMESTAMP: "DateTimeField", cx_Oracle.DB_TYPE_VARCHAR: "CharField", } def get_field_type(self, data_type, description): if data_type == cx_Oracle.NUMBER: precision, scale = description[4:6] if scale == 0: if precision > 11: return ( "BigAutoField" if description.is_autofield else "BigIntegerField" ) elif 1 < precision < 6 and description.is_autofield: return "SmallAutoField" elif precision == 1: return "BooleanField" elif description.is_autofield: return "AutoField" else: return "IntegerField" elif scale == -127: return "FloatField" elif data_type == cx_Oracle.NCLOB and description.is_json: return "JSONField" return super().get_field_type(data_type, description) def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" cursor.execute( """ SELECT user_tables.table_name, 't', user_tab_comments.comments FROM user_tables LEFT OUTER JOIN user_tab_comments ON user_tab_comments.table_name = user_tables.table_name WHERE NOT EXISTS ( SELECT 1 FROM user_mviews WHERE user_mviews.mview_name = user_tables.table_name ) UNION ALL SELECT view_name, 'v', NULL FROM user_views UNION ALL SELECT mview_name, 'v', NULL FROM user_mviews """ ) return [ TableInfo(self.identifier_converter(row[0]), row[1], row[2]) for row in cursor.fetchall() ] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ # user_tab_columns gives data default for columns cursor.execute( """ SELECT user_tab_cols.column_name, user_tab_cols.data_default, CASE WHEN user_tab_cols.collation = user_tables.default_collation THEN NULL ELSE user_tab_cols.collation END collation, CASE WHEN user_tab_cols.char_used IS NULL THEN user_tab_cols.data_length ELSE user_tab_cols.char_length END as display_size, CASE WHEN user_tab_cols.identity_column = 'YES' THEN 1 ELSE 0 END as is_autofield, CASE WHEN EXISTS ( SELECT 1 FROM user_json_columns WHERE user_json_columns.table_name = user_tab_cols.table_name AND user_json_columns.column_name = user_tab_cols.column_name ) THEN 1 ELSE 0 END as is_json, user_col_comments.comments as col_comment FROM user_tab_cols LEFT OUTER JOIN user_tables ON user_tables.table_name = user_tab_cols.table_name LEFT OUTER JOIN user_col_comments ON user_col_comments.column_name = user_tab_cols.column_name AND user_col_comments.table_name = user_tab_cols.table_name WHERE user_tab_cols.table_name = UPPER(%s) """, [table_name], ) field_map = { column: ( display_size, default.rstrip() if default and default != "NULL" else None, collation, is_autofield, is_json, comment, ) for ( column, default, collation, display_size, is_autofield, is_json, comment, ) in cursor.fetchall() } self.cache_bust_counter += 1 cursor.execute( "SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format( self.connection.ops.quote_name(table_name), self.cache_bust_counter ) ) description = [] for desc in cursor.description: name = desc[0] ( display_size, default, collation, is_autofield, is_json, comment, ) = field_map[name] name %= {} # cx_Oracle, for some reason, doubles percent signs. description.append( FieldInfo( self.identifier_converter(name), desc[1], display_size, desc[3], desc[4] or 0, desc[5] or 0, *desc[6:], default, collation, is_autofield, is_json, comment, ) ) return description def identifier_converter(self, name): """Identifier comparison is case insensitive under Oracle.""" return name.lower() def get_sequences(self, cursor, table_name, table_fields=()): cursor.execute( """ SELECT user_tab_identity_cols.sequence_name, user_tab_identity_cols.column_name FROM user_tab_identity_cols, user_constraints, user_cons_columns cols WHERE user_constraints.constraint_name = cols.constraint_name AND user_constraints.table_name = user_tab_identity_cols.table_name AND cols.column_name = user_tab_identity_cols.column_name AND user_constraints.constraint_type = 'P' AND user_tab_identity_cols.table_name = UPPER(%s) """, [table_name], ) # Oracle allows only one identity column per table. row = cursor.fetchone() if row: return [ { "name": self.identifier_converter(row[0]), "table": self.identifier_converter(table_name), "column": self.identifier_converter(row[1]), } ] # To keep backward compatibility for AutoFields that aren't Oracle # identity columns. for f in table_fields: if isinstance(f, models.AutoField): return [{"table": table_name, "column": f.column}] return [] def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all foreign keys in the given table. """ table_name = table_name.upper() cursor.execute( """ SELECT ca.column_name, cb.table_name, cb.column_name FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb WHERE user_constraints.table_name = %s AND user_constraints.constraint_name = ca.constraint_name AND user_constraints.r_constraint_name = cb.constraint_name AND ca.position = cb.position""", [table_name], ) return { self.identifier_converter(field_name): ( self.identifier_converter(rel_field_name), self.identifier_converter(rel_table_name), ) for field_name, rel_table_name, rel_field_name in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( """ SELECT cols.column_name FROM user_constraints, user_cons_columns cols WHERE user_constraints.constraint_name = cols.constraint_name AND user_constraints.constraint_type = 'P' AND user_constraints.table_name = UPPER(%s) ORDER BY cols.position """, [table_name], ) return [self.identifier_converter(row[0]) for row in cursor.fetchall()] def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the constraints, getting PKs, uniques, and checks cursor.execute( """ SELECT user_constraints.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), CASE user_constraints.constraint_type WHEN 'P' THEN 1 ELSE 0 END AS is_primary_key, CASE WHEN user_constraints.constraint_type IN ('P', 'U') THEN 1 ELSE 0 END AS is_unique, CASE user_constraints.constraint_type WHEN 'C' THEN 1 ELSE 0 END AS is_check_constraint FROM user_constraints LEFT OUTER JOIN user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name WHERE user_constraints.constraint_type = ANY('P', 'U', 'C') AND user_constraints.table_name = UPPER(%s) GROUP BY user_constraints.constraint_name, user_constraints.constraint_type """, [table_name], ) for constraint, columns, pk, unique, check in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "columns": columns.split(","), "primary_key": pk, "unique": unique, "foreign_key": None, "check": check, "index": unique, # All uniques come with an index } # Foreign key constraints cursor.execute( """ SELECT cons.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), LOWER(rcols.table_name), LOWER(rcols.column_name) FROM user_constraints cons INNER JOIN user_cons_columns rcols ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1 LEFT OUTER JOIN user_cons_columns cols ON cons.constraint_name = cols.constraint_name WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) GROUP BY cons.constraint_name, rcols.table_name, rcols.column_name """, [table_name], ) for constraint, columns, other_table, other_column in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "primary_key": False, "unique": False, "foreign_key": (other_table, other_column), "check": False, "index": False, "columns": columns.split(","), } # Now get indexes cursor.execute( """ SELECT ind.index_name, LOWER(ind.index_type), LOWER(ind.uniqueness), LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.column_position), LISTAGG(cols.descend, ',') WITHIN GROUP (ORDER BY cols.column_position) FROM user_ind_columns cols, user_indexes ind WHERE cols.table_name = UPPER(%s) AND NOT EXISTS ( SELECT 1 FROM user_constraints cons WHERE ind.index_name = cons.index_name ) AND cols.index_name = ind.index_name GROUP BY ind.index_name, ind.index_type, ind.uniqueness """, [table_name], ) for constraint, type_, unique, columns, orders in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "primary_key": False, "unique": unique == "unique", "foreign_key": None, "check": False, "index": True, "type": "idx" if type_ == "normal" else type_, "columns": columns.split(","), "orders": orders.split(","), } return constraints
f50e3c90e1009ba7fc7873b8b589846506ece90445f2a7f10b7b7d1066cf985a
import datetime import uuid from functools import lru_cache from django.conf import settings from django.db import DatabaseError, NotSupportedError from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import split_tzname_delta, strip_quotes, truncate_name from django.db.models import AutoField, Exists, ExpressionWrapper, Lookup from django.db.models.expressions import RawSQL from django.db.models.sql.where import WhereNode from django.utils import timezone from django.utils.encoding import force_bytes, force_str from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from .base import Database from .utils import BulkInsertMapper, InsertVar, Oracle_datetime class DatabaseOperations(BaseDatabaseOperations): # Oracle uses NUMBER(5), NUMBER(11), and NUMBER(19) for integer fields. # SmallIntegerField uses NUMBER(11) instead of NUMBER(5), which is used by # SmallAutoField, to preserve backward compatibility. integer_field_ranges = { "SmallIntegerField": (-99999999999, 99999999999), "IntegerField": (-99999999999, 99999999999), "BigIntegerField": (-9999999999999999999, 9999999999999999999), "PositiveBigIntegerField": (0, 9999999999999999999), "PositiveSmallIntegerField": (0, 99999999999), "PositiveIntegerField": (0, 99999999999), "SmallAutoField": (-99999, 99999), "AutoField": (-99999999999, 99999999999), "BigAutoField": (-9999999999999999999, 9999999999999999999), } set_operators = {**BaseDatabaseOperations.set_operators, "difference": "MINUS"} # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc. _sequence_reset_sql = """ DECLARE table_value integer; seq_value integer; seq_name user_tab_identity_cols.sequence_name%%TYPE; BEGIN BEGIN SELECT sequence_name INTO seq_name FROM user_tab_identity_cols WHERE table_name = '%(table_name)s' AND column_name = '%(column_name)s'; EXCEPTION WHEN NO_DATA_FOUND THEN seq_name := '%(no_autofield_sequence_name)s'; END; SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s; SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences WHERE sequence_name = seq_name; WHILE table_value > seq_value LOOP EXECUTE IMMEDIATE 'SELECT "'||seq_name||'".nextval FROM DUAL' INTO seq_value; END LOOP; END; /""" # Oracle doesn't support string without precision; use the max string size. cast_char_field_without_max_length = "NVARCHAR2(2000)" cast_data_types = { "AutoField": "NUMBER(11)", "BigAutoField": "NUMBER(19)", "SmallAutoField": "NUMBER(5)", "TextField": cast_char_field_without_max_length, } def cache_key_culling_sql(self): cache_key = self.quote_name("cache_key") return ( f"SELECT {cache_key} " f"FROM %s " f"ORDER BY {cache_key} OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY" ) # EXTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): extract_sql = f"TO_CHAR({sql}, %s)" extract_param = None if lookup_type == "week_day": # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. extract_param = "D" elif lookup_type == "iso_week_day": extract_sql = f"TO_CHAR({sql} - 1, %s)" extract_param = "D" elif lookup_type == "week": # IW = ISO week number extract_param = "IW" elif lookup_type == "quarter": extract_param = "Q" elif lookup_type == "iso_year": extract_param = "IYYY" else: lookup_type = lookup_type.upper() if not self._extract_format_re.fullmatch(lookup_type): raise ValueError(f"Invalid loookup type: {lookup_type!r}") # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/EXTRACT-datetime.html return f"EXTRACT({lookup_type} FROM {sql})", params return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html trunc_param = None if lookup_type in ("year", "month"): trunc_param = lookup_type.upper() elif lookup_type == "quarter": trunc_param = "Q" elif lookup_type == "week": trunc_param = "IW" else: return f"TRUNC({sql})", params return f"TRUNC({sql}, %s)", (*params, trunc_param) # Oracle crashes with "ORA-03113: end-of-file on communication channel" # if the time zone name is passed in parameter. Use interpolation instead. # https://groups.google.com/forum/#!msg/django-developers/zwQju7hbG78/9l934yelwfsJ # This regexp matches all time zone names from the zoneinfo database. _tzname_re = _lazy_re_compile(r"^[\w/:+-]+$") def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname): raise ValueError("Invalid time zone name: %s" % tzname) # Convert from connection timezone to the local time, returning # TIMESTAMP WITH TIME ZONE and cast it back to TIMESTAMP to strip the # TIME ZONE details. if self.connection.timezone_name != tzname: from_timezone_name = self.connection.timezone_name to_timezone_name = self._prepare_tzname_delta(tzname) return ( f"CAST((FROM_TZ({sql}, '{from_timezone_name}') AT TIME ZONE " f"'{to_timezone_name}') AS TIMESTAMP)", params, ) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP change to the # default date and convert the field to the specified timezone. sql, params = self._convert_sql_to_tz(sql, params, tzname) convert_datetime_sql = ( f"TO_TIMESTAMP(CONCAT('1900-01-01 ', TO_CHAR({sql}, 'HH24:MI:SS.FF')), " f"'YYYY-MM-DD HH24:MI:SS.FF')" ) return ( f"CASE WHEN {sql} IS NOT NULL THEN {convert_datetime_sql} ELSE NULL END", (*params, *params), ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html trunc_param = None if lookup_type in ("year", "month"): trunc_param = lookup_type.upper() elif lookup_type == "quarter": trunc_param = "Q" elif lookup_type == "week": trunc_param = "IW" elif lookup_type == "hour": trunc_param = "HH24" elif lookup_type == "minute": trunc_param = "MI" elif lookup_type == "day": return f"TRUNC({sql})", params else: # Cast to DATE removes sub-second precision. return f"CAST({sql} AS DATE)", params return f"TRUNC({sql}, %s)", (*params, trunc_param) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_sql_to_tz(sql, params, tzname) trunc_param = None if lookup_type == "hour": trunc_param = "HH24" elif lookup_type == "minute": trunc_param = "MI" elif lookup_type == "second": # Cast to DATE removes sub-second precision. return f"CAST({sql} AS DATE)", params return f"TRUNC({sql}, %s)", (*params, trunc_param) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type in ["JSONField", "TextField"]: converters.append(self.convert_textfield_value) elif internal_type == "BinaryField": converters.append(self.convert_binaryfield_value) elif internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) elif internal_type == "DateTimeField": if settings.USE_TZ: converters.append(self.convert_datetimefield_value) elif internal_type == "DateField": converters.append(self.convert_datefield_value) elif internal_type == "TimeField": converters.append(self.convert_timefield_value) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) # Oracle stores empty strings as null. If the field accepts the empty # string, undo this to adhere to the Django convention of using # the empty string instead of null. if expression.output_field.empty_strings_allowed: converters.append( self.convert_empty_bytes if internal_type == "BinaryField" else self.convert_empty_string ) return converters def convert_textfield_value(self, value, expression, connection): if isinstance(value, Database.LOB): value = value.read() return value def convert_binaryfield_value(self, value, expression, connection): if isinstance(value, Database.LOB): value = force_bytes(value.read()) return value def convert_booleanfield_value(self, value, expression, connection): if value in (0, 1): value = bool(value) return value # cx_Oracle always returns datetime.datetime objects for # DATE and TIMESTAMP columns, but Django wants to see a # python datetime.date, .time, or .datetime. def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) return value def convert_datefield_value(self, value, expression, connection): if isinstance(value, Database.Timestamp): value = value.date() return value def convert_timefield_value(self, value, expression, connection): if isinstance(value, Database.Timestamp): value = value.time() return value def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value @staticmethod def convert_empty_string(value, expression, connection): return "" if value is None else value @staticmethod def convert_empty_bytes(value, expression, connection): return b"" if value is None else value def deferrable_sql(self): return " DEFERRABLE INITIALLY DEFERRED" def fetch_returned_insert_columns(self, cursor, returning_params): columns = [] for param in returning_params: value = param.get_value() if value == []: raise DatabaseError( "The database did not return a new row id. Probably " '"ORA-1403: no data found" was raised internally but was ' "hidden by the Oracle OCI library (see " "https://code.djangoproject.com/ticket/28859)." ) columns.append(value[0]) return tuple(columns) def no_limit_value(self): return None def limit_offset_sql(self, low_mark, high_mark): fetch, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( ("OFFSET %d ROWS" % offset) if offset else None, ("FETCH FIRST %d ROWS ONLY" % fetch) if fetch else None, ) if sql ) def last_executed_query(self, cursor, sql, params): # https://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html#Cursor.statement # The DB API definition does not define this attribute. statement = cursor.statement # Unlike Psycopg's `query` and MySQLdb`'s `_executed`, cx_Oracle's # `statement` doesn't contain the query parameters. Substitute # parameters manually. if params: if isinstance(params, (tuple, list)): params = { f":arg{i}": param for i, param in enumerate(dict.fromkeys(params)) } elif isinstance(params, dict): params = {f":{key}": val for (key, val) in params.items()} for key in sorted(params, key=len, reverse=True): statement = statement.replace( key, force_str(params[key], errors="replace") ) return statement def last_insert_id(self, cursor, table_name, pk_name): sq_name = self._get_sequence_name(cursor, strip_quotes(table_name), pk_name) cursor.execute('"%s".currval' % sq_name) return cursor.fetchone()[0] def lookup_cast(self, lookup_type, internal_type=None): if lookup_type in ("iexact", "icontains", "istartswith", "iendswith"): return "UPPER(%s)" if ( lookup_type != "isnull" and internal_type in ("BinaryField", "TextField") ) or (lookup_type == "exact" and internal_type == "JSONField"): return "DBMS_LOB.SUBSTR(%s)" return "%s" def max_in_list_size(self): return 1000 def max_name_length(self): return 30 def pk_default_value(self): return "NULL" def prep_for_iexact_query(self, x): return x def process_clob(self, value): if value is None: return "" return value.read() def quote_name(self, name): # SQL92 requires delimited (quoted) names to be case-sensitive. When # not quoted, Oracle has case-insensitive behavior for identifiers, but # always defaults to uppercase. # We simplify things by making Oracle identifiers always uppercase. if not name.startswith('"') and not name.endswith('"'): name = '"%s"' % truncate_name(name, self.max_name_length()) # Oracle puts the query text into a (query % args) construct, so % signs # in names need to be escaped. The '%%' will be collapsed back to '%' at # that stage so we aren't really making the name longer here. name = name.replace("%", "%%") return name.upper() def regex_lookup(self, lookup_type): if lookup_type == "regex": match_option = "'c'" else: match_option = "'i'" return "REGEXP_LIKE(%%s, %%s, %s)" % match_option def return_insert_columns(self, fields): if not fields: return "", () field_names = [] params = [] for field in fields: field_names.append( "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) ) params.append(InsertVar(field)) return "RETURNING %s INTO %s" % ( ", ".join(field_names), ", ".join(["%s"] * len(params)), ), tuple(params) def __foreign_key_constraints(self, table_name, recursive): with self.connection.cursor() as cursor: if recursive: cursor.execute( """ SELECT user_tables.table_name, rcons.constraint_name FROM user_tables JOIN user_constraints cons ON (user_tables.table_name = cons.table_name AND cons.constraint_type = ANY('P', 'U')) LEFT JOIN user_constraints rcons ON (user_tables.table_name = rcons.table_name AND rcons.constraint_type = 'R') START WITH user_tables.table_name = UPPER(%s) CONNECT BY NOCYCLE PRIOR cons.constraint_name = rcons.r_constraint_name GROUP BY user_tables.table_name, rcons.constraint_name HAVING user_tables.table_name != UPPER(%s) ORDER BY MAX(level) DESC """, (table_name, table_name), ) else: cursor.execute( """ SELECT cons.table_name, cons.constraint_name FROM user_constraints cons WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) """, (table_name,), ) return cursor.fetchall() @cached_property def _foreign_key_constraints(self): # 512 is large enough to fit the ~330 tables (as of this writing) in # Django's test suite. return lru_cache(maxsize=512)(self.__foreign_key_constraints) def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] truncated_tables = {table.upper() for table in tables} constraints = set() # Oracle's TRUNCATE CASCADE only works with ON DELETE CASCADE foreign # keys which Django doesn't define. Emulate the PostgreSQL behavior # which truncates all dependent tables by manually retrieving all # foreign key constraints and resolving dependencies. for table in tables: for foreign_table, constraint in self._foreign_key_constraints( table, recursive=allow_cascade ): if allow_cascade: truncated_tables.add(foreign_table) constraints.add((foreign_table, constraint)) sql = ( [ "%s %s %s %s %s %s %s %s;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), style.SQL_KEYWORD("DISABLE"), style.SQL_KEYWORD("CONSTRAINT"), style.SQL_FIELD(self.quote_name(constraint)), style.SQL_KEYWORD("KEEP"), style.SQL_KEYWORD("INDEX"), ) for table, constraint in constraints ] + [ "%s %s %s;" % ( style.SQL_KEYWORD("TRUNCATE"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), ) for table in truncated_tables ] + [ "%s %s %s %s %s %s;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), style.SQL_KEYWORD("ENABLE"), style.SQL_KEYWORD("CONSTRAINT"), style.SQL_FIELD(self.quote_name(constraint)), ) for table, constraint in constraints ] ) if reset_sequences: sequences = [ sequence for sequence in self.connection.introspection.sequence_list() if sequence["table"].upper() in truncated_tables ] # Since we've just deleted all the rows, running our sequence ALTER # code will reset the sequence to 0. sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql def sequence_reset_by_name_sql(self, style, sequences): sql = [] for sequence_info in sequences: no_autofield_sequence_name = self._get_no_autofield_sequence_name( sequence_info["table"] ) table = self.quote_name(sequence_info["table"]) column = self.quote_name(sequence_info["column"] or "id") query = self._sequence_reset_sql % { "no_autofield_sequence_name": no_autofield_sequence_name, "table": table, "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), } sql.append(query) return sql def sequence_reset_sql(self, style, model_list): output = [] query = self._sequence_reset_sql for model in model_list: for f in model._meta.local_fields: if isinstance(f, AutoField): no_autofield_sequence_name = self._get_no_autofield_sequence_name( model._meta.db_table ) table = self.quote_name(model._meta.db_table) column = self.quote_name(f.column) output.append( query % { "no_autofield_sequence_name": no_autofield_sequence_name, "table": table, "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), } ) # Only one AutoField is allowed per model, so don't # continue to loop break return output def start_transaction_sql(self): return "" def tablespace_sql(self, tablespace, inline=False): if inline: return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace) else: return "TABLESPACE %s" % self.quote_name(tablespace) def adapt_datefield_value(self, value): """ Transform a date value to an object compatible with what is expected by the backend driver for date columns. The default implementation transforms the date to text, but that is not necessary for Oracle. """ return value def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ is True passed datetime is timezone aware. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # cx_Oracle doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "Oracle backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return Oracle_datetime.from_datetime(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value if isinstance(value, str): return datetime.datetime.strptime(value, "%H:%M:%S") # Oracle doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("Oracle backend does not support timezone-aware times.") return Oracle_datetime( 1900, 1, 1, value.hour, value.minute, value.second, value.microsecond ) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def combine_expression(self, connector, sub_expressions): lhs, rhs = sub_expressions if connector == "%%": return "MOD(%s)" % ",".join(sub_expressions) elif connector == "&": return "BITAND(%s)" % ",".join(sub_expressions) elif connector == "|": return "BITAND(-%(lhs)s-1,%(rhs)s)+%(lhs)s" % {"lhs": lhs, "rhs": rhs} elif connector == "<<": return "(%(lhs)s * POWER(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} elif connector == ">>": return "FLOOR(%(lhs)s / POWER(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} elif connector == "^": return "POWER(%s)" % ",".join(sub_expressions) elif connector == "#": raise NotSupportedError("Bitwise XOR is not supported in Oracle.") return super().combine_expression(connector, sub_expressions) def _get_no_autofield_sequence_name(self, table): """ Manually created sequence name to keep backward compatibility for AutoFields that aren't Oracle identity columns. """ name_length = self.max_name_length() - 3 return "%s_SQ" % truncate_name(strip_quotes(table), name_length).upper() def _get_sequence_name(self, cursor, table, pk_name): cursor.execute( """ SELECT sequence_name FROM user_tab_identity_cols WHERE table_name = UPPER(%s) AND column_name = UPPER(%s)""", [table, pk_name], ) row = cursor.fetchone() return self._get_no_autofield_sequence_name(table) if row is None else row[0] def bulk_insert_sql(self, fields, placeholder_rows): query = [] for row in placeholder_rows: select = [] for i, placeholder in enumerate(row): # A model without any fields has fields=[None]. if fields[i]: internal_type = getattr( fields[i], "target_field", fields[i] ).get_internal_type() placeholder = ( BulkInsertMapper.types.get(internal_type, "%s") % placeholder ) # Add columns aliases to the first select to avoid "ORA-00918: # column ambiguously defined" when two or more columns in the # first select have the same value. if not query: placeholder = "%s col_%s" % (placeholder, i) select.append(placeholder) query.append("SELECT %s FROM DUAL" % ", ".join(select)) # Bulk insert to tables with Oracle identity columns causes Oracle to # add sequence.nextval to it. Sequence.nextval cannot be used with the # UNION operator. To prevent incorrect SQL, move UNION to a subquery. return "SELECT * FROM (%s)" % " UNION ALL ".join(query) def subtract_temporals(self, internal_type, lhs, rhs): if internal_type == "DateField": lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) return ( "NUMTODSINTERVAL(TO_NUMBER(%s - %s), 'DAY')" % (lhs_sql, rhs_sql), params, ) return super().subtract_temporals(internal_type, lhs, rhs) def bulk_batch_size(self, fields, objs): """Oracle restricts the number of parameters in a query.""" if fields: return self.connection.features.max_query_params // len(fields) return len(objs) def conditional_expression_supported_in_where_clause(self, expression): """ Oracle supports only EXISTS(...) or filters in the WHERE clause, others must be compared with True. """ if isinstance(expression, (Exists, Lookup, WhereNode)): return True if isinstance(expression, ExpressionWrapper) and expression.conditional: return self.conditional_expression_supported_in_where_clause( expression.expression ) if isinstance(expression, RawSQL) and expression.conditional: return True return False
7b2635ccadb51fbda9176d1d838541c7fed9a42cf4e28af9b1d2d7a9efed07a8
import copy import datetime import re from django.db import DatabaseError from django.db.backends.base.schema import ( BaseDatabaseSchemaEditor, _related_non_m2m_objects, ) from django.utils.duration import duration_iso_string class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_create_column = "ALTER TABLE %(table)s ADD %(column)s %(definition)s" sql_alter_column_type = "MODIFY %(column)s %(type)s%(collation)s" sql_alter_column_null = "MODIFY %(column)s NULL" sql_alter_column_not_null = "MODIFY %(column)s NOT NULL" sql_alter_column_default = "MODIFY %(column)s DEFAULT %(default)s" sql_alter_column_no_default = "MODIFY %(column)s DEFAULT NULL" sql_alter_column_no_default_null = sql_alter_column_no_default sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s" sql_create_column_inline_fk = ( "CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(deferrable)s" ) sql_delete_table = "DROP TABLE %(table)s CASCADE CONSTRAINTS" sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" def quote_value(self, value): if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): return "'%s'" % value elif isinstance(value, datetime.timedelta): return "'%s'" % duration_iso_string(value) elif isinstance(value, str): return "'%s'" % value.replace("'", "''") elif isinstance(value, (bytes, bytearray, memoryview)): return "'%s'" % value.hex() elif isinstance(value, bool): return "1" if value else "0" else: return str(value) def remove_field(self, model, field): # If the column is an identity column, drop the identity before # removing the field. if self._is_identity_column(model._meta.db_table, field.column): self._drop_identity(model._meta.db_table, field.column) super().remove_field(model, field) def delete_model(self, model): # Run superclass action super().delete_model(model) # Clean up manually created sequence. self.execute( """ DECLARE i INTEGER; BEGIN SELECT COUNT(1) INTO i FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '%(sq_name)s'; IF i = 1 THEN EXECUTE IMMEDIATE 'DROP SEQUENCE "%(sq_name)s"'; END IF; END; /""" % { "sq_name": self.connection.ops._get_no_autofield_sequence_name( model._meta.db_table ) } ) def alter_field(self, model, old_field, new_field, strict=False): try: super().alter_field(model, old_field, new_field, strict) except DatabaseError as e: description = str(e) # If we're changing type to an unsupported type we need a # SQLite-ish workaround if "ORA-22858" in description or "ORA-22859" in description: self._alter_field_type_workaround(model, old_field, new_field) # If an identity column is changing to a non-numeric type, drop the # identity first. elif "ORA-30675" in description: self._drop_identity(model._meta.db_table, old_field.column) self.alter_field(model, old_field, new_field, strict) # If a primary key column is changing to an identity column, drop # the primary key first. elif "ORA-30673" in description and old_field.primary_key: self._delete_primary_key(model, strict=True) self._alter_field_type_workaround(model, old_field, new_field) # If a collation is changing on a primary key, drop the primary key # first. elif "ORA-43923" in description and old_field.primary_key: self._delete_primary_key(model, strict=True) self.alter_field(model, old_field, new_field, strict) # Restore a primary key, if needed. if new_field.primary_key: self.execute(self._create_primary_key_sql(model, new_field)) else: raise def _alter_field_type_workaround(self, model, old_field, new_field): """ Oracle refuses to change from some type to other type. What we need to do instead is: - Add a nullable version of the desired field with a temporary name. If the new column is an auto field, then the temporary column can't be nullable. - Update the table to transfer values from old to new - Drop old column - Rename the new column and possibly drop the nullable property """ # Make a new field that's like the new one but with a temporary # column name. new_temp_field = copy.deepcopy(new_field) new_temp_field.null = new_field.get_internal_type() not in ( "AutoField", "BigAutoField", "SmallAutoField", ) new_temp_field.column = self._generate_temp_name(new_field.column) # Add it self.add_field(model, new_temp_field) # Explicit data type conversion # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf # /Data-Type-Comparison-Rules.html#GUID-D0C5A47E-6F93-4C2D-9E49-4F2B86B359DD new_value = self.quote_name(old_field.column) old_type = old_field.db_type(self.connection) if re.match("^N?CLOB", old_type): new_value = "TO_CHAR(%s)" % new_value old_type = "VARCHAR2" if re.match("^N?VARCHAR2", old_type): new_internal_type = new_field.get_internal_type() if new_internal_type == "DateField": new_value = "TO_DATE(%s, 'YYYY-MM-DD')" % new_value elif new_internal_type == "DateTimeField": new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value elif new_internal_type == "TimeField": # TimeField are stored as TIMESTAMP with a 1900-01-01 date part. new_value = "CONCAT('1900-01-01 ', %s)" % new_value new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value # Transfer values across self.execute( "UPDATE %s set %s=%s" % ( self.quote_name(model._meta.db_table), self.quote_name(new_temp_field.column), new_value, ) ) # Drop the old field self.remove_field(model, old_field) # Rename and possibly make the new field NOT NULL super().alter_field(model, new_temp_field, new_field) # Recreate foreign key (if necessary) because the old field is not # passed to the alter_field() and data types of new_temp_field and # new_field always match. new_type = new_field.db_type(self.connection) if ( (old_field.primary_key and new_field.primary_key) or (old_field.unique and new_field.unique) ) and old_type != new_type: for _, rel in _related_non_m2m_objects(new_temp_field, new_field): if rel.field.db_constraint: self.execute( self._create_fk_sql(rel.related_model, rel.field, "_fk") ) def _alter_column_type_sql( self, model, old_field, new_field, new_type, old_collation, new_collation ): auto_field_types = {"AutoField", "BigAutoField", "SmallAutoField"} # Drop the identity if migrating away from AutoField. if ( old_field.get_internal_type() in auto_field_types and new_field.get_internal_type() not in auto_field_types and self._is_identity_column(model._meta.db_table, new_field.column) ): self._drop_identity(model._meta.db_table, new_field.column) return super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) def normalize_name(self, name): """ Get the properly shortened and uppercased identifier as returned by quote_name() but without the quotes. """ nn = self.quote_name(name) if nn[0] == '"' and nn[-1] == '"': nn = nn[1:-1] return nn def _generate_temp_name(self, for_name): """Generate temporary names for workarounds that need temp columns.""" suffix = hex(hash(for_name)).upper()[1:] return self.normalize_name(for_name + "_" + suffix) def prepare_default(self, value): # Replace % with %% as %-formatting is applied in # FormatStylePlaceholderCursor._fix_for_params(). return self.quote_value(value).replace("%", "%%") def _field_should_be_indexed(self, model, field): create_index = super()._field_should_be_indexed(model, field) db_type = field.db_type(self.connection) if ( db_type is not None and db_type.lower() in self.connection._limited_data_types ): return False return create_index def _is_identity_column(self, table_name, column_name): with self.connection.cursor() as cursor: cursor.execute( """ SELECT CASE WHEN identity_column = 'YES' THEN 1 ELSE 0 END FROM user_tab_cols WHERE table_name = %s AND column_name = %s """, [self.normalize_name(table_name), self.normalize_name(column_name)], ) row = cursor.fetchone() return row[0] if row else False def _drop_identity(self, table_name, column_name): self.execute( "ALTER TABLE %(table)s MODIFY %(column)s DROP IDENTITY" % { "table": self.quote_name(table_name), "column": self.quote_name(column_name), } ) def _get_default_collation(self, table_name): with self.connection.cursor() as cursor: cursor.execute( """ SELECT default_collation FROM user_tables WHERE table_name = %s """, [self.normalize_name(table_name)], ) return cursor.fetchone()[0] def _collate_sql(self, collation, old_collation=None, table_name=None): if collation is None and old_collation is not None: collation = self._get_default_collation(table_name) return super()._collate_sql(collation, old_collation, table_name)